text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.amqp.implementation;

import com.azure.core.amqp.AmqpRetryOptions;
import com.azure.core.amqp.exception.AmqpErrorContext;
import com.azure.core.amqp.exception.AmqpException;
import com.azure.core.amqp.implementation.handler.ReceiveLinkHandler;
import com.azure.core.amqp.implementation.handler.SendLinkHandler;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.transaction.TransactionalState;
import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode;
import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.EndpointState;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Record;
import org.apache.qpid.proton.engine.Sender;
import org.apache.qpid.proton.engine.Session;
import org.apache.qpid.proton.message.Message;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.ReplayProcessor;
import reactor.test.StepVerifier;

import java.io.IOException;
import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Request response tests.
 */
class RequestResponseChannelTest {
    private static final String CONNECTION_ID = "some-id";
    private static final String NAMESPACE = "test fqdn";
    private static final String LINK_NAME = "test-link-name";
    private static final String ENTITY_PATH = "test-entity-path";
    private static final Duration TIMEOUT = Duration.ofSeconds(23);

    private final AmqpRetryOptions retryOptions = new AmqpRetryOptions().setTryTimeout(TIMEOUT);
    private final DirectProcessor<Delivery> deliveryProcessor = DirectProcessor.create();
    private final FluxSink<Delivery> deliverySink = deliveryProcessor.sink();
    private final ReplayProcessor<EndpointState> endpointStateReplayProcessor = ReplayProcessor.cacheLast();

    @Mock
    private ReactorHandlerProvider handlerProvider;
    @Mock
    private ReactorProvider reactorProvider;
    @Mock
    private ReactorDispatcher reactorDispatcher;
    @Mock
    private ReceiveLinkHandler receiveLinkHandler;
    @Mock
    private SendLinkHandler sendLinkHandler;

    @Mock
    private Session session;
    @Mock
    private Sender sender;
    @Mock
    private Receiver receiver;
    @Mock
    private MessageSerializer serializer;
    @Captor
    private ArgumentCaptor<Runnable> dispatcherCaptor;

    @BeforeAll
    static void beforeAll() {
        StepVerifier.setDefaultTimeout(Duration.ofSeconds(10));
    }

    @AfterAll
    static void afterAll() {
        StepVerifier.resetDefaultTimeout();
    }

    @BeforeEach
    void beforeEach() {
        MockitoAnnotations.initMocks(this);

        when(reactorProvider.getReactorDispatcher()).thenReturn(reactorDispatcher);

        final Record record = mock(Record.class);
        when(sender.attachments()).thenReturn(record);
        when(receiver.attachments()).thenReturn(record);

        when(session.sender(LINK_NAME + ":sender")).thenReturn(sender);
        when(session.receiver(LINK_NAME + ":receiver")).thenReturn(receiver);

        when(handlerProvider.createReceiveLinkHandler(eq(CONNECTION_ID), eq(NAMESPACE), eq(LINK_NAME), eq(ENTITY_PATH)))
            .thenReturn(receiveLinkHandler);
        when(handlerProvider.createSendLinkHandler(CONNECTION_ID, NAMESPACE, LINK_NAME, ENTITY_PATH))
            .thenReturn(sendLinkHandler);

        FluxSink<EndpointState> sink1 = endpointStateReplayProcessor.sink();
        sink1.next(EndpointState.ACTIVE);
        when(receiveLinkHandler.getEndpointStates()).thenReturn(endpointStateReplayProcessor);
        when(receiveLinkHandler.getDeliveredMessages()).thenReturn(deliveryProcessor);

        when(sendLinkHandler.getEndpointStates()).thenReturn(endpointStateReplayProcessor);
    }

    @AfterEach
    void afterEach() {
        Mockito.framework().clearInlineMocks();
    }

    /**
     * Validate that this gets and sets properties correctly.
     */
    @Test
    void getsProperties() {
        // Arrange
        SenderSettleMode settleMode = SenderSettleMode.SETTLED;
        ReceiverSettleMode receiverSettleMode = ReceiverSettleMode.SECOND;
        AmqpErrorContext expected = new AmqpErrorContext("namespace-test");
        when(receiveLinkHandler.getErrorContext(receiver)).thenReturn(expected);

        // Act
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, settleMode,
            receiverSettleMode);
        final AmqpErrorContext errorContext = channel.getErrorContext();

        channel.dispose();

        // Assert
        assertEquals(expected, errorContext);

        verify(sender).setTarget(argThat(t -> t != null && ENTITY_PATH.equals(t.getAddress())));
        verify(sender).setSenderSettleMode(settleMode);

