text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataFactory.Models
{
    public partial class AzureMLExecutePipelineActivity : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(LinkedServiceName))
            {
                writer.WritePropertyName("linkedServiceName");
                writer.WriteObjectValue(LinkedServiceName);
            }
            if (Optional.IsDefined(Policy))
            {
                writer.WritePropertyName("policy");
                writer.WriteObjectValue(Policy);
            }
            writer.WritePropertyName("name");
            writer.WriteStringValue(Name);
            writer.WritePropertyName("type");
            writer.WriteStringValue(ActivityType);
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (Optional.IsCollectionDefined(DependsOn))
            {
                writer.WritePropertyName("dependsOn");
                writer.WriteStartArray();
                foreach (var item in DependsOn)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(UserProperties))
            {
                writer.WritePropertyName("userProperties");
                writer.WriteStartArray();
                foreach (var item in UserProperties)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WritePropertyName("typeProperties");
            writer.WriteStartObject();
            if (Optional.IsDefined(MlPipelineId))
            {
                writer.WritePropertyName("mlPipelineId");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(MlPipelineId);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(MlPipelineId.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(MlPipelineEndpointId))
            {
                writer.WritePropertyName("mlPipelineEndpointId");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(MlPipelineEndpointId);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(MlPipelineEndpointId.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(Version))
            {
                writer.WritePropertyName("version");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(Version);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(Version.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(ExperimentName))
            {
                writer.WritePropertyName("experimentName");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(ExperimentName);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(ExperimentName.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(MlPipelineParameters))
            {
                writer.WritePropertyName("mlPipelineParameters");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(MlPipelineParameters);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(MlPipelineParameters.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(DataPathAssignments))
            {
                writer.WritePropertyName("dataPathAssignments");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(DataPathAssignments);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(DataPathAssignments.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(MlParentRunId))
            {
                writer.WritePropertyName("mlParentRunId");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(MlParentRunId);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(MlParentRunId.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(ContinueOnStepFailure))
            {
                writer.WritePropertyName("continueOnStepFailure");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(ContinueOnStepFailure);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(ContinueOnStepFailure.ToString()).RootElement);
#endif
            }
            writer.WriteEndObject();
            foreach (var item in AdditionalProperties)
            {
                writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
				writer.WriteRawValue(item.Value);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(item.Value.ToString()).RootElement);
#endif
            }
            writer.WriteEndObject();
        }

        internal static AzureMLExecutePipelineActivity DeserializeAzureMLExecutePipelineActivity(JsonElement element)
        {
            Optional<FactoryLinkedServiceReference> linkedServiceName = default;
            Optional<ActivityPolicy> policy = default;
            string name = default;
            string type = default;
            Optional<string> description = default;
            Optional<IList<ActivityDependency>> dependsOn = default;
            Optional<IList<ActivityUserProperty>> userProperties = default;
            Optional<BinaryData> mlPipelineId = default;
            Optional<BinaryData> mlPipelineEndpointId = default;
            Optional<BinaryData> version = default;
            Optional<BinaryData> experimentName = default;
            Optional<BinaryData> mlPipelineParameters = default;
            Optional<BinaryData> dataPathAssignments = default;
            Optional<BinaryData> mlParentRunId = default;
            Optional<BinaryData> continueOnStepFailure = default;
            IDictionary<string, BinaryData> additionalProperties = default;
            Dictionary<string, BinaryData> additionalPropertiesDictionary = new Dictionary<string, BinaryData>();
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("linkedServiceName"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    linkedServiceName = FactoryLinkedServiceReference.DeserializeFactoryLinkedServiceReference(property.Value);
                    continue;
                }
                if (property.NameEquals("policy"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    policy = ActivityPolicy.DeserializeActivityPolicy(property.Value);
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("dependsOn"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ActivityDependency> array = new List<ActivityDependency>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ActivityDependency.DeserializeActivityDependency(item));
                    }
                    dependsOn = array;
                    continue;
                }
                if (property.NameEquals("userProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ActivityUserProperty> array = new List<ActivityUserProperty>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ActivityUserProperty.DeserializeActivityUserProperty(item));
                    }
                    userProperties = array;
                    continue;
                }
                if (property.NameEquals("typeProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("mlPipelineId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mlPipelineId = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("mlPipelineEndpointId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mlPipelineEndpointId = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("version"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            version = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("experimentName"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            experimentName = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("mlPipelineParameters"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mlPipelineParameters = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("dataPathAssignments"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            dataPathAssignments = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("mlParentRunId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mlParentRunId = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("continueOnStepFailure"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            continueOnStepFailure = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                    }
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText()));
            }
            additionalProperties = additionalPropertiesDictionary;
            return new AzureMLExecutePipelineActivity(name, type, description.Value, Optional.ToList(dependsOn), Optional.ToList(userProperties), additionalProperties, linkedServiceName.Value, policy.Value, mlPipelineId.Value, mlPipelineEndpointId.Value, version.Value, experimentName.Value, mlPipelineParameters.Value, dataPathAssignments.Value, mlParentRunId.Value, continueOnStepFailure.Value);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.lua.commons.impl</groupId>
      <artifactId>lua-commons-impl-lua</artifactId>
      <version>5.2</version>
   </parent>

   <groupId>org.lua.commons.impl</groupId>
   <artifactId>lua-commons-impl-lua-tests</artifactId>
   <packaging>jar</packaging>
   <name>Lua Commons Impl::Lua 5.2 for Java Tests</name>

   <dependencies>
      <dependency>
         <groupId>org.lua.commons</groupId>
         <artifactId>lua-commons-native-level</artifactId>
      </dependency>
      <dependency>
         <groupId>org.lua.commons.impl</groupId>
         <artifactId>lua-commons-impl-lua-java</artifactId>
      </dependency>

      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

</project>


text:
from string import ascii_lowercase, ascii_uppercase, digits

natural = digits[1:] + '0'

# next line might error out if destination file does not exist
with open('../lists/abc.wl', 'r+') as file:
    for a in range(3, len(ascii_lowercase) + 1):
        for b in range(len(ascii_lowercase)):
            if len(ascii_lowercase[b: b + a]) == a:
                file.write(ascii_lowercase[b: b + a] + '\n')
    for a in range(3, len(ascii_uppercase) + 1):
        for b in range(len(ascii_uppercase)):
            if len(ascii_uppercase[b: b + a]) == a:
                file.write(ascii_uppercase[b: b + a] + '\n')
    for a in range(3, len(digits) + 1):
        for b in range(len(digits)):
            if len(digits[b: b + a]) == a:
                file.write(digits[b: b + a] + '\n')
    for a in range(3, len(natural) + 1):
        for b in range(len(natural)):
            if len(natural[b: b + a]) == a:
                file.write(natural[b: b + a] + '\n')
    reversed_lowercase = ascii_lowercase[:: -1]
    reversed_uppercase = ascii_uppercase[:: -1]
    reversed_digits = digits[:: -1]
    reversed_natural = natural[:: -1]
    for a in range(3, len(reversed_lowercase) + 1):
        for b in range(len(reversed_lowercase)):
            if len(reversed_lowercase[b: b + a]) == a:
                file.write(reversed_lowercase[b: b + a] + '\n')
    for a in range(3, len(reversed_uppercase) + 1):
        for b in range(len(reversed_uppercase)):
            if len(reversed_uppercase[b: b + a]) == a:
                file.write(reversed_uppercase[b: b + a] + '\n')
    for a in range(3, len(reversed_digits) + 1):
        for b in range(len(reversed_digits)):
            if len(reversed_digits[b: b + a]) == a:
                file.write(reversed_digits[b: b + a] + '\n')
    for a in range(3, len(reversed_natural) + 1):
        for b in range(len(reversed_natural)):
            if len(reversed_natural[b: b + a]) == a:
                file.write(reversed_natural[b: b + a] + '\n')

file.close()


text:
package io.pravega.test.integration.endtoendtest;

import io.pravega.client.ClientConfig;
import io.pravega.client.admin.ReaderGroupManager;
import io.pravega.client.admin.impl.ReaderGroupManagerImpl;
import io.pravega.client.connection.impl.ConnectionPoolImpl;
import io.pravega.client.connection.impl.SocketConnectionFactoryImpl;
import io.pravega.client.stream.Checkpoint;
import io.pravega.client.stream.EventRead;
import io.pravega.client.stream.EventStreamReader;
import io.pravega.client.stream.EventStreamWriter;
import io.pravega.client.stream.EventWriterConfig;
import io.pravega.client.stream.ReaderConfig;
import io.pravega.client.stream.ReaderGroup;
import io.pravega.client.stream.ReaderGroupConfig;
import io.pravega.client.stream.ScalingPolicy;
import io.pravega.client.stream.Stream;
import io.pravega.client.stream.StreamConfiguration;
import io.pravega.client.stream.impl.ClientFactoryImpl;
import io.pravega.client.control.impl.Controller;
import io.pravega.client.stream.impl.JavaSerializer;
import io.pravega.client.stream.impl.StreamImpl;
import io.pravega.common.concurrent.ExecutorServiceHelpers;
import io.pravega.segmentstore.contracts.StreamSegmentStore;
import io.pravega.segmentstore.contracts.tables.TableStore;
import io.pravega.segmentstore.server.host.handler.PravegaConnectionListener;
import io.pravega.segmentstore.server.store.ServiceBuilder;
import io.pravega.segmentstore.server.store.ServiceBuilderConfig;
import io.pravega.test.common.InlineExecutor;
import io.pravega.test.common.TestUtils;
import io.pravega.test.common.TestingServerStarter;
import io.pravega.test.integration.utils.ControllerWrapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.test.TestingServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static io.pravega.test.common.AssertExtensions.assertEventuallyEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

@Slf4j
public class EndToEndChannelLeakTest {

    private static final String SCOPE = "test";
    private static final String STREAM_NAME = "test";
    private static final String READER_GROUP = "reader";
    private static final long ASSERT_TIMEOUT = 10000;

    private final int controllerPort = TestUtils.getAvailableListenPort();
    private final String serviceHost = "localhost";
    private final int servicePort = TestUtils.getAvailableListenPort();
    private final int containerCount = 4;
    private final JavaSerializer<String> serializer = new JavaSerializer<>();
    private final EventWriterConfig writerConfig = EventWriterConfig.builder().enableConnectionPooling(true).build();
    private TestingServer zkTestServer;
    private PravegaConnectionListener server;
    private ControllerWrapper controllerWrapper;
    private ServiceBuilder serviceBuilder;
    private ScheduledExecutorService executor;

    @Before
    public void setUp() throws Exception {
        executor = new InlineExecutor();
        zkTestServer = new TestingServerStarter().start();

        serviceBuilder = ServiceBuilder.newInMemoryBuilder(ServiceBuilderConfig.getDefaultConfig());
        serviceBuilder.initialize();
        StreamSegmentStore store = serviceBuilder.createStreamSegmentService();
        TableStore tableStore = serviceBuilder.createTableStoreService();

        server = new PravegaConnectionListener(false, servicePort, store, tableStore, this.serviceBuilder.getLowPriorityExecutor());
        server.startListening();

        controllerWrapper = new ControllerWrapper(zkTestServer.getConnectString(),
                false, controllerPort, serviceHost, servicePort, containerCount);
        controllerWrapper.awaitRunning();
    }

    @After
    public void tearDown() throws Exception {
        ExecutorServiceHelpers.shutdown(executor);
        controllerWrapper.close();
        server.close();
        serviceBuilder.close();
        zkTestServer.close();
    }

    @Test(timeout = 30000)
    public void testDetectChannelLeakSegmentSealedPooled() throws Exception {
        StreamConfiguration config = StreamConfiguration.builder()
                                                        .scalingPolicy(ScalingPolicy.fixed(1))
                                                        .build();
        Controller controller = controllerWrapper.getController();
        controllerWrapper.getControllerService().createScope(SCOPE, 0L).get();
        controller.createStream(SCOPE, STREAM_NAME, config).get();
        //Set the max number connections to verify channel creation behaviour
        final ClientConfig clientConfig = ClientConfig.builder().maxConnectionsPerSegmentStore(5).build();

        @Cleanup
        SocketConnectionFactoryImpl connectionFactory = new SocketConnectionFactoryImpl(clientConfig, new InlineExecutor());
        @Cleanup
        ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, connectionFactory);
        @Cleanup
        ClientFactoryImpl clientFactory = new ClientFactoryImpl(SCOPE, controller, connectionPool);

        //Create a writer.
        @Cleanup
        EventStreamWriter<String> writer = clientFactory.createEventWriter(SCOPE, serializer, writerConfig);

        //Write an event.
        writer.writeEvent("0", "zero").get();

        assertChannelCount(1, connectionPool, connectionFactory);

        @Cleanup
        ReaderGroupManager groupManager = new ReaderGroupManagerImpl(SCOPE, controller, clientFactory);
        groupManager.createReaderGroup(READER_GROUP, ReaderGroupConfig.builder().disableAutomaticCheckpoints().groupRefreshTimeMillis(0)
                                       .stream(Stream.of(SCOPE, STREAM_NAME)).build());

        @Cleanup
        EventStreamReader<String> reader1 = clientFactory.createReader("readerId1", READER_GROUP, serializer,
                                                                       ReaderConfig.builder().disableTimeWindows(true).build());

        //Read an event.
        EventRead<String> event = reader1.readNextEvent(10000);
        assertEquals("zero", event.getEvent());

        // scale
        Stream stream = new StreamImpl(SCOPE, SCOPE);
        Map<Double, Double> map = new HashMap<>();
        map.put(0.0, 0.33);
        map.put(0.33, 0.66);
        map.put(0.66, 1.0);
        Boolean result = controller.scaleStream(stream, Collections.singletonList(0L), map, executor).getFuture().get();
        assertTrue(result);

        event = reader1.readNextEvent(0);
        assertNull(event.getEvent());

        @Cleanup
        ReaderGroup readerGroup = groupManager.getReaderGroup(READER_GROUP);
        readerGroup.initiateCheckpoint("cp", executor);

        event = reader1.readNextEvent(5000);
        assertEquals("cp", event.getCheckpointName());

        //Write more events.
        writer.writeEvent("0", "one").get();
        writer.writeEvent("0", "two").get();
        writer.writeEvent("1", "three").get();

        event = reader1.readNextEvent(10000);
        assertNotNull(event.getEvent());

        assertChannelCount(5, connectionPool, connectionFactory);

        event = reader1.readNextEvent(10000);
        assertNotNull(event.getEvent());
        assertChannelCount(5, connectionPool, connectionFactory);

        event = reader1.readNextEvent(10000);
        assertNotNull(event.getEvent());
        assertChannelCount(5, connectionPool, connectionFactory);
    }

    @Test(timeout = 30000)
    public void testDetectChannelLeakMultiReaderPooled() throws Exception {
        StreamConfiguration config = StreamConfiguration.builder()
                                                        .scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1))
                                                        .build();
        //Set the max number connections to verify channel creation behaviour
        final ClientConfig clientConfig = ClientConfig.builder().maxConnectionsPerSegmentStore(5).build();

        Controller controller = controllerWrapper.getController();
        controllerWrapper.getControllerService().createScope(SCOPE, 0L).get();
        controller.createStream(SCOPE, STREAM_NAME, config).get();
        @Cleanup
        SocketConnectionFactoryImpl connectionFactory = new SocketConnectionFactoryImpl(clientConfig, executor);
        @Cleanup
        ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, connectionFactory);
        @Cleanup
        ClientFactoryImpl clientFactory = new ClientFactoryImpl(SCOPE, controller, connectionPool);
        int expectedChannelCount = 0; // open socket count.
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        //Create a writer and write an event.
        @Cleanup
        EventStreamWriter<String> writer = clientFactory.createEventWriter(STREAM_NAME, serializer, writerConfig);
        writer.writeEvent("0", "zero").get();

        expectedChannelCount += 1; // connection to segment 0.
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        @Cleanup
        ReaderGroupManager groupManager = new ReaderGroupManagerImpl(SCOPE, controller, clientFactory);
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory); // no changes expected.

        groupManager.createReaderGroup(READER_GROUP, ReaderGroupConfig.builder().disableAutomaticCheckpoints().groupRefreshTimeMillis(0)
                                       .stream(Stream.of(SCOPE, STREAM_NAME)).build());

        //create a reader and read an event.
        @Cleanup
        EventStreamReader<String> reader1 = clientFactory.createReader("readerId1", READER_GROUP, serializer,
                ReaderConfig.builder().disableTimeWindows(true).build());
        //Creating a reader spawns a revisioned stream client which opens 4 sockets ( read, write, metadataClient and conditionalUpdates).
        EventRead<String> event = reader1.readNextEvent(10000);
        //reader creates a new connection to the segment 0;
        assertEquals("zero", event.getEvent());
        //Connection to segment 0 does not cause an increase in number of open connections since we have reached the maxConnection count.
        assertChannelCount(5, connectionPool, connectionFactory);

        // scale
        Stream stream = new StreamImpl(SCOPE, STREAM_NAME);
        Map<Double, Double> map = new HashMap<>();
        map.put(0.0, 0.33);
        map.put(0.33, 0.66);
        map.put(0.66, 1.0);
        Boolean result = controller.scaleStream(stream, Collections.singletonList(0L), map, executor).getFuture().get();
        assertTrue(result);
        //No changes to the channel count.
        assertChannelCount(5, connectionPool, connectionFactory);

        //Reaches EOS
        event = reader1.readNextEvent(1000);
        assertNull(event.getEvent());

        //Write more events.
        writer.writeEvent("1", "one").get();
        writer.writeEvent("2", "two").get();
        writer.writeEvent("3", "three").get();
        writer.writeEvent("4", "four").get();
        writer.writeEvent("5", "five").get();
        writer.writeEvent("6", "six").get();

        //2 new flows  are opened.(+3 connections to the segments 1,2,3 after scale by the writer,
        // -1 flow to segment 0 which is sealed.)
        assertChannelCount(5, connectionPool, connectionFactory);

        ReaderGroup readerGroup = groupManager.getReaderGroup(READER_GROUP);
        CompletableFuture<Checkpoint> future = readerGroup.initiateCheckpoint("cp1", executor);
        //4 more from the state synchronizer
        assertChannelCount(5, connectionPool, connectionFactory);
        event = reader1.readNextEvent(5000);
        assertEquals("cp1", event.getCheckpointName());
        event = reader1.readNextEvent(5000);
        assertNotNull(event.getEvent());
        future.join();
        //Checkpoint should close connections back down
        readerGroup.close();
        assertChannelCount(5, connectionPool, connectionFactory);

        event = reader1.readNextEvent(10000);
        assertNotNull(event.getEvent());
        assertChannelCount(5, connectionPool, connectionFactory);
    }

    @Test(timeout = 30000)
    public void testDetectChannelLeakSegmentSealed() throws Exception {
        StreamConfiguration config = StreamConfiguration.builder()
                                                        .scalingPolicy(ScalingPolicy.fixed(1))
                                                        .build();
        Controller controller = controllerWrapper.getController();
        controllerWrapper.getControllerService().createScope(SCOPE, 0L).get();
        controller.createStream(SCOPE, STREAM_NAME, config).get();
        //Set the max number connections to verify channel creation behaviour
        final ClientConfig clientConfig = ClientConfig.builder().maxConnectionsPerSegmentStore(500).build();

        @Cleanup
        SocketConnectionFactoryImpl connectionFactory = new SocketConnectionFactoryImpl(clientConfig, executor);
        @Cleanup
        ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, connectionFactory);
        @Cleanup
        ClientFactoryImpl clientFactory = new ClientFactoryImpl(SCOPE, controller, connectionPool);

        int channelCount = 0;
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        @Cleanup
        ReaderGroupManager groupManager = new ReaderGroupManagerImpl(SCOPE, controller, clientFactory);
        groupManager.createReaderGroup(READER_GROUP, ReaderGroupConfig.builder().disableAutomaticCheckpoints().groupRefreshTimeMillis(0)
                                       .stream(Stream.of(SCOPE, STREAM_NAME)).build());

        //Should not add any connections
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        //Create a writer.
        @Cleanup
        EventStreamWriter<String> writer = clientFactory.createEventWriter(SCOPE, serializer, writerConfig);

        //Write an event.
        writer.writeEvent("0", "zero").get();
        channelCount += 1;
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        @Cleanup
        EventStreamReader<String> reader1 = clientFactory.createReader("readerId1", READER_GROUP, serializer,
                ReaderConfig.builder().disableTimeWindows(true).build());

        channelCount += 4; //One for segment 3 for state synchronizer
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        //Read an event.
        EventRead<String> event = reader1.readNextEvent(10000);
        assertEquals("zero", event.getEvent());

        channelCount += 1;
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        // scale
        Stream stream = new StreamImpl(SCOPE, SCOPE);
        Map<Double, Double> map = new HashMap<>();
        map.put(0.0, 0.33);
        map.put(0.33, 0.66);
        map.put(0.66, 1.0);
        Boolean result = controller.scaleStream(stream, Collections.singletonList(0L), map, executor).getFuture().get();
        assertTrue(result);

        event = reader1.readNextEvent(0);
        assertNull(event.getEvent());
        channelCount -= 1; //Reader should see EOS
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        writer.writeEvent("1", "one").get(); //should detect end of segment
        channelCount += 2; //Close one segment open 3.
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        ReaderGroup readerGroup = groupManager.getReaderGroup(READER_GROUP);
        readerGroup.getMetrics().unreadBytes();
        CompletableFuture<Checkpoint> future = readerGroup.initiateCheckpoint("cp1", executor);
        //3 more from the state synchronizer
        channelCount += 4;
        assertChannelCount(channelCount, connectionPool, connectionFactory);
        event = reader1.readNextEvent(5000);
        assertEquals("cp1", event.getCheckpointName());

        event = reader1.readNextEvent(10000);
        assertEquals("one", event.getEvent());
        channelCount += 3; //From new segments on reader
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        future.join();
        //Checkpoint should close connections back down
        readerGroup.close();
        channelCount -= 4;
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        //Write more events.
        writer.writeEvent("2", "two").get();
        writer.writeEvent("3", "three").get();
        writer.writeEvent("4", "four").get();

        //no changes to socket count.
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        event = reader1.readNextEvent(10000);
        assertNotNull(event.getEvent());
        //no changes to socket count.
        assertChannelCount(channelCount, connectionPool, connectionFactory);

        reader1.close();
        //3 from segments 4 from group state.
        channelCount -= 7;
        assertChannelCount(channelCount, connectionPool, connectionFactory);
        groupManager.close();
        writer.close();
        assertChannelCount(0, connectionPool, connectionFactory);

    }

    @Test(timeout = 30000)
    public void testDetectChannelLeakMultiReader() throws Exception {
        StreamConfiguration config = StreamConfiguration.builder()
                                                        .scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1))
                                                        .build();
        //Set the max number connections to verify channel creation behaviour
        final ClientConfig clientConfig = ClientConfig.builder().maxConnectionsPerSegmentStore(500).build();
        Controller controller = controllerWrapper.getController();
        controllerWrapper.getControllerService().createScope(SCOPE, 0L).get();
        controller.createStream(SCOPE, STREAM_NAME, config).get();
        @Cleanup
        SocketConnectionFactoryImpl connectionFactory = new SocketConnectionFactoryImpl(clientConfig, new InlineExecutor());
        @Cleanup
        ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, connectionFactory);
        @Cleanup
        ClientFactoryImpl clientFactory = new ClientFactoryImpl(SCOPE, controller, connectionPool);
        int expectedChannelCount = 0; // open socket count.
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        //Create a writer and write an event.
        @Cleanup
        EventStreamWriter<String> writer = clientFactory.createEventWriter(STREAM_NAME, serializer, writerConfig);
        writer.writeEvent("0", "zero").get();

        expectedChannelCount += 1; // connection to segment 0.
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        @Cleanup
        ReaderGroupManager groupManager = new ReaderGroupManagerImpl(SCOPE, controller, clientFactory);
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory); // no changes expected.

        groupManager.createReaderGroup(READER_GROUP, ReaderGroupConfig.builder().disableAutomaticCheckpoints().groupRefreshTimeMillis(0)
                                       .stream(Stream.of(SCOPE, STREAM_NAME)).build());

        //create a reader and read an event.
        @Cleanup
        EventStreamReader<String> reader1 = clientFactory.createReader("readerId1", READER_GROUP, serializer,
                ReaderConfig.builder().disableTimeWindows(true).build());
        //Creating a reader spawns a revisioned stream client which opens 4 sockets ( read, write, metadataClient and conditionalUpdates).
        expectedChannelCount += 4;
        EventRead<String> event = reader1.readNextEvent(10000);

        //reader creates a new connection to the segment 0;
        expectedChannelCount += 1;
        assertEquals("zero", event.getEvent());
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        // scale
        Stream stream = new StreamImpl(SCOPE, STREAM_NAME);
        Map<Double, Double> map = new HashMap<>();
        map.put(0.0, 0.33);
        map.put(0.33, 0.66);
        map.put(0.66, 1.0);
        Boolean result = controller.scaleStream(stream, Collections.singletonList(0L), map, executor).getFuture().get();
        assertTrue(result);
        //No changes to the channel count.
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        event = reader1.readNextEvent(0);
        assertNull(event.getEvent());
        event = reader1.readNextEvent(0);
        assertNull(event.getEvent());
        //should decrease channel count from close connection
        expectedChannelCount -= 1;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        //Write more events.
        writer.writeEvent("1", "one").get();
        writer.writeEvent("2", "two").get();
        writer.writeEvent("3", "three").get();
        writer.writeEvent("4", "four").get();
        writer.writeEvent("5", "five").get();
        writer.writeEvent("6", "six").get();

        //Open 3 new segments close one old one.
        expectedChannelCount += 2;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        ReaderGroup readerGroup = groupManager.getReaderGroup(READER_GROUP);
        CompletableFuture<Checkpoint> future = readerGroup.initiateCheckpoint("cp1", executor);
        //4 more from the state synchronizer
        expectedChannelCount += 4;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);
        event = reader1.readNextEvent(5000);
        assertEquals("cp1", event.getCheckpointName());

        //Add a new reader
        @Cleanup
        EventStreamReader<String> reader2 = clientFactory.createReader("readerId2", READER_GROUP, serializer,
                ReaderConfig.builder().disableTimeWindows(true).build());
        //Creating a reader spawns a revisioned stream client which opens 4 sockets ( read, write, metadataClient and conditionalUpdates).
        expectedChannelCount += 4;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        event = reader1.readNextEvent(5000);
        assertNotNull(event.getEvent());
        event = reader2.readNextEvent(5000);
        assertNotNull(event.getEvent());
        //3 more from the new segments
        expectedChannelCount += 3;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        future.join();
        //Checkpoint should close connections back down
        readerGroup.close();
        expectedChannelCount -= 4;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);

        reader1.close();
        reader2.close();
        expectedChannelCount -= 8 + 3;
        assertChannelCount(expectedChannelCount, connectionPool, connectionFactory);
    }

    private void assertChannelCount(int expectedChannelCount, ConnectionPoolImpl connectionPool,
            SocketConnectionFactoryImpl factory) throws Exception {
        assertEventuallyEquals(expectedChannelCount, () -> {
            connectionPool.pruneUnusedConnections();
            return factory.getOpenSocketCount();
        }, ASSERT_TIMEOUT);
    }

}


text:
{% extends "base.html" %}
{% block content %}

Update System Profile

{% from "_formhelpers.html" import render_field %}

<form method=post class="form-horizontal">
    {{ form.hidden_tag() }}
    {{ render_field(form.profile_name) }}
    {{ render_field(form.version) }}
    {{ render_field(form.source_system) }}
    {{ render_field(form.source_system_code) }}
    {{ render_field(form.source_database_type) }}
    {{ render_field(form.source_connection) }}
    {{ render_field(form.target_system) }}
    {{ render_field(form.target_system_code) }}
    {{ render_field(form.target_database_type) }}
    {{ render_field(form.target_connection) }}
    {{ render_field(form.active_ind) }}
    {{ render_field(form.server_path) }}
    {{ render_field(form.description) }}

    {% if g.user.is_authenticated %}
    <button type="submit" class="btn btn-primary">Submit</button>
    {% endif %}
    <input type="button" class="btn btn-primary" value="Cancel" onclick="window.location.href='/profilelist';">

</form>

{% endblock %}


text:
layout: default
title: James Yong, Software Engineer
---

Hi there, I'm James Yong!

I'm a software engineer doing polyglot programming. Read more about my blog...


text:
namespace testing {

// Declares Google Mock flags that we want a user to use programmatically.
GMOCK_DECLARE_bool_(catch_leaked_mocks);
GMOCK_DECLARE_string_(verbose);
GMOCK_DECLARE_int32_(default_mock_behavior);

// Initializes Google Mock.  This must be called before running the
// tests.  In particular, it parses the command line for the flags
// that Google Mock recognizes.  Whenever a Google Mock flag is seen,
// it is removed from argv, and *argc is decremented.
//
// No value is returned.  Instead, the Google Mock flag variables are
// updated.
//
// Since Google Test is needed for Google Mock to work, this function
// also initializes Google Test and parses its flags, if that hasn't
// been done.
GTEST_API_ void InitGoogleMock(int* argc, char** argv);

// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);

}  // namespace testing