        verify(receiver).setTarget(argThat(t -> t != null && t.getAddress().startsWith(ENTITY_PATH)));
        verify(receiver).setSource(argThat(s -> s != null && ENTITY_PATH.equals(s.getAddress())));
        verify(receiver).setReceiverSettleMode(receiverSettleMode);
    }

    @Test
    void disposes() {
        // Arrange
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);

        // Act
        channel.dispose();

        // Assert
        verify(sender).close();
        verify(receiver).close();
    }

    /**
     * Verifies error when sending with null
     */
    @Test
    void sendNull() {
        // Arrange
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);

        // Act & Assert
        StepVerifier.create(channel.sendWithAck(null))
            .expectError(NullPointerException.class)
            .verify();
    }

    /**
     * Verifies error when sending with a reply to property set.
     */
    @Test
    void sendReplyToSet() {
        // Arrange
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);
        final Message message = mock(Message.class);
        when(message.getReplyTo()).thenReturn("test-reply-to");

        // Act & Assert
        StepVerifier.create(channel.sendWithAck(message))
            .expectError(IllegalArgumentException.class)
            .verify();
    }

    /**
     * Verifies error when sending with message id is set.
     */
    @Test
    void sendMessageIdSet() {
        // Arrange
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);
        final Message message = mock(Message.class);
        when(message.getMessageId()).thenReturn(10L);

        // Act & Assert
        StepVerifier.create(channel.sendWithAck(message))
            .expectError(IllegalArgumentException.class)
            .verify();
    }
    /**
     * Verifies a message is received.
     */
    @Test
    void sendMessageWithTransaction() throws IOException {
        // Arrange
        // This message was copied from one that was received.
        TransactionalState transactionalState = new TransactionalState();
        transactionalState.setTxnId(new Binary("1".getBytes()));

        final byte[] messageBytes = new byte[]{0, 83, 115, -64, 15, 13, 64, 64, 64, 64, 64, 83, 1, 64, 64, 64, 64, 64,
            64, 64, 0, 83, 116, -63, 49, 4, -95, 11, 115, 116, 97, 116, 117, 115, 45, 99, 111, 100, 101, 113, 0, 0, 0,
            -54, -95, 18, 115, 116, 97, 116, 117, 115, 45, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, -95, 8,
            65, 99, 99, 101, 112, 116, 101, 100};
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);
        final UnsignedLong messageId = UnsignedLong.valueOf(1);
        final Message message = mock(Message.class);
        final int encodedSize = 143;
        when(serializer.getSize(message)).thenReturn(150);
        when(message.encode(any(), eq(0), anyInt())).thenReturn(encodedSize);
        when(message.getCorrelationId()).thenReturn(messageId);
        // Creating delivery for sending.
        final Delivery deliveryToSend = mock(Delivery.class);
        doNothing().when(deliveryToSend).setMessageFormat(anyInt());
        doNothing().when(deliveryToSend).disposition(any(TransactionalState.class));
        when(sender.delivery(any(byte[].class))).thenReturn(deliveryToSend);

        // Creating a received message because we decodeDelivery calls implementation details for proton-j.
        final Delivery delivery = mock(Delivery.class);
        when(delivery.pending()).thenReturn(messageBytes.length);
        when(receiver.recv(any(), eq(0), eq(messageBytes.length))).thenAnswer(invocation -> {
            final byte[] buffer = invocation.getArgument(0);
            System.arraycopy(messageBytes, 0, buffer, 0, messageBytes.length);
            return messageBytes.length;
        });

        // Act
        StepVerifier.create(channel.sendWithAck(message, transactionalState))
            .then(() -> deliverySink.next(delivery))
            .assertNext(received -> assertEquals(messageId, received.getCorrelationId()))
            .verifyComplete();

        // Getting the runnable so we can manually invoke it and verify contents are correct.
        verify(reactorDispatcher, atLeastOnce()).invoke(dispatcherCaptor.capture());
        dispatcherCaptor.getAllValues().forEach(work -> {
            assertNotNull(work);
            work.run();
        });

        // Assert
        verify(message).setMessageId(argThat(e -> e instanceof UnsignedLong && messageId.equals(e)));
        verify(message).setReplyTo(argThat(path -> path != null && path.startsWith(ENTITY_PATH)));

        verify(deliveryToSend).disposition(same(transactionalState));

        verify(receiver).flow(1);
        verify(sender).delivery(any());
        verify(sender).send(any(), eq(0), eq(encodedSize));
        verify(sender).advance();
    }

    /**
     * Verifies a message is received.
     */
    @Test
    void sendMessage() throws IOException {
        // Arrange
        // This message was copied from one that was received.
        final byte[] messageBytes = new byte[]{0, 83, 115, -64, 15, 13, 64, 64, 64, 64, 64, 83, 1, 64, 64, 64, 64, 64,
            64, 64, 0, 83, 116, -63, 49, 4, -95, 11, 115, 116, 97, 116, 117, 115, 45, 99, 111, 100, 101, 113, 0, 0, 0,
            -54, -95, 18, 115, 116, 97, 116, 117, 115, 45, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, -95, 8,
            65, 99, 99, 101, 112, 116, 101, 100};
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);
        final UnsignedLong messageId = UnsignedLong.valueOf(1);
        final Message message = mock(Message.class);
        final int encodedSize = 143;
        when(serializer.getSize(message)).thenReturn(150);
        when(message.encode(any(), eq(0), anyInt())).thenReturn(encodedSize);
        when(message.getCorrelationId()).thenReturn(messageId);

        // Creating delivery for sending.
        final Delivery deliveryToSend = mock(Delivery.class);
        doNothing().when(deliveryToSend).setMessageFormat(anyInt());
        when(sender.delivery(any(byte[].class))).thenReturn(deliveryToSend);

        // Creating a received message because we decodeDelivery calls implementation details for proton-j.
        final Delivery delivery = mock(Delivery.class);
        when(delivery.pending()).thenReturn(messageBytes.length);
        when(receiver.recv(any(), eq(0), eq(messageBytes.length))).thenAnswer(invocation -> {
            final byte[] buffer = invocation.getArgument(0);
            System.arraycopy(messageBytes, 0, buffer, 0, messageBytes.length);
            return messageBytes.length;
        });

        // Act
        StepVerifier.create(channel.sendWithAck(message))
            .then(() -> deliverySink.next(delivery))
            .assertNext(received -> assertEquals(messageId, received.getCorrelationId()))
            .verifyComplete();

        // Getting the runnable so we can manually invoke it and verify contents are correct.
        verify(reactorDispatcher, atLeastOnce()).invoke(dispatcherCaptor.capture());
        dispatcherCaptor.getAllValues().forEach(work -> {
            assertNotNull(work);
            work.run();
        });

        // Assert
        verify(message).setMessageId(argThat(e -> e instanceof UnsignedLong && messageId.equals(e)));
        verify(message).setReplyTo(argThat(path -> path != null && path.startsWith(ENTITY_PATH)));

        verify(receiver).flow(1);
        verify(sender).delivery(any());
        verify(sender).send(any(), eq(0), eq(encodedSize));
        verify(sender).advance();
    }

    @Test
    void clearMessagesOnError() {
        // Arrange
        final RequestResponseChannel channel = new RequestResponseChannel(CONNECTION_ID, NAMESPACE, LINK_NAME,
            ENTITY_PATH, session, retryOptions, handlerProvider, reactorProvider, serializer, SenderSettleMode.SETTLED,
            ReceiverSettleMode.SECOND);
        final AmqpException error = new AmqpException(true, "Message", new AmqpErrorContext("some-context"));
        final Message message = mock(Message.class);
        when(serializer.getSize(message)).thenReturn(150);
        when(message.encode(any(), eq(0), anyInt())).thenReturn(143);

        // Act
        StepVerifier.create(channel.sendWithAck(message))
            .then(() -> endpointStateReplayProcessor.sink().error(error))
            .verifyError(AmqpException.class);

        // Assert
        assertTrue(channel.isDisposed());
    }

}


text:
<input type="file"
    {%- if id is defined %} id="{{ id }}"{% endif %}
    {%- if class is defined %} class="{{ class }}"{% endif %}
    {%- if name is defined %} name="{{ name }}"{% endif %}
    {%- if autofocus is defined and autofocus and not craft.app.request.isMobileBrowser(true) %} autofocus{% endif %}
    {%- if disabled is defined and disabled %} disabled{% endif %}
    {%- if block('attr') is defined %} {{ block('attr') }}{% endif %}>

redpajama_set_name: RedPajamaGithub


text:
exclude :test_establishing_a_connection_in_connected_to_block_uses_current_role_and_shard, 'tries to load SQLite3 driver'
exclude :test_establish_connection_using_3_levels_config, 'tries to load SQLite3 driver'
exclude :test_establish_connection_using_3_levels_config_with_shards_and_replica, 'tries to load SQLite3 driver'
exclude :test_switching_connections_via_handler, 'tries to load SQLite3 driver'
exclude :test_retrieves_proper_connection_with_nested_connected_to, 'tries to load SQLite3 driver'
exclude :test_retrieves_proper_connection_with_nested_connected_to_on_abstract_classes, 'tries to load SQLite3 driver'
exclude :test_same_shards_across_clusters, 'tries to load SQLite3 driver'
exclude :test_sharding_separation, 'tries to load SQLite3 driver'
exclude :test_swapping_shards_globally_in_a_multi_threaded_environment, 'tries to load SQLite3 driver'
exclude :test_swapping_shards_and_roles_in_a_multi_threaded_environment, 'tries to load SQLite3 driver'
exclude :test_swapping_granular_shards_and_roles_in_a_multi_threaded_environment, 'tries to load SQLite3 driver'


text:
package org.springframework.boot.configurationdocs;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Options for generating documentation for configuration properties.
 *
 * @author Brian Clozel
 */
public final class DocumentOptions {

	private final Map<String, List<String>> metadataSections;

	private final Map<String, String> overrides;

	private DocumentOptions(Map<String, List<String>> metadataSections,
			Map<String, String> overrides) {
		this.metadataSections = metadataSections;
		this.overrides = overrides;
	}

	Map<String, List<String>> getMetadataSections() {
		return this.metadataSections;
	}

	Map<String, String> getOverrides() {
		return this.overrides;
	}

	static Builder builder() {
		return new Builder();
	}

	/**
	 * Builder for DocumentOptions.
	 */
	public static class Builder {

		Map<String, List<String>> metadataSections = new HashMap<>();

		Map<String, String> overrides = new HashMap<>();

		SectionSpec addSection(String name) {
			return new SectionSpec(this, name);
		}

		Builder addOverride(String keyPrefix, String description) {
			this.overrides.put(keyPrefix, description);
			return this;
		}

		DocumentOptions build() {
			return new DocumentOptions(this.metadataSections, this.overrides);
		}

	}

	/**
	 * Configuration for a documentation section listing properties for a specific theme.
	 */
	public static class SectionSpec {