#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_H_


text:
<?php
$this->pageTitle = Yii::app()->name . ' - Contact Us';
$this->breadcrumbs = array(
	'Contact',
);
?>

Contact Us

<?php if (Yii::app()->user->hasFlash('contact')): ?>

	<?php echo Yii::app()->user->getFlash('contact'); ?>

<?php else: ?>

	If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.

	<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id' => 'contact-form',
	'enableClientValidation' => true,
	'htmlOptions' => array('class' => 'well'),
	'clientOptions' => array(
		'validateOnSubmit' => true,
	),
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model); ?>

	<?php echo $form->textFieldRow($model, 'name'); ?>
	<?php echo $form->textFieldRow($model, 'email'); ?>
	<?php echo $form->textFieldRow($model, 'subject', array('size' => 60, 'maxlength' => 128)); ?>
	<?php echo $form->textAreaRow($model, 'body', array('rows' => 6, 'cols' => 50)); ?>

	<?php if (CCaptcha::checkRequirements()): ?>
	<?php $this->widget('CCaptcha'); ?>
	<?php echo $form->textFieldRow($model, 'verifyCode'); ?>

Please, enter the letters as they are shown in the image above. Letters are not
		case-sensitive

	<?php endif; ?>

		<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'submit', 'type' => 'primary', 'label' => 'Submit', 'icon' => 'ok'));?>
		<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'reset', 'label' => 'Reset'));?>

	<?php $this->endWidget(); ?>