		private final String name;

		private final Builder builder;

		SectionSpec(Builder builder, String name) {
			this.builder = builder;
			this.name = name;
		}

		Builder withKeyPrefixes(String... keyPrefixes) {
			this.builder.metadataSections.put(this.name, Arrays.asList(keyPrefixes));
			return this.builder;
		}

	}

}


text:
/*
 * Copyright (c) 2011-2016 Spotify AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.spotify.google.cloud.pubsub.client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

class ConfigurableSSLSocketFactory extends SSLSocketFactory {

  private final String[] enabledCipherSuites;
  private final SSLSocketFactory sslSocketFactory;

  ConfigurableSSLSocketFactory(final String[] enabledCipherSuites, final SSLSocketFactory sslSocketFactory) {
    this.enabledCipherSuites = enabledCipherSuites;
    this.sslSocketFactory = sslSocketFactory;
  }

  @Override
  public String[] getDefaultCipherSuites() {
    return enabledCipherSuites;
  }

  @Override
  public String[] getSupportedCipherSuites() {
    return enabledCipherSuites;
  }

  @Override
  public Socket createSocket(final Socket sock, final String host, final int port, final boolean autoClose)
      throws IOException {
    final SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(sock, host, port, autoClose);
    if (enabledCipherSuites != null) {
      s.setEnabledCipherSuites(enabledCipherSuites);
    }
    return s;
  }

  @Override
  public Socket createSocket(final String host, final int port) throws IOException {
    final SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(host, port);
    if (enabledCipherSuites != null) {
      s.setEnabledCipherSuites(enabledCipherSuites);
    }
    return s;
  }

  @Override
  public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort)
      throws IOException {
    final SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(host, port, localAddress, localPort);
    if (enabledCipherSuites != null) {
      s.setEnabledCipherSuites(enabledCipherSuites);
    }
    return s;
  }

  @Override
  public Socket createSocket(final InetAddress host, final int port) throws IOException {
    final SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(host, port);
    if (enabledCipherSuites != null) {
      s.setEnabledCipherSuites(enabledCipherSuites);
    }
    return s;
  }

  @Override
  public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                             final int localPort)
      throws IOException {
    final SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(host, port, localAddress, localPort);
    if (enabledCipherSuites != null) {
      s.setEnabledCipherSuites(enabledCipherSuites);
    }
    return s;
  }
}


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.sandbox;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableMap;
import com.google.devtools.common.options.OptionsParsingException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@code SandboxOptions}. */
@RunWith(JUnit4.class)
public final class SandboxOptionsTest {

  private ImmutableMap.Entry<String, String> pathPair;

  @Test
  public void testParsingAdditionalMounts_SinglePathWithoutColonSucess() throws Exception {
    String source = "/a/bc/def/gh";
    String target = source;
    String input = source;
    pathPair = new SandboxOptions.MountPairConverter().convert(input);
    assertMountPair(pathPair, source, target);
  }

  @Test
  public void testParsingAdditionalMounts_SinglePathWithColonSucess() throws Exception {
    String source = "/a/b:c/def/gh";
    String target = source;
    String input = "/a/b\\:c/def/gh";
    pathPair = new SandboxOptions.MountPairConverter().convert(input);
    assertMountPair(pathPair, source, target);
  }

  @Test
  public void testParsingAdditionalMounts_PathPairWithoutColonSucess() throws Exception {
    String source = "/a/bc/def/gh";
    String target = "/1/2/3/4/5";
    String input = source + ":" + target;
    pathPair = new SandboxOptions.MountPairConverter().convert(input);
    assertMountPair(pathPair, source, target);
  }

  @Test
  public void testParsingAdditionalMounts_PathPairWithColonSucess() throws Exception {
    String source = "/a:/bc:/d:ef/gh";
    String target = ":/1/2/3/4/5";
    String input = "/a\\:/bc\\:/d\\:ef/gh:\\:/1/2/3/4/5";
    pathPair = new SandboxOptions.MountPairConverter().convert(input);
    assertMountPair(pathPair, source, target);
  }

  @Test
  public void testParsingAdditionalMounts_TooManyPaths() throws Exception {
    String input = "a/bc/def/gh:/1/2/3:x/y/z";
    OptionsParsingException e =
        assertThrows(
            OptionsParsingException.class,
            () -> pathPair = new SandboxOptions.MountPairConverter().convert(input));
    assertThat(e)
        .hasMessageThat()
        .isEqualTo(
            "Input must be a single path to mount inside the sandbox or "
                + "a mounting pair in the form of 'source:target'");
  }

  @Test
  public void testParsingAdditionalMounts_EmptyInput() throws Exception {
    String input = "";
    OptionsParsingException e =
        assertThrows(
            OptionsParsingException.class,
            () -> pathPair = new SandboxOptions.MountPairConverter().convert(input));
    assertThat(
            "Input "
                + input
                + " contains one or more empty paths. "
                + "Input must be a single path to mount inside the sandbox or "
                + "a mounting pair in the form of 'source:target'")
        .isEqualTo(e.getMessage());
  }

  private static void assertMountPair(
      ImmutableMap.Entry<String, String> pathPair, String source, String target) {
    assertThat(source).isEqualTo(pathPair.getKey());
    assertThat(target).isEqualTo(pathPair.getValue());
  }
}


text:
<?php

namespace Comodojo\Exception;

use \Psr\Cache\CacheException as PsrCacheException;
use \Exception;

class CacheException extends Exception implements PsrCacheException
{
}


text:
import rospy
from sensor_msgs.msg import JointState
from segway_rmp.msg import SegwayStatusStamped

def segway_callback(segway_msg):
    jointstate_msg = JointState()
    jointstate_msg.header.stamp = segway_msg.header.stamp
    jointstate_msg.name = [
        '/segway_wheel_left',
        '/segway_wheel_right',
    ]
    jointstate_msg.position = [
        -segway_msg.segway.left_wheel_displacement,
        -segway_msg.segway.right_wheel_displacement,
    ]
    jointstate_msg.velocity = [
        -segway_msg.segway.left_wheel_velocity,
        -segway_msg.segway.right_wheel_velocity,
    ]
    jointstate_msg.effort = [
        -segway_msg.segway.left_motor_torque,
        -segway_msg.segway.right_motor_torque,
    ]

    jointstate_pub.publish(jointstate_msg)

def main():
    global jointstate_pub, joint_prefix

    rospy.init_node('segway_relay')

    jointstate_pub = rospy.Publisher('/joint_states', JointState)
    wamstate_sub = rospy.Subscriber('segway_status', SegwayStatusStamped,
                                    segway_callback)

    rospy.spin()

if __name__ == '__main__':
    main()


text:
@class KivaImage;

@interface KivaPartner : NSObject <FromJSON>

@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) NSURL *url;
@property (nonatomic, readonly) NSNumber *averageLoanSizePercentPerCapitaIncome;
@property (nonatomic, getter = doesChargeFeesAndInterest) BOOL chargesFeesAndInterest;
@property (nonatomic, readonly) NSArray *countries;
@property (nonatomic, readonly) NSNumber *currencyExchangeLossRate;
@property (nonatomic, readonly) NSNumber *defaultRate;
@property (nonatomic, readonly) NSString *defaultRateNote;
@property (nonatomic, readonly) NSNumber *delinquencyRate;
@property (nonatomic, readonly) NSString *delinquencyRateNote;
@property (nonatomic, readonly) NSNumber *partnerId;
@property (nonatomic, readonly) KivaImage *image;
@property (nonatomic, readonly) NSNumber *loansAtRiskRate;
@property (nonatomic, readonly) NSNumber *loansPosted;
@property (nonatomic, readonly) NSString *portfolioYieldNote;
@property (nonatomic, readonly) NSString *rating;
@property (nonatomic, readonly) NSDate *startDate;
@property (nonatomic, readonly) NSString *status;
@property (nonatomic, readonly) NSNumber *totalAmountRaised;