<?php  endif; ?>


text:
struct wcore_window;
union waffle_native_window;

struct wcore_window {
    struct api_object api;
    struct wcore_display *display;
};

static inline struct waffle_window*
waffle_window(struct wcore_window *win) {
    return (struct waffle_window*) win;
}

static inline struct wcore_window*
wcore_window(struct waffle_window *win) {
    return (struct wcore_window*) win;
}

static inline bool
wcore_window_init(struct wcore_window *self,
                  struct wcore_config *config)
{
    assert(self);
    assert(config);

    self->api.display_id = config->display->api.display_id;
    self->display = config->display;

    return true;
}

static inline bool
wcore_window_teardown(struct wcore_window *self)
{
    (void) self;
    assert(self);
    return true;
}


text:
"""Input pipeline for the listops dataset."""

import numpy as np

import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds
import tensorflow_text as text

AUTOTUNE = tf.data.experimental.AUTOTUNE

def rename_close_brackets(x):
  source = x['Source']
  source = tf.strings.regex_replace(source, ']', 'X')
  source = tf.strings.regex_replace(source, r'\(', '')
  source = tf.strings.regex_replace(source, r'\)', '')
  return {'Source': source, 'Target': x['Target']}

def preprocess_dataset(file_path, batch_size):
  """Preprocess dataset."""
  tf.logging.info(file_path)
  sel_cols = ['Source', 'Target']
  col_defaults = [tf.string, tf.int32]
  ds = tf.data.experimental.make_csv_dataset([file_path],
                                             batch_size,
                                             column_defaults=col_defaults,
                                             select_columns=sel_cols,
                                             field_delim='\t',
                                             header=True,
                                             num_epochs=1)
  ds = ds.unbatch()
  # we rename close brackets to X for this particular task because
  # tokenizer removes non alphanumeric.
  # since there is no trivial way to change this behaviour
  # we opt for an equivalent fix since the vocab in listops is fixed.
  ds = ds.map(rename_close_brackets, num_parallel_calls=AUTOTUNE)
  return ds

def get_datasets(n_devices,
                 task_name,
                 data_dir=None,
                 batch_size=256,
                 max_length=2000):
  """Get algorithmic datasets."""
  if batch_size % n_devices:
    raise ValueError("Batch size %d isn't divided evenly by n_devices %d" %
                     (batch_size, n_devices))

  train_path = data_dir + task_name + '_train.tsv'
  val_path = data_dir + task_name + '_val.tsv'
  test_path = data_dir + task_name + '_test.tsv'

  train_dataset = preprocess_dataset(train_path, batch_size)
  val_dataset = preprocess_dataset(val_path, batch_size)
  test_dataset = preprocess_dataset(test_path, batch_size)

  tf.logging.info('Finished preprocessing')
  tf.logging.info('Building vocab')
  # build vocab
  vocab_set = set()
  tokenizer = text.WhitespaceTokenizer()

  lengths = []
  for i, data in enumerate(val_dataset):
    examples = data['Source']
    examples = tokenizer.tokenize(examples.numpy())
    examples = np.reshape(examples, (-1)).tolist()
    lengths.append(len(examples))
    vocab_set.update(examples)
    if i % 1000 == 0:
      tf.logging.info('Processed {}'.format(i))
    if i > 1000:
      break
  vocab_set = list(set(vocab_set))
  tf.logging.info('Finished processing vocab size={}'.format(len(vocab_set)))

  encoder = tfds.deprecated.text.TokenTextEncoder(
      vocab_set)

  def tf_encode(x):
    result = tf.py_function(lambda s: tf.constant(encoder.encode(s.numpy())),
                            [x,],
                            tf.int32)
    result.set_shape([None])
    return result

  def tokenize(d):
    return {'inputs': tf_encode(d['Source'])[:max_length],
            'targets': d['Target']}

  train_dataset = train_dataset.map(tokenize, num_parallel_calls=AUTOTUNE)
  val_dataset = val_dataset.map(tokenize, num_parallel_calls=AUTOTUNE)
  test_dataset = test_dataset.map(tokenize, num_parallel_calls=AUTOTUNE)

  max_shape = {'inputs': [max_length], 'targets': []}
  train_dataset = train_dataset.shuffle(
      buffer_size=1024, reshuffle_each_iteration=True).padded_batch(
          batch_size, padded_shapes=max_shape)
  val_dataset = val_dataset.padded_batch(batch_size, padded_shapes=max_shape)
  test_dataset = test_dataset.padded_batch(batch_size, padded_shapes=max_shape)

  train_dataset = train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
  val_dataset = val_dataset.prefetch(tf.data.experimental.AUTOTUNE)
  test_dataset = test_dataset.prefetch(tf.data.experimental.AUTOTUNE)

  return train_dataset, val_dataset, test_dataset, encoder


text:
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using NuGetConsole.Implementation.Console;
using NuGetConsole.Implementation.PowerConsole;
using NuGet.PackageManagement;
using NuGet.PackageManagement.VisualStudio;