@end


text:
package com.bookofbrilliantthings.callgrind4j;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

public class CallgrindClassVisitor extends ClassVisitor {

  public CallgrindClassVisitor(final int flags, final ClassWriter classWriter) {
    super(flags, classWriter);
  }

  // TODO Auto-generated constructor stub
}


text:
<?php

namespace IPS\Data\Cache;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * XCache Storage Class
 */
class _Xcache extends \IPS\Data\Cache
{
	/**
	 * Server supports this method?
	 *
	 * @return	bool
	 */
	public static function supported()
	{
		return function_exists('xcache_get');
	}

	/**
	 * Abstract Method: Get
	 *
	 * @param	string	$key	Key
	 * @return	string	Value from the _datastore
	 */
	protected function get( $key )
	{
		if( isset( $this->cache[ $key ] ) )
		{
			\IPS\Log::debug( "Get {$key} from Xcache (already loaded)", 'cache' );
			return $this->cache[ $key ];
		}

		\IPS\Log::debug( "Get {$key} from Xcache", 'cache' );

		$this->cache[ $key ]	= xcache_get( \IPS\SUITE_UNIQUE_KEY . '_' . $key );
		return $this->cache[ $key ];
	}

	/**
	 * Abstract Method: Set
	 *
	 * @param	string			$key	Key
	 * @param	string			$value	Value
	 * @para,	\IPS\DateTime	$expire	Expreation time, or NULL for no expiration
	 * @return	bool
	 */
	protected function set( $key, $value, \IPS\DateTime $expire = NULL )
	{
		\IPS\Log::debug( "Set {$key} in Xcache", 'cache' );
		return (bool) xcache_set( \IPS\SUITE_UNIQUE_KEY . '_' . $key, $value, $expire ? ( $expire->getTimestamp() - time() ) : 0 );
	}

	/**
	 * Abstract Method: Exists?
	 *
	 * @param	string	$key	Key
	 * @return	bool
	 */
	protected function exists( $key )
	{
		if( isset( $this->cache[ $key ] ) )
		{
			\IPS\Log::debug( "Check exists {$key} from Xcache (already loaded)", 'cache' );
			return TRUE;
		}

		\IPS\Log::debug( "Check exists {$key} from Xcache", 'cache' );
		return xcache_isset( \IPS\SUITE_UNIQUE_KEY . '_' . $key );
	}

	/**
	 * Abstract Method: Delete
	 *
	 * @param	string	$key	Key
	 * @return	bool
	 */
	protected function delete( $key )
	{
		\IPS\Log::debug( "Delete {$key} from Xcache", 'cache' );
		return (bool) xcache_unset( \IPS\SUITE_UNIQUE_KEY . '_' . $key );
	}
}


text:
package org.kie.workbench.common.dmn.client.marshaller.converters.dd;

import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dc.JSIColor;

public class ColorUtils {

    public static JSIColor dmnFromWB(final String colorString) {
        final JSIColor result = new JSIColor();

        try {
            final int i = Integer.decode(colorString);
            result.setRed((i >> 16) & 0xFF);
            result.setGreen((i >> 8) & 0xFF);
            result.setBlue(i & 0xFF);
        } catch (final NumberFormatException nfe) {
            //Return default
        }

        return result;
    }

    public static String wbFromDMN(final JSIColor color) {
        return "#" + toHexString(color.getRed()) + toHexString(color.getGreen()) + toHexString(color.getBlue());
    }

    private static String toHexString(final int value) {
        final String hex = Integer.toHexString(value & 0xFF);
        return hex.length() > 1 ? hex : "0" + hex;
    }
}


text:
'use strict';
/**
 * Takes a sorted array and a function p. The array is sorted in such a way that all elements where p(x) is false
 * are located before all elements where p(x) is true.
 * @returns the least x for which p(x) is true or array.length if no element fullfills the given function.
 */
export function findFirst(array, p) {
    var low = 0, high = array.length;
    if (high === 0) {
        return 0; // no children
    }
    while (low < high) {
        var mid = Math.floor((low + high) / 2);
        if (p(array[mid])) {
            high = mid;
        }
        else {
            low = mid + 1;
        }
    }
    return low;
}
export function includes(array, item) {
    return array.indexOf(item) !== -1;
}
export function union() {
    var arrays = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        arrays[_i] = arguments[_i];
    }
    var result = [];
    for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
        var array = arrays_1[_a];
        for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
            var item = array_1[_b];
            if (!includes(result, item)) {
                result.push(item);
            }
        }
    }
    return result;
}


text:
"""Wrapper around vtctl execute_vtctl_command for sandboxes.

Note: This also provides a backup option of using kvtctl.sh, a kubernetes script
used to temporarily forward a port if vtctld has no forwarded port.

TODO(thompsonja): This is heavily tied to the kubernetes and will need to be
updated if other systems are used.
"""

import json
import os
import subprocess
import threading
import time

class Command(object):

  def __init__(self, cmd):
    self.cmd = cmd
    self.process = None
    self.stdout = None
    self.stderr = None

  def run(self, timeout_s):
    """Runs the vtctl command."""
    def target():
      self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE)
      self.stdout, self.stderr = self.process.communicate()

    thread = threading.Thread(target=target)
    thread.start()

    thread.join(timeout_s)
    if thread.is_alive():
      self.process.terminate()
      thread.join()
    return self.process.returncode

def execute_vtctl_command(vtctl_args, namespace='default', timeout_s=180):
  """Executes a vtctl command with some retry logic."""
  vtctl_cmd_args = []
  vtctld_info = json.loads(subprocess.check_output(
      ['kubectl', 'get', 'service', 'vtctld', '--namespace=%s' % namespace,
       '-o', 'json']))
  try:
    # Check to see if the vtctld service has a forwarded port.
    ip = vtctld_info['status']['loadBalancer']['ingress'][0]['ip']
    vtctl_cmd_args = ['vtctlclient', '-server', '%s:15999' % ip] + vtctl_args
  except (KeyError, IndexError):
    pass
  if not vtctl_cmd_args:
    # Default to trying to use kvtctl.sh if a forwarded port cannot be found.
    os.environ['VITESS_NAME'] = namespace
    vtctl_cmd_args = (
        [os.path.join(os.environ['VTTOP'], 'examples/kubernetes/kvtctl.sh')]
        + vtctl_args)

  start_time = time.time()
  while time.time() - start_time < timeout_s:
    cmd = Command(vtctl_cmd_args)
    retcode = cmd.run(10)
    if cmd.stdout.startswith('Starting port forwarding'):
      # Ignore this extra output line if using kvtctl.sh
      cmd.stdout = cmd.stdout[cmd.stdout.find('\n')+1:]
    if retcode:
      last_error = 'Failed w/ errorcode %d, stdout %s, stderr %s' % (
          cmd.process.returncode, cmd.stdout, cmd.stderr)
    else:
      return cmd.stdout, True

  return ('Last error running %s: %s' % (' '.join(vtctl_cmd_args), last_error),
          False)


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Loading } from 'cf-component-loading';
import { combineRules, createComponent } from 'cf-style-container';

const active = ({ active, theme }) => {
  if (!active) return {};

  return {
    color: theme.colorActive,
    borderColor: theme.borderColorActive,
    backgroundColor: theme.backgroundColorActive,
    zIndex: theme.zIndexActive,
    cursor: theme.cursorActive
  };
};

const disabled = ({ disabled, theme }) => {
  if (!disabled) return {};

  return {
    color: theme.colorDisabled,
    backgroundColor: theme.backgroundColorDisabled,
    cursor: theme.cursorDisabled
  };
};