namespace NuGetConsole.Implementation
{
    /// <summary>
    /// This class implements the tool window.
    /// </summary>
    [Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")]
    public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget, IPowerConsoleService
    {
        /// <summary>
        /// Get VS IComponentModel service.
        /// </summary>
        private IComponentModel ComponentModel
        {
            get
            {
                return this.GetService<IComponentModel>(typeof(SComponentModel));
            }
        }

        private IProductUpdateService ProductUpdateService
        {
            get
            {
                return ComponentModel.GetService<IProductUpdateService>();
            }
        }

        private IPackageRestoreManager PackageRestoreManager
        {
            get
            {
                return ComponentModel.GetService<IPackageRestoreManager>();
            }
        }

        private PowerConsoleWindow PowerConsoleWindow
        {
            get
            {
                return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow;
            }
        }

        private IVsUIShell VsUIShell
        {
            get
            {
                return this.GetService<IVsUIShell>(typeof(SVsUIShell));
            }
        }

        private bool IsToolbarEnabled
        {
            get
            {
                return _wpfConsole != null &&
                       _wpfConsole.Dispatcher.IsStartCompleted &&
                       _wpfConsole.Host != null &&
                       _wpfConsole.Host.IsCommandEnabled;
            }
        }

        /// <summary>
        /// Standard constructor for the tool window.
        /// </summary>
        public PowerConsoleToolWindow() :
            base(null)
        {
            this.Caption = Resources.ToolWindowTitle;
            this.BitmapResourceID = 301;
            this.BitmapIndex = 0;
            this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar);
        }

        protected override void Initialize()
        {
            base.Initialize();

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (mcs != null)
            {
                // Get list command for the Feed combo
                CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList);
                mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID));

                // invoke command for the Feed combo
                CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources);
                mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID));

                // get default project command
                CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList);
                mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID));

                // invoke command for the Default project combo
                CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects);
                mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID));

                // clear console command
                CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost);
                mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID));

                // terminate command execution command
                CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost);
                mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID));
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Design",
            "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "We really don't want exceptions from the console to bring down VS")]
        public override void OnToolWindowCreated()
        {
            // Register key bindings to use in the editor
            var windowFrame = (IVsWindowFrame)Frame;
            Guid cmdUi = VSConstants.GUID_TextEditorFactory;
            windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi);

            // pause for a tiny moment to let the tool window open before initializing the host
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(10);
            timer.Tick += (o, e) =>
            {
                // all exceptions from the timer thread should be caught to avoid crashing VS
                try
                {
                    LoadConsoleEditor();
                    timer.Stop();
                }
                catch (Exception x)
                {
                    ExceptionHelper.WriteToActivityLog(x);
                }
            };
            timer.Start();

            base.OnToolWindowCreated();
        }

        protected override void OnClose()
        {
            base.OnClose();

            if (_wpfConsole != null)
            {
                _wpfConsole.Dispose();
            }
        }

        /// <summary>
        /// This override allows us to forward these messages to the editor instance as well
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        protected override bool PreProcessMessage(ref System.Windows.Forms.Message m)
        {
            IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane;
            if (vsWindowPane != null)
            {
                MSG[] pMsg = new MSG[1];
                pMsg[0].hwnd = m.HWnd;
                pMsg[0].message = (uint)m.Msg;
                pMsg[0].wParam = m.WParam;
                pMsg[0].lParam = m.LParam;

                return vsWindowPane.TranslateAccelerator(pMsg) == 0;
            }

            return base.PreProcessMessage(ref m);
        }

        /// <summary>
        /// Override to forward to editor or handle accordingly if supported by this tool window.
        /// </summary>
        int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            // examine buttons within our toolbar
            if (pguidCmdGroup == GuidList.guidNuGetCmdSet)
            {
                bool isEnabled = IsToolbarEnabled;

                if (isEnabled)
                {
                    bool isStopButton = (prgCmds[0].cmdID == 0x0600);   // 0x0600 is the Command ID of the Stop button, defined in .vsct

                    // when command is executing: enable stop button and disable the rest
                    // when command is not executing: disable the stop button and enable the rest
                    isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand;
                }

                if (isEnabled)
                {
                    prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
                }
                else
                {
                    prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                }

                return VSConstants.S_OK;
            }

            int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED;

            if (this.VsTextView != null)
            {
                IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView;
                hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
            }

            if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED ||
                hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP)
            {
                IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
                if (target != null)
                {
                    hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
                }
            }

            return hr;
        }

        /// <summary>
        /// Override to forward to editor or handle accordingly if supported by this tool window.
        /// </summary>
        int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED;

            if (this.VsTextView != null)
            {
                IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView;
                hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
            }

            if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED ||
                hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP)
            {
                IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
                if (target != null)
                {
                    hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                }
            }

            return hr;
        }

        private void SourcesList_Exec(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
            if (args != null)
            {
                if (args.InValue != null || args.OutValue == IntPtr.Zero)
                {
                    throw new ArgumentException("Invalid argument", "e");
                }
                Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue);
            }
        }

        /// <summary>
        /// Called to retrieve current combo item name or to select a new item.
        /// </summary>
        private void Sources_Exec(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
            if (args != null)
            {
                if (args.InValue != null && args.InValue is int) // Selected a feed
                {
                    int index = (int)args.InValue;
                    if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length)
                    {
                        PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index];
                    }
                }
                else if (args.OutValue != IntPtr.Zero) // Query selected feed name
                {
                    string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty;
                    Marshal.GetNativeVariantForObject(displayName, args.OutValue);
                }
            }
        }

        private void ProjectsList_Exec(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
            if (args != null)
            {
                if (args.InValue != null || args.OutValue == IntPtr.Zero)
                {
                    throw new ArgumentException("Invalid argument", "e");
                }

                // get project list here
                Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue);
            }
        }

        /// <summary>
        /// Called to retrieve current combo item name or to select a new item.
        /// </summary>
        private void Projects_Exec(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
            if (args != null)
            {
                if (args.InValue != null && args.InValue is int)
                {
                    // Selected a default projects
                    int index = (int)args.InValue;
                    if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length)
                    {
                        PowerConsoleWindow.SetDefaultProjectIndex(index);
                    }
                }
                else if (args.OutValue != IntPtr.Zero)
                {
                    string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty;
                    Marshal.GetNativeVariantForObject(displayName, args.OutValue);
                }
            }
        }

        /// <summary>
        /// ClearHost command handler.
        /// </summary>
        private void ClearHost_Exec(object sender, EventArgs e)
        {
            if (WpfConsole != null)
            {
                WpfConsole.Dispatcher.ClearConsole();
            }
        }

        private void StopHost_Exec(object sender, EventArgs e)
        {
            if (WpfConsole != null)
            {
                WpfConsole.Host.Abort();
            }
        }

        private HostInfo ActiveHostInfo
        {
            get
            {
                return PowerConsoleWindow.ActiveHostInfo;
            }
        }

        private void LoadConsoleEditor()
        {
            if (WpfConsole != null)
            {
                // allow the console to start writing output
                WpfConsole.StartWritingOutput();

                FrameworkElement consolePane = WpfConsole.Content as FrameworkElement;
                ConsoleParentPane.AddConsoleEditor(consolePane);

                // WPF doesn't handle input focus automatically in this scenario. We
                // have to set the focus manually, otherwise the editor is displayed but
                // not focused and not receiving keyboard inputs until clicked.
                if (consolePane != null)
                {
                    PendingMoveFocus(consolePane);
                }
            }
        }

        /// <summary>
        /// Set pending focus to a console pane. At the time of setting active host,
        /// the pane (UIElement) is usually not loaded yet and can't receive focus.
        /// In this case, we need to set focus in its Loaded event.
        /// </summary>
        /// <param name="consolePane"></param>
        private void PendingMoveFocus(FrameworkElement consolePane)
        {
            if (consolePane.IsLoaded && PresentationSource.FromDependencyObject(consolePane) != null)
            {
                PendingFocusPane = null;
                MoveFocus(consolePane);
            }
            else
            {
                PendingFocusPane = consolePane;
            }
        }

        private FrameworkElement _pendingFocusPane;
        private FrameworkElement PendingFocusPane
        {
            get
            {
                return _pendingFocusPane;
            }
            set
            {
                if (_pendingFocusPane != null)
                {
                    _pendingFocusPane.Loaded -= PendingFocusPane_Loaded;
                }
                _pendingFocusPane = value;
                if (_pendingFocusPane != null)
                {
                    _pendingFocusPane.Loaded += PendingFocusPane_Loaded;
                }
            }
        }

        private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e)
        {
            MoveFocus(PendingFocusPane);
            PendingFocusPane = null;
        }

        private void MoveFocus(FrameworkElement consolePane)
        {
            // TAB focus into editor (consolePane.Focus() does not work due to editor layouts)
            consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));

            // Try start the console session now. This needs to be after the console
            // pane getting focus to avoid incorrect initial editor layout.
            StartConsoleSession(consolePane);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Design",
            "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "We really don't want exceptions from the console to bring down VS")]
        private void StartConsoleSession(FrameworkElement consolePane)
        {
            if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null)
            {
                try
                {
                    if (WpfConsole.Dispatcher.IsStartCompleted)
                    {
                        OnDispatcherStartCompleted();
                        // if the dispatcher was started before we reach here,
                        // it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false).
                        // enable key input now.
                        WpfConsole.Dispatcher.AcceptKeyInput();
                    }
                    else
                    {
                        WpfConsole.Dispatcher.StartCompleted += (sender, args) => OnDispatcherStartCompleted();
                        WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey;
                        WpfConsole.Dispatcher.Start();
                    }
                }
                catch (Exception x)
                {
                    // hide the text "initialize host" when an error occurs.
                    ConsoleParentPane.NotifyInitializationCompleted();

                    WpfConsole.WriteLine(x.GetBaseException().ToString());
                    ExceptionHelper.WriteToActivityLog(x);
                }
            }
            else
            {
                ConsoleParentPane.NotifyInitializationCompleted();
            }
        }

        private void OnDispatcherStartWaitingKey(object sender, EventArgs args)
        {
            WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey;
            // we want to hide the text "initialize host..." when waiting for key input
            ConsoleParentPane.NotifyInitializationCompleted();
        }

        private void OnDispatcherStartCompleted()
        {
            WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey;

            ConsoleParentPane.NotifyInitializationCompleted();

            // force the UI to update the toolbar
            VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */);

            NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleLoaded);
        }

        private IWpfConsole _wpfConsole;

        /// <summary>
        /// Get the WpfConsole of the active host.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private IWpfConsole WpfConsole
        {
            get
            {
                if (_wpfConsole == null)
                {
                    _wpfConsole = ActiveHostInfo.WpfConsole;
                }

                return _wpfConsole;
            }
        }

        private IVsTextView _vsTextView;

        /// <summary>
        /// Get the VsTextView of current WpfConsole if exists.
        /// </summary>
        private IVsTextView VsTextView
        {
            get
            {
                if (_vsTextView == null && _wpfConsole != null)
                {
                    _vsTextView = (IVsTextView)(WpfConsole.VsTextView);
                }
                return _vsTextView;
            }
        }

        private ConsoleContainer _consoleParentPane;

        /// <summary>
        /// Get the parent pane of console panes. This serves as the Content of this tool window.
        /// </summary>
        private ConsoleContainer ConsoleParentPane
        {
            get
            {
                if (_consoleParentPane == null)
                {
                    _consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager);
                }
                return _consoleParentPane;
            }
        }

        public override object Content
        {
            get
            {
                return this.ConsoleParentPane;
            }
            set
            {
                base.Content = value;
            }
        }

        #region IPowerConsoleService Region

        public event EventHandler ExecuteEnd;
        private ITextSnapshot _snapshot;
        private int _previousPosition;

        public bool Execute(string command, object[] inputs)
        {
            if (ConsoleStatus.IsBusy)
            {
                VSOutputConsole.WriteLine(Resources.PackageManagerConsoleBusy);
                throw new NotSupportedException(Resources.PackageManagerConsoleBusy);
            }

            if (!String.IsNullOrEmpty(command))
            {
                WpfConsole.SetExecutionMode(true);
                // Cast the ToolWindowPane to PowerConsoleToolWindow
                // Access the IHost from PowerConsoleToolWindow as follows PowerConsoleToolWindow.WpfConsole.Host
                // Cast IHost to IAsyncHost
                // Also, register for IAsyncHost.ExecutedEnd and return only when the command is completed
                IPrivateWpfConsole powerShellConsole = (IPrivateWpfConsole)WpfConsole;
                IHost host = powerShellConsole.Host;

                var asynchost = host as IAsyncHost;
                if (asynchost != null)
                {
                    asynchost.ExecuteEnd += PowerConsoleCommand_ExecuteEnd;
                }

                // Here, we store the snapshot of the powershell Console output text buffer
                // Snapshot has reference to the buffer and the current length of the buffer
                // And, upon execution of the command, (check the commandexecuted handler)
                // the changes to the buffer is identified and copied over to the VS output window
                if (powerShellConsole.InputLineStart != null && powerShellConsole.InputLineStart.Value.Snapshot != null)
                {
                    _snapshot = powerShellConsole.InputLineStart.Value.Snapshot;
                }

                // We should write the command to the console just to imitate typical user action before executing it
                // Asserts get fired otherwise. Also, the log is displayed in a disorderly fashion
                powerShellConsole.WriteLine(command);

                return host.Execute(powerShellConsole, command, null);
            }
            return false;
        }

        private void PowerConsoleCommand_ExecuteEnd(object sender, EventArgs e)
        {
            // Flush the change in console text buffer onto the output window for testability
            // If the VSOutputConsole could not be obtained, just ignore
            if (VSOutputConsole != null && _snapshot != null)
            {
                if (_previousPosition < _snapshot.Length)
                {
                    VSOutputConsole.WriteLine(_snapshot.GetText(_previousPosition, (_snapshot.Length - _previousPosition)));
                }
                _previousPosition = _snapshot.Length;
            }

            (sender as IAsyncHost).ExecuteEnd -= PowerConsoleCommand_ExecuteEnd;
            WpfConsole.SetExecutionMode(false);

            // This does NOT imply that the command succeeded. It just indicates that the console is ready for input now
            VSOutputConsole.WriteLine(Resources.PackageManagerConsoleCommandExecuted);
            ExecuteEnd.Raise(this, EventArgs.Empty);
        }

        private IConsole _vsOutputConsole = null;
        private IConsole VSOutputConsole
        {
            get
            {
                if (_vsOutputConsole == null)
                {
                    IOutputConsoleProvider outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>();
                    if (null != outputConsoleProvider)
                    {
                        _vsOutputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false);
                    }
                }
                return _vsOutputConsole;
            }
        }

        private IConsoleStatus _consoleStatus;
        private IConsoleStatus ConsoleStatus
        {
            get
            {
                if (_consoleStatus == null)
                {
                    _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>();
                    Debug.Assert(_consoleStatus != null);
                }

                return _consoleStatus;
            }
        }
        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="C:\Program Files\Android\Android Studio\gradle\gradle-2.2.1" />
        <option name="gradleJvm" value="1.7" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/activation" />
            <option value="$PROJECT_DIR$/additionnal" />
            <option value="$PROJECT_DIR$/app" />
            <option value="$PROJECT_DIR$/mail" />
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.test.internal.constraintvalidators.bv;

import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Min;

import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.AbstractMinValidator;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForBigDecimal;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForBigInteger;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForDouble;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForFloat;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForLong;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.MinValidatorForNumber;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.AbstractDecimalMinValidator;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForBigDecimal;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForBigInteger;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForDouble;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForFloat;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForLong;
import org.hibernate.validator.internal.constraintvalidators.bv.number.bound.decimal.DecimalMinValidatorForNumber;
import org.hibernate.validator.internal.util.annotationfactory.AnnotationDescriptor;
import org.hibernate.validator.internal.util.annotationfactory.AnnotationFactory;
import org.hibernate.validator.testutil.TestForIssue;

import org.testng.annotations.Test;

/**
 * @author Alaa Nassef
 * @author Hardy Ferentschik
 * @author Xavier Sosnovsky
 * @author Marko Bekhta
 */
public class MinValidatorForNumberTest extends BaseMinMaxValidatorForNumberTest {

	@Test
	public void testIsValidMinValidator() {
		AnnotationDescriptor<Min> descriptor = new AnnotationDescriptor<Min>( Min.class );
		descriptor.setValue( "value", 15L );
		descriptor.setValue( "message", "{validator.min}" );
		Min m = AnnotationFactory.create( descriptor );

		testMin( m, true );
	}

	@Test
	public void testIsValidDecimalMinValidator() {
		AnnotationDescriptor<DecimalMin> descriptor = new AnnotationDescriptor<DecimalMin>( DecimalMin.class );
		descriptor.setValue( "value", "1500E-2" );
		descriptor.setValue( "message", "{validator.min}" );
		DecimalMin m = AnnotationFactory.create( descriptor );

		testDecimalMin( m, true );
	}

	@Test(expectedExceptions = IllegalArgumentException.class)
	public void testInitializeDecimalMinWithInvalidValue() {
		AnnotationDescriptor<DecimalMin> descriptor = new AnnotationDescriptor<DecimalMin>( DecimalMin.class );
		descriptor.setValue( "value", "foobar" );
		descriptor.setValue( "message", "{validator.min}" );
		DecimalMin m = AnnotationFactory.create( descriptor );

		DecimalMinValidatorForNumber constraint = new DecimalMinValidatorForNumber();
		constraint.initialize( m );
	}

	@Test
	@TestForIssue(jiraKey = "HV-256")
	public void testIsValidDecimalMinExclusive() {
		boolean inclusive = false;
		AnnotationDescriptor<DecimalMin> descriptor = new AnnotationDescriptor<DecimalMin>( DecimalMin.class );
		descriptor.setValue( "value", "1500E-2" );
		descriptor.setValue( "inclusive", inclusive );
		descriptor.setValue( "message", "{validator.min}" );
		DecimalMin m = AnnotationFactory.create( descriptor );

		testDecimalMin( m, inclusive );
	}