const normal = ({ theme, type: itemType }) => ({
  float: theme.float,
  position: theme.position,
  backgroundColor: theme.backgroundColor,
  color: theme.color,
  border: theme.border,
  borderBottomWidth: theme.borderBottomWidth,
  cursor: theme.cursor,
  ...theme[itemType]
});

const styles = combineRules(normal, active, disabled);

const Link = createComponent(
  ({ theme, disabled, active }) => {
    let cursor = theme.cursor;
    if (disabled) {
      cursor = theme.cursorDisabled;
    }
    if (active) {
      cursor = theme.cursorActive;
    }

    return {
      userSelect: theme.link.userSelect,
      position: theme.link.position,
      display: theme.link.display,
      paddingTop: theme.link.paddingTop,
      paddingBottom: theme.link.paddingBottom,
      paddingLeft: theme.link.paddingLeft,
      paddingRight: theme.link.paddingRight,
      textDecoration: theme.link.textDecoration,
      color: theme.link.color,
      cursor: cursor,
      ':focus': {
        zIndex: theme.link['zIndex:focus']
      }
    };
  },
  'a',
  ['onClick', 'href', 'aria-label']
);

class PaginationItem extends React.Component {
  constructor() {
    super();

    this.onClick = this.onClick.bind(this);
  }

  onClick(event) {
    event.preventDefault();
    this.props.onClick();
  }

  render() {
    const props = this.props;
    const isEllipsis = props.type === 'ellipsis';
    const isLoading = props.type === 'loading';

    const role = isEllipsis ? 'presentation' : null;

    let children;

    if (isEllipsis) {
      children = …;
    } else if (isLoading) {
      children = <Loading />;
    } else {
      children = props.children;
    }

    return (

        <Link
          onClick={this.onClick}
          href="#"
          aria-label={props.label}
          active={props.active}
          disabled={props.disabled}
        >
          {children}
        </Link>

    );
  }
}

PaginationItem.propTypes = {
  type: PropTypes.oneOf([
    'number',
    'next',
    'prev',
    'ellipsis',
    'loading',
    'dot'
  ]).isRequired,
  active: PropTypes.bool,
  disabled: PropTypes.bool,
  children: PropTypes.node,
  onClick: PropTypes.func
};

PaginationItem.defaultProps = {
  disabled: false
};

export default createComponent(styles, PaginationItem);


text:
package app.ebank.com.ebank.model;

/**
 * Created by Haden on 2016/7/11.
 */
public class Zhangdan {

    private String zhangdan_time;

    private String zhangdan_type;

    private String zhangdan_sum;

    private String zhangdan_balance;

    public Zhangdan(String zhagndan_time, String zhangdan_type, String zhangdan_sum,String zhangdan_balance){
        this.zhangdan_time = zhagndan_time;
        this.zhangdan_type = zhangdan_type;
        this.zhangdan_sum = zhangdan_sum;
        this.zhangdan_balance = zhangdan_balance;
    }

    public String getZhangdan_time(){
        return zhangdan_time;
    }

    public String getZhangdan_type(){
        return zhangdan_type;
    }

    public String getZhangdan_sum(){
        return zhangdan_sum;
    }

    public String getZhangdan_balance(){
        return zhangdan_balance;
    }
}


text:
var assert = require('assert');
var ospos = require('./ospos');

describe("test receiving quantity", function() {

    var def_timeout = 10000;

    var item = {
        name: "recvQty",
        category: "aCategory",
        cost_price: 10,
        unit_price: 20,
        receiving_quantity: 2
    };

    it("should be able to create item with receiving quantity", function(done) {
        return ospos.create_item(this.browser, item).then(done, done);
    });

    it("should be able to receive quantities with multiplier", function(done) {
        this.browser.get(ospos.url('/index.php/receivings')).elementById("item").clear().type(item.name)
            .elementByCssSelector(".ui-autocomplete .ui-menu-item", def_timeout).click()
            .elementByName("quantity")
            .elementByCssSelector("#cart_contents tr td:nth-child(5)").text().then(function(value) {
                assert(value, "x "  + item.receiving_quantity, "receiving quantity " + item.receiving_quantity + " is not displayed correctly in receivings module!");
            }).elementById("finish_receiving_button", def_timeout).submit()
            .elementByCssSelector("#receipt_items tr:nth-child(2) td:nth-last-child(2)", def_timeout).text().then(function(value) {
                assert(value, "1    x " + item.receiving_quantity, "receiving quantity " + item.receiving_quantity + " is not displayed correctly on receipt!!");
            }).then(done, done);
    });

});


text:
#ifndef SPROKIT_PIPELINE_UTIL_LOAD_PIPE_H
#define SPROKIT_PIPELINE_UTIL_LOAD_PIPE_H

#include "pipeline_util-config.h"

#include "path.h"
#include "pipe_declaration_types.h"

#include <iosfwd>

/**
 * \file load_pipe.h
 *
 * \brief Load a pipeline declaration from a stream.
 */

namespace sprokit
{

/**
 * \brief Convert a pipeline description file into a collection of pipeline blocks.
 *
 * \param fname The file to load the pipeline blocks from.
 *
 * \returns A new set of pipeline blocks.
 */
SPROKIT_PIPELINE_UTIL_EXPORT pipe_blocks load_pipe_blocks_from_file(path_t const& fname);

/**
 * \brief Convert a pipeline description into a pipeline.
 *
 * \param istr The stream to load the pipeline from.
 * \param inc_root The root directory to search for includes from.
 *
 * \returns A new set of pipeline blocks.
 */
SPROKIT_PIPELINE_UTIL_EXPORT pipe_blocks load_pipe_blocks(std::istream& istr, path_t const& inc_root = "");

/**
 * \brief Convert a cluster description file into a collection of cluster blocks.
 *
 * \param fname The file to load the cluster blocks from.
 *
 * \returns A new set of cluster blocks.
 */
cluster_blocks SPROKIT_PIPELINE_UTIL_EXPORT load_cluster_blocks_from_file(path_t const& fname);

/**
 * \brief Convert a cluster description into a cluster.
 *
 * \param istr The stream to load the cluster from.
 * \param inc_root The root directory to search for includes from.
 *
 * \returns A new set of cluster blocks.
 */
cluster_blocks SPROKIT_PIPELINE_UTIL_EXPORT load_cluster_blocks(std::istream& istr, path_t const& inc_root = "");

}