	private void testDecimalMin(DecimalMin m, boolean inclusive) {
		AbstractDecimalMinValidator constraint = new DecimalMinValidatorForNumber();
		constraint.initialize( m );
		testNumberValidator( constraint, inclusive, false );

		constraint = new DecimalMinValidatorForBigDecimal();
		constraint.initialize( m );
		testValidatorBigDecimal( constraint, inclusive, false );

		constraint = new DecimalMinValidatorForBigInteger();
		constraint.initialize( m );
		testValidatorBigInteger( constraint, inclusive, false );

		constraint = new DecimalMinValidatorForLong();
		constraint.initialize( m );
		testValidatorLong( constraint, inclusive, false );

		constraint = new DecimalMinValidatorForFloat();
		constraint.initialize( m );
		testValidatorFloat( constraint, inclusive, false );

		constraint = new DecimalMinValidatorForDouble();
		constraint.initialize( m );
		testValidatorDouble( constraint, inclusive, false );
	}

	private void testMin(Min m, boolean inclusive) {
		AbstractMinValidator constraint = new MinValidatorForNumber();
		constraint.initialize( m );
		testNumberValidator( constraint, inclusive, false );

		constraint = new MinValidatorForBigDecimal();
		constraint.initialize( m );
		testValidatorBigDecimal( constraint, inclusive, false );

		constraint = new MinValidatorForBigInteger();
		constraint.initialize( m );
		testValidatorBigInteger( constraint, inclusive, false );

		constraint = new MinValidatorForLong();
		constraint.initialize( m );
		testValidatorLong( constraint, inclusive, false );

		constraint = new MinValidatorForFloat();
		constraint.initialize( m );
		testValidatorFloat( constraint, inclusive, false );

		constraint = new MinValidatorForDouble();
		constraint.initialize( m );
		testValidatorDouble( constraint, inclusive, false );
	}

}


text:
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>

</body>
<script type="text/javascript">

// var myObject={
// 	a: 1,
// 	b: 2
// }
function Person(){
	this.name = 'zbl',
	this.say = function(){
		console.log(this.name)
	}
}
let myObject = new Person()
console.log(myObject)
for (var key in myObject) {
  console.log(key);
}

for (var key in myObject) {
	if (myObject.hasOwnProperty(key))
  console.log(key);
}
</script>

</html>


text:
<?php

return [
    'max_attempts'      => [
        'label'        => 'Allowed Login Attempts',
        'instructions' => 'How many failed login attempts are allowed within the Throttle Interval?',
    ],
    'throttle_interval' => [
        'label'        => 'Throttle Interval',
        'instructions' => 'If the Allowed Login Attempts is reached within the specified number of minutes, lockout the user.',
    ],
    'lockout_interval'  => [
        'label'        => 'Lockout Interval',
        'instructions' => 'Specify how many minutes a throttled user is locked out before they can attempt to login again.',
    ],
];


text:
{% extends 'console/base.html' %}
{% load i18n %}

{% block content %}

{% trans "Confirm Delete?" %}

    <form id="frmConfirmDelete" action="{% block confirm_delete_url %}{% endblock %}" method="post" enctype="multipart/form-data">{% csrf_token %}
        <input type="submit" value="Confirm" />
        {% trans "Decline" %}
    </form>
{% endblock %}


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

package com.azure.resourcemanager.appcontainers.generated;

import com.azure.resourcemanager.appcontainers.models.AppLogsConfiguration;
import com.azure.resourcemanager.appcontainers.models.CustomDomainConfiguration;
import com.azure.resourcemanager.appcontainers.models.EnvironmentSkuProperties;
import com.azure.resourcemanager.appcontainers.models.LogAnalyticsConfiguration;
import com.azure.resourcemanager.appcontainers.models.ManagedEnvironmentOutBoundType;
import com.azure.resourcemanager.appcontainers.models.ManagedEnvironmentOutboundSettings;
import com.azure.resourcemanager.appcontainers.models.SkuName;
import com.azure.resourcemanager.appcontainers.models.VnetConfiguration;
import com.azure.resourcemanager.appcontainers.models.WorkloadProfile;
import java.util.Arrays;

/** Samples for ManagedEnvironments CreateOrUpdate. */
public final class ManagedEnvironmentsCreateOrUpdateSamples {
    /*
     * x-ms-original-file: specification/app/resource-manager/Microsoft.App/preview/2022-06-01-preview/examples/ManagedEnvironments_CreateOrUpdate.json
     */
    /**
     * Sample code: Create environments.
     *
     * @param manager Entry point to ContainerAppsApiManager.
     */
    public static void createEnvironments(com.azure.resourcemanager.appcontainers.ContainerAppsApiManager manager) {
        manager
            .managedEnvironments()
            .define("testcontainerenv")
            .withRegion("East US")
            .withExistingResourceGroup("examplerg")
            .withSku(new EnvironmentSkuProperties().withName(SkuName.PREMIUM))
            .withDaprAIConnectionString(
                "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://northcentralus-0.in.applicationinsights.azure.com/")
            .withVnetConfiguration(
                new VnetConfiguration()
                    .withOutboundSettings(
                        new ManagedEnvironmentOutboundSettings()
                            .withOutBoundType(ManagedEnvironmentOutBoundType.USER_DEFINED_ROUTING)
                            .withVirtualNetworkApplianceIp("192.168.1.20")))
            .withAppLogsConfiguration(
                new AppLogsConfiguration()
                    .withLogAnalyticsConfiguration(
                        new LogAnalyticsConfiguration().withCustomerId("string").withSharedKey("string")))
            .withZoneRedundant(true)
            .withCustomDomainConfiguration(
                new CustomDomainConfiguration()
                    .withDnsSuffix("www.my-name.com")
                    .withCertificateValue("PFX-or-PEM-blob".getBytes())
                    .withCertificatePassword("private key password".getBytes()))
            .withWorkloadProfiles(
                Arrays
                    .asList(
                        new WorkloadProfile()
                            .withWorkloadProfileType("GeneralPurpose")
                            .withMinimumCount(3)
                            .withMaximumCount(12),
                        new WorkloadProfile()
                            .withWorkloadProfileType("MemoryOptimized")
                            .withMinimumCount(3)
                            .withMaximumCount(6),
                        new WorkloadProfile()
                            .withWorkloadProfileType("ComputeOptimized")
                            .withMinimumCount(3)
                            .withMaximumCount(6)))
            .create();
    }
}


text:
SPEC_BEGIN(CJRATINGSPEC)

describe(@"Rating Model", ^{
  NSDictionary *stub = @{
                         @"id": @"crowd",
                         @"score": @7.5
                         };

  NSDictionary *textStub = @{
                         @"id": @"crowd",
                         @"score": @"Lorem ipsum"
                         };

  __block CJRating *rating;
  beforeEach(^{
    rating = [[CJRating alloc] initWithInfo:stub];
  });

  describe(@".ratingWithInfo", ^{
    it(@"Returns a new instance of a CJRating with the provided info", ^{
      rating = [CJRating ratingWithInfo:stub];

      [[rating.Id should] equal:stub[@"id"]];
    });
  });

  context(@"Mapping", ^{
    describe(@"#Id", ^{
      it(@"produces a correct mapping", ^{
        [[rating.Id should] equal:stub[@"id"]];
      });
    });

    context(@"When score is a number", ^{
      describe(@"#score", ^{
        it(@"produces a correct mapping", ^{
          [[rating.score should] equal:stub[@"score"]];
        });
      });
    });

    context(@"When score is a string", ^{
      beforeEach(^{
        rating = [[CJRating alloc] initWithInfo:textStub];
      });

      describe(@"#textReview", ^{
        it(@"produces a correct mapping", ^{
          [[rating.textReview should] equal:textStub[@"score"]];
        });
      });
    });
  });
});

SPEC_END


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class IntensityFlashLight : MonoBehaviour {

    [SerializeField]
    GameObject[] wavesGO;
    Image[] wavesImg;
    [SerializeField]
    PlayerController pController;

    Scripts.colors last_color = Scripts.colors.unknown;
    int currentIndex = 0;

    void Start ()
    {
        wavesImg = new Image[wavesGO.Length];
        for(int i = 0; i < wavesGO.Length; ++i)
        {
            wavesImg[i] = wavesGO[i].GetComponent<Image>();
        }
	}

	void Update ()
    {
        if (last_color != pController.fLColor)
        {
            if ((int)last_color - 1 < 0)
                last_color = (Scripts.colors)1;

            last_color = pController.fLColor;
            //Tint
            wavesImg[currentIndex].color = Scripts.getColor(last_color);
        }

        float intense = pController.flashLight.intensity;
        if (intense >= 2.0f && intense < 4.5f)
        {
            wavesGO[currentIndex].SetActive(false);
            currentIndex = 0;
            wavesGO[currentIndex].SetActive(true);

            wavesImg[currentIndex].color = Scripts.getColor(last_color);
        }
        else if (intense >= 4.5f && intense < 7.0f)
        {
            wavesGO[currentIndex].SetActive(false);
            currentIndex = 1;
            wavesGO[currentIndex].SetActive(true);

            wavesImg[currentIndex].color = Scripts.getColor(last_color);
        }
        else if (intense >= 7.0f && intense <= 8.0f)
        {
            wavesGO[currentIndex].SetActive(false);
            currentIndex = 2;
            wavesGO[currentIndex].SetActive(true);

            wavesImg[currentIndex].color = Scripts.getColor(last_color);
        }
    }

}


text:
package io.switchbit;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
}


text:
'use strict';

import React from 'react';
import { Link } from 'react-router';
import SwipeViews from 'react-swipe-views';
import Gist from './Gist.js';

export default class App extends React.Component {

  render() {
    return (
      <SwipeViews>
        <div title={<Link to="intro">Intro</Link>}>

A React component for binded Tabs and Swipeable Views

See
          Swipe Views on the Android Design Patterns website to understand the desired effect.

This demo is best viewed on a touch enabled device (real or emulated).

<button>Download</button>

        <div title={<Link to="code">Code</Link>}>
          <Gist />

        <div title={<Link to="thanks">Thanks</Link>}>

David Bruant for making me believe in JavaScript

React for being awesome

Babel for removing so much pain from transpiling/compiling/bundling

Dan Abramov for all the useful ressources, in this case React Hot Boilerplate

Hassan Hayat's Swipe Pages WebComponent for inspiration

Ferran Negre for helping me debug

<Link to="intro"><button>Back to Intro</button></Link>

      </SwipeViews>
    );
  }

}


text:
[ExtensionMethods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)
are a nice feature added in C# 3.0 that allow us to 'pretend' that
a method is an instance method of an object where really it's defined in
a static class outside of the type. This small difference can make a
huge step forward in readability:

Code with Linq query like this:

```c#
var query2 = people
			.Where(p => p.Age > 20)
			.OrderByDescending(p => p.Age)
			.ThenBy(p => p.Name));
```

will look like this without extension methods:

```c#
var query2 = Enumerable.ThenBy(
                Enumerable.OrderBy(
                   Enumerable.Where(
                        people,
                   p => p.Age > 20),
                p => p.Age),
             p => p.Name):
```

because all these methods are not implemented over
`IEnumerable<T>`.

The library avalanche (Advanced Topic)
--------------------------------------

This language feature has become so useful that many utility projects
have grown around the concept, an active [question](http://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-codeplex-com-extensionoverflow) about this.

It looks like everybody wants to make an 'standard' set of extension
methods, and in the way they introduce a new library, making the problem
bigger.

So, why bother doing a new one?

-   **Consistency**: It looks better for Signum Framework to depend on
    Signum.Utilities than on an external library.
-   **Control**: We prefer to have control over the library so we can
    add code we need.
-   **Clutter**: Extension methods tend to create clutter on your
    IntelliSense. We follow [Framework Design Guidelines](http://blogs.msdn.com/b/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx).


text:
require 'spec_helper'

describe 'Projects > Members > Group member cannot leave group project' do
  let(:user) { create(:user) }
  let(:group) { create(:group) }
  let(:project) { create(:project, namespace: group) }

  before do
    group.add_developer(user)
    sign_in(user)
    visit project_path(project)
  end

  it 'user does not see a "Leave project" link' do
    expect(page).not_to have_content 'Leave project'
  end
end


text:
; (function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ?
        module.exports = factory(require('./a'), require('./dir/b')) :
        typeof define === 'function' && define.amd ?
            define(['./a', './dir/b'], factory) :
            global.mymodule = factory(global.a, global.dir.b)
}(this, function (a, b) {
    return {
        bar: a.foo,
        foo: b.bar
    };
}));


text:
/** @babel */

import TerminalSession from '../lib/terminal-session';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('TerminalTab', () => {
  let workspaceElement, activationPromise;

  beforeEach(() => {
    workspaceElement = atom.views.getView(atom.workspace);
    activationPromise = atom.packages.activatePackage('terminal-tab');
  });

  describe('when the terminal:open event is triggered', () => {

    it('opens a new terminal', () => {

      // Ensure that the terminal view element is not present in the workspace.
      expect(workspaceElement.querySelector('terminal-view')).not.toExist();

      let terminalPromise = atom.commands.dispatch(workspaceElement, 'terminal:open');

      waitsForPromise(() => {
        return activationPromise;
      });

      waitsForPromise(() => {
        return terminalPromise;
      })

      runs(() => {
        // Ensure that the terminal view element is present in the workspace.
        const terminalViewElement = workspaceElement.querySelector('terminal-view');
        expect(terminalViewElement).toExist();

        // Ensure that the bottom dock is visible.
        let bottomDock = atom.workspace.getBottomDock();
        expect(bottomDock.isVisible()).toBe(true);

        // Ensure that the terminal view is present in the bottom dock's pane.
        let activePaneItem = bottomDock.getActivePaneItem();
        expect(activePaneItem).toBeInstanceOf(TerminalSession);
        let terminalView = atom.views.getView(activePaneItem);
        expect(terminalView).toEqual(terminalViewElement);
      });

    });

  });
});


text:
@protocol ActiveResourceProtocol

-(NSString *)resourceBaseURL;
-(NSString *)resourceName;
-(NSString *)resourcesName;
-(NSString *)format;

@end


text:
function submitEnabler() {
  if (nifValidator() &&
    nameValidator() &&
    surnameValidator() &&
    emailValidator() &&
    passChecker()) {
    $('#submit').removeClass('disabled');
  }
}

function styleValidator(id, condition) {
  if (condition) {
    $(id).removeClass('has-error');
    $(id).addClass('has-success');
  } else {
    // var focus = id.split('-');
    // console.log(focus[0]);
    $(id).removeClass('has-success');
    $(id).addClass('has-error');
    //$(focus[0]).focus();
  }
}

function nameValidator() {
  var name = $('#name').val();
  styleValidator('#name-group', name.length > 2);
  return name.length > 2;
}

function surnameValidator() {
  var surname = $('#surname').val();
  styleValidator('#surname-group', surname.length > 2);
  return surname.length > 2;
}

function nifValidator() {
  var nif = $('#nif').val();
  var patt = new RegExp('([\\d]{8})([- | \\s]?)([A-z])')

  if (patt.test(nif)) {
    var validator = true;
  } else {
    var validator = false;
  }

  styleValidator('#nif-group', validator);
  return validator;
}

function emailValidator() {
  var email = $("#email").val();
  var patt = new RegExp('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$');
  styleValidator('#email-group', patt.test(email));
  return patt.test(email);
}

function passwordValidator() {
  var password = $("#password").val();
  var patt = new RegExp('^(?=.*[A-z])(?=.*\\d)[A-z\\d]{8,}$');
  styleValidator('#password-group', patt.test(password));
  return patt.test(password);
}

function passChecker() {
  var password = $("#password").val();
  var passwordCheck = $("#password-check").val();
  styleValidator('#check-password-group', ((password == passwordCheck)));
  return password == passwordCheck;
}

function yearValidator() {
  var fullYear = $('#year').val();
  var date = new Date();
  var limit = date.getFullYear();

  var patt = new RegExp('(\\d{4})-(\\d{4})');

  if (patt.test(fullYear)) {
    fullYear = fullYear.split('-');
    var year = fullYear[0];
    var nextYear = fullYear[1];

    if (year <= limit && year == (nextYear - 1)) {
      var validator = true;
    } else {
      var validator = false;
    }

  } else {
    var validator = false;
  }

  styleValidator('#year-group', validator);
  return validator;
}

$(document).ready(function() {
  $('#name').focusout(function() {
    nameValidator();
  });

  $('#surname').focusout(function() {
    surnameValidator();
  });

  $('#nif').focusout(function() {
    nifValidator();
  });

  $('#email').focusout(function() {
    emailValidator();
  });

  $('#password').focusout(function() {
    passwordValidator();
  });

  $('#check-password').focusout(function() {
    passChecker();
  });

  $('#year').focusout(function() {
    yearValidator();
  });

  $('input').focusout(function() {
    submitEnabler();
  });
});


text:
import UnitTestCase from '@/__tests__/UnitTestCase'
import { expect, it } from 'vitest'
import { fireEvent } from '@testing-library/vue'
import ThemeCard from './ThemeCard.vue'

const theme: Theme = {
  id: 'sample',
  thumbnailColor: '#f00'
}

new class extends UnitTestCase {
  private renderComponent () {
    return this.render(ThemeCard, {
      props: {
        theme
      }
    })
  }

  protected test () {
    it('renders', () => {
      expect(this.renderComponent().html()).toMatchSnapshot()
    })

    it('emits an event when selected', async () => {
      const { emitted, getByTestId } = this.renderComponent()
      await fireEvent.click(getByTestId('theme-card-sample'))
      expect(emitted().selected[0]).toEqual([theme])
    })
  }
}