#endif // SPROKIT_PIPELINE_UTIL_LOAD_PIPE_H


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Profiler
{
	/// <summary>
	/// Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started.
	/// </summary>
	[CommandResponse(ProtocolName.Profiler.TakePreciseCoverage)]
	[SupportedBy("Chrome")]
	public class TakePreciseCoverageCommandResponse
	{
		/// <summary>
		/// Gets or sets Coverage data for the current isolate.
		/// </summary>
		public ScriptCoverage[] Result { get; set; }
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015 Coder.HanXin
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/brand_text"
                android:orientation="vertical"
    >

    <RelativeLayout
        android:id="@+id/drawer_item_backup"
        android:layout_width="match_parent"
        android:layout_height="@dimen/list_item_height_small"
        android:layout_marginTop="@dimen/spacing_normal"
        >

        <ImageView
            android:id="@+id/imageView_backup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/spacing_small"
            android:src="@drawable/ic_action_upload"
            />

        <TextView
            android:id="@+id/backup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/imageView_backup"
            android:paddingLeft="@dimen/spacing_tiny"
            android:text="@string/drawer.item.backup"
            android:textSize="@dimen/font_large"
            />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/drawer_item_about"
        android:layout_width="match_parent"
        android:layout_height="@dimen/list_item_height_small"
        android:layout_below="@+id/drawer_item_backup"
        >

        <ImageView
            android:id="@+id/imageView_about"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/spacing_small"
            android:src="@drawable/ic_action_info"
            />

        <TextView
            android:id="@+id/about"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/imageView_about"
            android:paddingLeft="@dimen/spacing_tiny"
            android:text="@string/drawer.item.about"
            android:textSize="@dimen/font_large"
            />
    </RelativeLayout>
</RelativeLayout>


text:
import React from 'react'
import PropTypes from 'prop-types'
import { TouchableOpacity, Text } from 'react-native'
import styles from './rounded-button.styles'

export default class RoundedButton extends React.Component {
  static propTypes = {
    onPress: PropTypes.func,
    text: PropTypes.string,
    children: PropTypes.string,
    navigator: PropTypes.object,
    testID: PropTypes.string
  }

  getText () {
    const buttonText = this.props.text || this.props.children || ''
    return buttonText.toUpperCase()
  }

  render () {
    return (
      <TouchableOpacity testID={this.props.testID} style={styles.button} onPress={this.props.onPress}>
        <Text style={styles.buttonText}>{this.getText()}</Text>
      </TouchableOpacity>
    )
  }
}


text:
#ifndef _NUTI_BITMAPCANVAS_H_
#define _NUTI_BITMAPCANVAS_H_

#include "core/ScreenPos.h"
#include "core/ScreenBounds.h"
#include "graphics/Color.h"

#include <memory>
#include <vector>

namespace Nuti {
    class Bitmap;

    /**
     * A canvas class for constructing bitmaps procedurally.
     */
    class BitmapCanvas {
    public:
        enum DrawMode {
            FILL,
            STROKE
        };

        BitmapCanvas(int width, int height);
        virtual ~BitmapCanvas();

        void setDrawMode(DrawMode mode);
        void setColor(const Color& color);
        void setStrokeWidth(float width);
        void setFont(const std::string& name, float size);

        void pushClipRect(const ScreenBounds& clipRect);
        void popClipRect();

        void drawText(std::string text, const ScreenPos& pos, int maxWidth, bool breakLines);
        void drawPolygon(const std::vector<ScreenPos>& poses);
        void drawRoundRect(const ScreenBounds& rect, float radius);
        void drawBitmap(const ScreenBounds& rect, const std::shared_ptr<Bitmap>& bitmap);

        ScreenBounds measureTextSize(std::string text, int maxWidth, bool breakLines);

        std::shared_ptr<Bitmap> buildBitmap(bool pow2Padding) const;

    protected:
        struct State;

        std::unique_ptr<State> _state;
    };
}

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Lubala.Core.Cryptographic;
using Lubala.Core.Logs;
using Lubala.Core.Pushing.Crypography;
using Lubala.Core.Pushing.Services;
using Lubala.Core.Resolvers;

namespace Lubala.Core.Pushing
{
    internal class PushingHub : IPushingHub
    {
        private readonly HubContext _hubContext;

        static PushingHub()
        {
            TypeResolver.Resolver.Register<ISourceStreamReader, DefaultSourceStreamReader>();
            TypeResolver.Resolver.Register<IPushingEngine, PushingEngine>();
            TypeResolver.Resolver.Register<ITypeDetector, TypeDetector>();
            TypeResolver.Resolver.Register<IEncodingProvider, AesEncodingProvider>();
            TypeResolver.Resolver.Register<IAesCrypography, AesCrypography>();
        }

        internal PushingHub(HubContext hubContext)
        {
            if (hubContext == null)
            {
                throw new ArgumentNullException(nameof(hubContext));
            }

            _hubContext = hubContext;

            MessageTypes = _hubContext.GetMessageTypes();
            MessageHandlers = _hubContext.GetMessageHandlers();
            Resolver = _hubContext.Resolver;
            Channel = _hubContext.Channel;
        }

        internal IReadOnlyDictionary<TypeIdentity, Type> MessageTypes { get; }
        internal ITypeResolver Resolver { get; }

        public ILubalaChannel Channel { get; }
        public EncodingMode EncodingMode { get; set; } = EncodingMode.Plain;
        public IReadOnlyDictionary<Type, IMessageHandler> MessageHandlers { get; }

        public bool Verify(string timestamp, string nonce, string signature, string verifyToken)
        {
            Log.Logger.Debug("verifing server.");
            Log.Logger.Info("timestamp: {0}, nonce: {1}, signature: {2}, verifyToken: {3}",
                timestamp,
                nonce,
                signature,
                verifyToken);
            var tokenValue = verifyToken;
            var tempArray = new SortedSet<string> {timestamp, nonce, tokenValue};
            var toHash = string.Join("", tempArray);

            var hasher = Resolver.Resolve<ISha1Hasher>();
            var result = hasher.HashString(toHash, Encoding.ASCII);

            Log.Logger.Info("verified signature: {0}", result);
            Log.Logger.Debug("verifing server done.");

            return result == signature;
        }

        public async Task InterpretingAsync(Stream sourceStream, Stream targetStream,
            IDictionary<string, string> payloads)
        {
            var engine = Resolver.Resolve<IPushingEngine>();
            var result = await engine.ProducePassiveMessage(sourceStream, _hubContext, payloads);

            await result.SerializeTo(targetStream, _hubContext);
        }
    }
}


text:
namespace Browsio.UnitTest.Domain
{
    #region << Using >>

    using Browsio.Domain;
    using Incoding.CQRS;
    using Incoding.MSpecContrib;
    using Machine.Specifications;

    #endregion

    [Subject(typeof(ExistFacebookUserQuery))]
    public class When_exist_facebook_user_with_wrong_fb
    {
        #region Establish value

        static MockMessage<ExistFacebookUserQuery, IncStructureResponse<bool>> mockQuery;

        #endregion

        Establish establish = () =>
                                  {
                                      var query = Pleasure.Generator.Invent<ExistFacebookUserQuery>();

                                      mockQuery = MockQuery<ExistFacebookUserQuery, IncStructureResponse<bool>>
                                              .When(query)
                                              .StubEmptyQuery(whereSpecification: new UserByFBIdWhereSpec(query.FBId));
                                  };

        Because of = () => mockQuery.Original.Execute();

        It should_be_result = () => mockQuery.ShouldBeIsResult(new IncStructureResponse<bool>(false));
    }
}


text:
LEVEL = ../../../make

ENABLE_THREADS := YES
CXX_SOURCES := main.cpp

include $(LEVEL)/Makefile.rules


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import copy
import os
import unittest
from collections import defaultdict
from contextlib import contextmanager
from tempfile import mkdtemp
from textwrap import dedent

from pants.backend.core.targets.dependencies import Dependencies
from pants.base.address import SyntheticAddress
from pants.base.build_configuration import BuildConfiguration
from pants.base.build_file import FilesystemBuildFile
from pants.base.build_file_address_mapper import BuildFileAddressMapper
from pants.base.build_file_aliases import BuildFileAliases
from pants.base.build_file_parser import BuildFileParser
from pants.base.build_graph import BuildGraph
from pants.base.build_root import BuildRoot
from pants.base.cmd_line_spec_parser import CmdLineSpecParser
from pants.base.exceptions import TaskError
from pants.base.source_root import SourceRoot
from pants.base.target import Target
from pants.goal.goal import Goal
from pants.goal.products import MultipleRootedProducts, UnionProducts
from pants.option.global_options import GlobalOptionsRegistrar
from pants.option.options import Options
from pants.option.ranked_value import RankedValue
from pants.subsystem.subsystem import Subsystem
from pants.util.contextutil import pushd, temporary_dir
from pants.util.dirutil import safe_mkdir, safe_open, safe_rmtree, touch
from pants_test.base.context_utils import create_context
from pants_test.option.util.fakes import create_option_values, options_registration_function

# TODO: Rename to 'TestBase', for uniformity, and also for logic: This is a baseclass
# for tests, not a test of a thing called 'Base'.
class BaseTest(unittest.TestCase):
  """A baseclass useful for tests requiring a temporary buildroot."""

  def build_path(self, relpath):
    """Returns the canonical BUILD file path for the given relative build path."""
    if os.path.basename(relpath).startswith('BUILD'):
      return relpath
    else:
      return os.path.join(relpath, 'BUILD')

  def create_dir(self, relpath):
    """Creates a directory under the buildroot.

    relpath: The relative path to the directory from the build root.
    """
    path = os.path.join(self.build_root, relpath)
    safe_mkdir(path)
    return path

  def create_file(self, relpath, contents='', mode='wb'):
    """Writes to a file under the buildroot.

    relpath:  The relative path to the file from the build root.
    contents: A string containing the contents of the file - '' by default..
    mode:     The mode to write to the file in - over-write by default.
    """
    path = os.path.join(self.build_root, relpath)
    with safe_open(path, mode=mode) as fp:
      fp.write(contents)
    return path

  def add_to_build_file(self, relpath, target):
    """Adds the given target specification to the BUILD file at relpath.

    relpath: The relative path to the BUILD file from the build root.
    target:  A string containing the target definition as it would appear in a BUILD file.
    """
    self.create_file(self.build_path(relpath), target, mode='a')
    cls = self.address_mapper._build_file_type
    return cls(root_dir=self.build_root, relpath=self.build_path(relpath))

  def make_target(self,
                  spec='',
                  target_type=Target,
                  dependencies=None,
                  resources=None,
                  derived_from=None,
                  **kwargs):
    address = SyntheticAddress.parse(spec)
    target = target_type(name=address.target_name,
                         address=address,
                         build_graph=self.build_graph,
                         **kwargs)
    dependencies = dependencies or []
    dependencies.extend(resources or [])

    self.build_graph.inject_target(target,
                                   dependencies=[dep.address for dep in dependencies],
                                   derived_from=derived_from)
    return target

  @property
  def alias_groups(self):
    return BuildFileAliases.create(targets={'target': Dependencies})

  def setUp(self):
    super(BaseTest, self).setUp()
    Goal.clear()
    Subsystem.reset()

    self.real_build_root = BuildRoot().path

    self.build_root = os.path.realpath(mkdtemp(suffix='_BUILD_ROOT'))
    self.addCleanup(safe_rmtree, self.build_root)

    self.pants_workdir = os.path.join(self.build_root, '.pants.d')
    safe_mkdir(self.pants_workdir)

    self.options = defaultdict(dict)  # scope -> key-value mapping.
    self.options[''] = {
      'pants_workdir': self.pants_workdir,
      'pants_supportdir': os.path.join(self.build_root, 'build-support'),
      'pants_distdir': os.path.join(self.build_root, 'dist'),
      'pants_configdir': os.path.join(self.build_root, 'config'),
      'cache_key_gen_version': '0-test',
    }

    BuildRoot().path = self.build_root
    self.addCleanup(BuildRoot().reset)

    # We need a pants.ini, even if empty. get_buildroot() uses its presence.
    self.create_file('pants.ini')
    self._build_configuration = BuildConfiguration()
    self._build_configuration.register_aliases(self.alias_groups)
    self.build_file_parser = BuildFileParser(self._build_configuration, self.build_root)
    self.address_mapper = BuildFileAddressMapper(self.build_file_parser, FilesystemBuildFile)
    self.build_graph = BuildGraph(address_mapper=self.address_mapper)

  def reset_build_graph(self):
    """Start over with a fresh build graph with no targets in it."""
    self.address_mapper = BuildFileAddressMapper(self.build_file_parser, FilesystemBuildFile)
    self.build_graph = BuildGraph(address_mapper=self.address_mapper)

  def set_options_for_scope(self, scope, **kwargs):
    self.options[scope].update(kwargs)

  def context(self, for_task_types=None, options=None, target_roots=None,
              console_outstream=None, workspace=None):
    for_task_types = for_task_types or []
    options = options or {}

    option_values = defaultdict(dict)
    registered_subsystems = set()
    bootstrap_option_values = None  # We fill these in after registering bootstrap options.

    # We provide our own test-only registration implementation, bypassing argparse.
    # When testing we set option values directly, so we don't care about cmd-line flags, config,
    # env vars etc. In fact, for test isolation we explicitly don't want to look at those.
    # All this does is make the names available in code, with the default values.
    # Individual tests can then override the option values they care about.
    def register_func(on_scope):
      scoped_options = option_values[on_scope]
      register = options_registration_function(scoped_options)
      register.bootstrap = bootstrap_option_values
      register.scope = on_scope
      return register

    # TODO: This sequence is a bit repetitive of the real registration sequence.

    # Register bootstrap options and grab their default values for use in subsequent registration.
    GlobalOptionsRegistrar.register_bootstrap_options(register_func(Options.GLOBAL_SCOPE))
    bootstrap_option_values = create_option_values(copy.copy(option_values[Options.GLOBAL_SCOPE]))

    # Now register the full global scope options.
    GlobalOptionsRegistrar.register_options(register_func(Options.GLOBAL_SCOPE))

    # Now register task and subsystem options for relevant tasks.
    for task_type in for_task_types:
      scope = task_type.options_scope
      if scope is None:
        raise TaskError('You must set a scope on your task type before using it in tests.')
      task_type.register_options(register_func(scope))
      for subsystem in Subsystem.closure(set(task_type.global_subsystems()) |
                                         set(task_type.task_subsystems()) |
                                         self._build_configuration.subsystems()):
        if subsystem not in registered_subsystems:
          subsystem.register_options(register_func(subsystem.options_scope))
          registered_subsystems.add(subsystem)

    # Now default option values override with any caller-specified values.
    # TODO(benjy): Get rid of the options arg, and require tests to call set_options.

    for scope, opts in options.items():
      for key, val in opts.items():
        option_values[scope][key] = val

    for scope, opts in self.options.items():
      for key, val in opts.items():
        option_values[scope][key] = val

    # Make inner scopes inherit option values from their enclosing scopes.
    all_scopes = set(option_values.keys())
    for task_type in for_task_types:  # Make sure we know about pre-task subsystem scopes.
      all_scopes.update([si.scope for si in task_type.known_scope_infos()])
    # Iterating in sorted order guarantees that we see outer scopes before inner scopes,
    # and therefore only have to inherit from our immediately enclosing scope.
    for scope in sorted(all_scopes):
      if scope != Options.GLOBAL_SCOPE:
        enclosing_scope = scope.rpartition('.')[0]
        opts = option_values[scope]
        for key, val in option_values.get(enclosing_scope, {}).items():
          if key not in opts:  # Inner scope values override the inherited ones.
            opts[key] = val

    context = create_context(options=option_values,
                             target_roots=target_roots,
                             build_graph=self.build_graph,
                             build_file_parser=self.build_file_parser,
                             address_mapper=self.address_mapper,
                             console_outstream=console_outstream,
                             workspace=workspace)
    Subsystem._options = context.options
    return context

  def tearDown(self):
    SourceRoot.reset()
    FilesystemBuildFile.clear_cache()

  def target(self, spec):
    """Resolves the given target address to a Target object.

    address: The BUILD target address to resolve.

    Returns the corresponding Target or else None if the address does not point to a defined Target.
    """
    address = SyntheticAddress.parse(spec)
    self.build_graph.inject_address_closure(address)
    return self.build_graph.get_target(address)

  def targets(self, spec):
    """Resolves a target spec to one or more Target objects.

    spec: Either BUILD target address or else a target glob using the siblings ':' or
          descendants '::' suffixes.

    Returns the set of all Targets found.
    """

    spec_parser = CmdLineSpecParser(self.build_root, self.address_mapper)
    addresses = list(spec_parser.parse_addresses(spec))
    for address in addresses:
      self.build_graph.inject_address_closure(address)
    targets = [self.build_graph.get_target(address) for address in addresses]
    return targets

  def create_files(self, path, files):
    """Writes to a file under the buildroot with contents same as file name.

     path:  The relative path to the file from the build root.
     files: List of file names.
    """
    for f in files:
      self.create_file(os.path.join(path, f), contents=f)

  def create_library(self, path, target_type, name, sources=None, **kwargs):
    """Creates a library target of given type at the BUILD file at path with sources

     path: The relative path to the BUILD file from the build root.
     target_type: valid pants target type.
     name: Name of the library target.
     sources: List of source file at the path relative to path.
     **kwargs: Optional attributes that can be set for any library target.
       Currently it includes support for resources, java_sources, provides
       and dependencies.
    """
    if sources:
      self.create_files(path, sources)
    self.add_to_build_file(path, dedent('''
          %(target_type)s(name='%(name)s',
            %(sources)s
            %(resources)s
            %(java_sources)s
            %(provides)s
            %(dependencies)s
          )
        ''' % dict(target_type=target_type,
                   name=name,
                   sources=('sources=%s,' % repr(sources)
                              if sources else ''),
                   resources=('resources=["%s"],' % kwargs.get('resources')
                              if 'resources' in kwargs else ''),
                   java_sources=('java_sources=[%s],'
                                 % ','.join(map(lambda str_target: '"%s"' % str_target,
                                                kwargs.get('java_sources')))
                                 if 'java_sources' in kwargs else ''),
                   provides=('provides=%s,' % kwargs.get('provides')
                              if 'provides' in kwargs else ''),
                   dependencies=('dependencies=%s,' % kwargs.get('dependencies')
                              if 'dependencies' in kwargs else ''),
                   )))
    return self.target('%s:%s' % (path, name))

  def create_resources(self, path, name, *sources):
    return self.create_library(path, 'resources', name, sources)

  @contextmanager
  def workspace(self, *buildfiles):
    with temporary_dir() as root_dir:
      with BuildRoot().temporary(root_dir):
        with pushd(root_dir):
          for buildfile in buildfiles:
            touch(os.path.join(root_dir, buildfile))
          yield os.path.realpath(root_dir)

  def populate_compile_classpath(self, context, classpath=None):
    """
    Helps actual test cases to populate the 'compile_classpath' products data mapping
    in the context, which holds the classpath value for targets.

    :param context: The execution context where the products data mapping lives.
    :param classpath: a list of classpath strings. If not specified, [os.path.join(self.buildroot, 'none')] will be used.
    """
    classpath = classpath or [os.path.join(self.build_root, 'none')]
    compile_classpaths = context.products.get_data('compile_classpath', lambda: UnionProducts())
    compile_classpaths.add_for_targets(context.targets(), [('default', entry) for entry in classpath])

  @contextmanager
  def add_data(self, context_products, data_type, target, *products):
    make_products = lambda: defaultdict(MultipleRootedProducts)
    data_by_target = context_products.get_data(data_type, make_products)
    with temporary_dir() as outdir:
      def create_product(product):
        abspath = os.path.join(outdir, product)
        with safe_open(abspath, mode='w') as fp:
          fp.write(product)
        return abspath
      data_by_target[target].add_abs_paths(outdir, map(create_product, products))
      yield temporary_dir

  @contextmanager
  def add_products(self, context_products, product_type, target, *products):
    product_mapping = context_products.get(product_type)
    with temporary_dir() as outdir:
      def create_product(product):
        with safe_open(os.path.join(outdir, product), mode='w') as fp:
          fp.write(product)
        return product
      product_mapping.add(target, outdir, map(create_product, products))
      yield temporary_dir


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Not Found | WonderFox | http://www.videoconverterfactory.com</title>
<meta name="keywords" content="wonderfox soft 404 page">
<meta name="description" content="The page you are trying to view is moved or not exist, sorry about that. You may be interested in:">
<link rel="shortcut icon" href="images/favicon.ico"/>
<link rel="Bookmark" href="images/favicon.ico"/>
<link href="css/newstyle.css" rel="stylesheet" type="text/css" />
<link href="css2/404.css" rel="stylesheet" type="text/css" />
<link href="css2/bg.css" rel="stylesheet" type="text/css" />
<link href="css2/h-index.css" rel="stylesheet" type="text/css" />

Store

Download

Support

Resource

Company

Promotion

						DVD Software

DVD Video Converter

DVD Ripper

DVD to Apple Device Ripper

DVD to iPad Ripper

DVD to Cell Phone Ripper

Free DVD Ripper (Speedy)

						Video Software

HD Video Converter

Video Converter

Apple Video Converter

BlackBerry Video Converter

Nokia Video Converter

Video to Picture Converter

						Watermark Software

Video Watermark

Photo Watermark

						GIF Software

Video to GIF Converter

SWF to GIF Converter

						Office Software

Document Manager

		Home > 404 Error

The page you are trying to view is moved or not exist, sorry about that. You may be interested in:

DVD Ripper Pro

Rip DVD to AVI, MP4, MPG, WMV, iPad, iPhone, Android with 0-Quality-Loss.(Rip a DVD in 5~10 Minutes)

HD Video Converter

Convert video to 150+ video formats with 30x conversion speed. It also support 4K video, H264(Hevc)...

DVD Video Converter

DVD Backup, Video and DVD Converter, Video Downloader, Video Editor/Player

Back to Homepage >>

If you have any question please feel free to contact us >>

			About | Contact | Affiliate | Privacy | Sitemap

Useful Link

Order support

Product Support

Retrieve Registration Code

FAQ

Submit Ticket

News

Refund Policy

License Policy

Subscribe Newsletter

Resource Directory

Rip DVD & Rip Encrypted DVD

Convert HD Video & Common Video

Convert Video to Apple Devices

Convert Video to Nokia

Convert Video to Blackberry

Convert YouTube & FLV

Hot Topic

Glossary

Tips Center

Free Video Converter

Free HD Video Converter

Free Video Converter

Free MP4 Video Converter

Free AVI Video Converter

Free Apple Video Converter

Free iPhone Video Converter

Free Blackberry Video Converter

Free Nokia Video Converter

Free PSP Video Converter

Free Flash Video Converter

Cheap Video Converter

MP4 Video Converter

AVI Video Converter

MPEG Video Converter

iPod Video Converter

iPad Video Converter

iPhone Video Converter

Flash Video Converter

3GP Video Converter

FLV Video Converter

SWF Video Converter

CopyRight @ 2009-2017 WonderFox Soft, Inc. All Rights Reserved.


text:
    public function executeIndex( sfWebRequest $request )
    {

        if ( $request->getParameter( 'sort' ) && $this->isValidSortRule( $request->getParameter( 'sort' ) ) )
        {
            $this->setSort( array( $request->getParameter( 'sort' ), $request->getParameter( 'sort_type' ) ) );
        }

        if ( $request->getParameter( 'page' ) )
        {
            $this->setPage( $request->getParameter( 'page' ) );
        }

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();
        $this->hasFilters = $this->getFilters();

    } // <?php echo $this->getGeneratedModuleName() ?>Actions::executeIndex()


text:
FROM crystallang/crystal:0.35.1

# Install Dependencies
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update -qq && apt-get install -y --no-install-recommends libpq-dev libsqlite3-dev libmysqlclient-dev libreadline-dev git curl vim netcat

# Install Node
RUN curl -sL https://deb.nodesource.com/setup_14.x | bash -
RUN apt-get install -y nodejs

WORKDIR /opt/amber

# Build Amber
ENV PATH /opt/amber/bin:$PATH
COPY . /opt/amber
RUN shards build amber

CMD ["crystal", "spec"]