text:
package org.cohorte.remote.shell;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

/**
 * The shell server: accepts clients and starts shell session threads
 *
 * @author Thomas Calmant
 */
public class Server implements Runnable {

    /** The client acceptance thread */
    private Thread pListeningThread;

    /** The server socket */
    private ServerSocket pServer;

    /** The parent shell service */
    private final RemoteShellService pShellService;

    /** The stop flag */
    private boolean pStop;

    /**
     * Sets up the server members
     *
     * @param aShellService
     *            The parent shell service
     */
    public Server(final RemoteShellService aShellService) {

        pShellService = aShellService;
    }

    /**
     * Closes the server socket
     *
     * @throws IOException
     *             Error closing the socket
     */
    public void close() throws IOException {

        // Set up the stop flag
        pStop = true;

        if (pServer != null) {
            try {
                pServer.close();

            } finally {
                pServer = null;
            }
        }

        // Wait for the listening thread
        try {
            pListeningThread.join();

        } catch (final InterruptedException ex) {
            // Ignore
        }

        pListeningThread = null;
    }

    /**
     * Returns the address the server socket is bound to (generally "::" or
     * "0.0.0.0"). Returns null if the server is down.
     *
     * @return The server binding address or null.
     */
    public String getAddress() {

        if (pServer == null) {
            return null;
        }

        final InetAddress boundAddress = pServer.getInetAddress();
        if (boundAddress == null) {
            return null;
        }

        return boundAddress.toString();
    }

    /**
     * Returns the port the server is listening to. Returns -1 if the server is
     * down.
     *
     * @return The listening port or -1
     */
    public int getPort() {

        if (pServer == null) {
            return -1;
        }

        return pServer.getLocalPort();
    }

    /**
     * Open the server, listening the given address and port
     *
     * @param aAddress
     *            A binding address (can be null)
     * @param aPort
     *            A listening port (can be 0)
     * @throws IOException
     *             Error opening the server servlet
     */
    public void open(final String aAddress, final int aPort) throws IOException {

        if (pServer != null) {
            // Refuse to re-open a connection
            throw new IOException("Server is already running");
        }

        // Compute the binding address
        final InetAddress bindAddr;
        if (aAddress == null) {
            // Accept all connections
            bindAddr = null;

        } else {
            // Bind to a specific address
            bindAddr = InetAddress.getByName(aAddress);
        }

        // Reset the stop flag
        pStop = false;

        // Create the server
        pServer = new ServerSocket(aPort, 1, bindAddr);

        // Wait for clients in another thread
        pListeningThread = new Thread(this, "cohorte.remote.shell.acceptor");
        pListeningThread.start();
    }

    /**
     * The server client acceptance loop
     *
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {

        try {
            while (!pStop) {
                try {
                    final Socket client = pServer.accept();

                    // Start a new client thread
                    final Thread clientThread = new Thread(
                            new ShellClientHandler(pShellService, client));
                    clientThread.setName("cohorte.remote.shell="
                            + client.getRemoteSocketAddress());
                    clientThread.start();

                } catch (final SocketException ex) {
                    // Log the exception
                    pShellService.error("acceptLoop",
                            "Error accepting client:", ex);

                } catch (final SocketTimeoutException ex) {
                    // Ignore
                }
            }

        } catch (final IOException ex) {
            // Log the exception
            pStop = true;
            pShellService.error("acceptLoop", "Error waiting for clients:", ex);

            try {
                // Kill the server
                close();

            } catch (final IOException ex2) {
                // Ignore
            }
        }
    }

    /**
     * Sets the socket timeout. Does nothing if the server has not been opened
     *
     * @param aTimeout
     *            The timeout to set
     * @throws SocketException
     *             Error setting up the timeout
     */
    public void setSocketTimeout(final int aTimeout) throws SocketException {

        if (pServer != null) {
            pServer.setSoTimeout(aTimeout);
        }
    }
}


text:
require "west_framework/version"
require "west_framework/hello"

module WestFramework
  # Your code goes here...
end

redpajama_set_name: RedPajamaGithub


text:
#include "ManyClientsOneServerNonBlockingTest.h"

/*
What is being done here is having 256 clients connect to one server, disconnect, connect again.

Do this for about 10 seconds. Then allow them all to connect for one last time.

This one has a nonblocking recieve so doesn't wait for connects or anything.
Just rapid connecting disconnecting.

Good ideas for changes:
After the last check run a eightpeers like test an add the conditions
of that test as well.

Make sure that if we initiate the connection we get a proper message
and if not we get a proper message. Add proper conditions.

Randomize sending the disconnect notes

Success conditions:
All connected normally.

Failure conditions:
Doesn't reconnect normally.

During the very first connect loop any connect returns false.

Connect function returns false and peer is not connected to anything.

*/
int ManyClientsOneServerNonBlockingTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	const int clientNum= 256;

	RakPeerInterface *clientList[clientNum];//A list of clients
	RakPeerInterface *server;//The server
	SystemAddress currentSystem;

	//SystemAddress currentSystem;

	Packet *packet;
	destroyList.Clear(false,_FILE_AND_LINE_);

	//Initializations of the arrays
	for (int i=0;i<clientNum;i++)
	{
		clientList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(clientList[i],_FILE_AND_LINE_);

		clientList[i]->Startup(1,&SocketDescriptor(), 1);

	}

	server=RakPeerInterface::GetInstance();
	destroyList.Push(server,_FILE_AND_LINE_);
	server->Startup(clientNum, &SocketDescriptor(60000,0), 1);
	server->SetMaximumIncomingConnections(clientNum);

	//Connect all the clients to the server

	for (int i=0;i<clientNum;i++)
	{

		if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
		{

			if (isVerbose)
				DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);

			return 1;//This fails the test, don't bother going on.

		}

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	DataStructures::List< SystemAddress  > systemList;
	DataStructures::List< RakNetGUID > guidList;

	if (isVerbose)
		printf("Entering disconnect loop \n");

	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		//Disconnect all clients IF connected to any from client side
		for (int i=0;i<clientNum;i++)
		{

			clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
			int len=systemList.Size();

			for (int j=0;j<len;j++)//Disconnect them all
			{

				clientList[i]->CloseConnection (systemList[j],true,0,LOW_PRIORITY);
			}

		}

		//RakSleep(100);

		//Connect

		for (int i=0;i<clientNum;i++)
		{

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000;
			if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
			{

				if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
				{

					if (isVerbose)
						DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

					return 1;//This fails the test, don't bother going on.

				}
			}

		}

		//Server receive

		packet=server->Receive();

		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all peers
		{

			packet=clientList[i]->Receive();

			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	entryTime=GetTimeMS();

	while(GetTimeMS()-entryTime<2000)//Run for 2 Secoonds to process incoming disconnects
	{

		//Server receive

		packet=server->Receive();

		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all peers
		{

			packet=clientList[i]->Receive();
			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	//Connect

	for (int i=0;i<clientNum;i++)
	{

		currentSystem.SetBinaryAddress("127.0.0.1");
		currentSystem.port=60000;

		if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
		{

			if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{

				clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
				int len=systemList.Size();

				if (isVerbose)
					DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

				return 1;//This fails the test, don't bother going on.

			}
		}

	}

	entryTime=GetTimeMS();

	while(GetTimeMS()-entryTime<5000)//Run for 5 Secoonds
	{

		//Server receive

		packet=server->Receive();
		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all clients
		{

			packet=clientList[i]->Receive();
			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	for (int i=0;i<clientNum;i++)
	{

		clientList[i]->GetSystemList(systemList,guidList);
		int connNum=guidList.Size();//Get the number of connections for the current peer
		if (connNum!=1)//Did we connect to all?
		{

			if (isVerbose)
				printf("Not all clients reconnected normally.\nFailed on clients number %i\n",i);

			if (isVerbose)
				DebugTools::ShowError("",!noPauses && isVerbose,__LINE__,__FILE__);

			return 2;

		}

	}

	if (isVerbose)
		printf("Pass\n");
	return 0;

}

RakString ManyClientsOneServerNonBlockingTest::GetTestName()
{

	return "ManyClientsOneServerNonBlockingTest";

}

RakString ManyClientsOneServerNonBlockingTest::ErrorCodeToString(int errorCode)
{

	switch (errorCode)
	{

	case 0:
		return "No error";
		break;

	case 1:
		return "The connect function failed.";
		break;

	case 2:
		return "Peers did not connect normally.";
		break;

	default:
		return "Undefined Error";
	}

}

ManyClientsOneServerNonBlockingTest::ManyClientsOneServerNonBlockingTest(void)
{
}

ManyClientsOneServerNonBlockingTest::~ManyClientsOneServerNonBlockingTest(void)
{
}

void ManyClientsOneServerNonBlockingTest::DestroyPeers()
{

	int theSize=destroyList.Size();

	for (int i=0; i < theSize; i++)
		RakPeerInterface::DestroyInstance(destroyList[i]);

}


text:
package dao

import java.util.UUID

import model.UserSession
import scalikejdbc._

import scala.util.Try

class SessionDao {

  def insertSession(userSession: UserSession): Try[UUID] = Try {
    NamedDB('auth).localTx { implicit session =>
      sql"""insert into sessions values(${userSession.sessionId},
        ${userSession.token}, ${userSession.userId},
        ${userSession.created}, ${userSession.updated},
        ${userSession.ttl})""".update().apply()
      userSession.sessionId
    }
  }

  def findSession(token: String): Try[Option[UserSession]] = Try {
    NamedDB('auth).readOnly { implicit session =>
      sql"select * from sessions where token = $token".
        map(UserSession.fromDb).headOption().apply()
    }
  }

  def deleteSession(token: String): Try[Unit] = Try {
    NamedDB('auth).localTx { implicit session =>
      sql"delete from sessions where token = $token".update().apply()
    }
  }
}


text:
import os
from unittest import TestCase

from .exc import NoDefaultError
from .types import LocalSetting, SecretSetting
from .util import NO_DEFAULT, get_file_name

class TestUtil(TestCase):

    def test_NO_DEFAULT_is_False(self):
        self.assertFalse(NO_DEFAULT)

    def test_default_file_name(self):
        os.environ.pop('LOCAL_SETTINGS_FILE', None)
        file_name = get_file_name()
        self.assertEqual(os.path.basename(file_name), 'local.cfg')

    def test_set_file_name_via_environ(self):
        os.environ['LOCAL_SETTINGS_FILE'] = 'pants.cfg'
        file_name = get_file_name()
        self.assertEqual(file_name, 'pants.cfg')

class TestLocalSetting(TestCase):

    def test_create_local_setting(self):
        setting = LocalSetting()
        self.assertRaises(NoDefaultError, lambda: setting.default)
        self.assertFalse(setting.has_default)
        self.assertFalse(setting.has_value)

    def test_create_local_setting_with_default(self):
        setting = LocalSetting(default={})
        self.assertTrue(setting.has_default)
        self.assertEqual(setting.default, {})
        self.assertTrue(setting.has_value)
        self.assertEqual(setting.value, {})

    def test_set_value_of_local_setting_with_default(self):
        setting = LocalSetting(default={})
        setting.value = 'X'
        self.assertEqual(setting.default, {})
        self.assertEqual(setting.value, 'X')

    def test_local_setting_default_must_be_json_serializable(self):
        self.assertRaises(TypeError, LocalSetting, default=object())

    def test_local_setting_can_has_local_setting_as_default(self):
        default_setting = LocalSetting(default=1)
        setting = LocalSetting(default=default_setting)
        self.assertTrue(setting.has_default)
        self.assertEqual(setting.default, 1)
        self.assertEqual(setting.value, 1)
        setting.value = 2
        self.assertEqual(default_setting.value, 1)
        self.assertEqual(setting.value, 2)

    def test_local_setting_with_validator(self):
        setting = LocalSetting(validator=lambda v: isinstance(v, int))
        with self.assertRaises(ValueError):
            setting.value = 'abc'
        setting.value = 123

    def test_local_setting_with_callable_default(self):
        setting = LocalSetting(default=lambda: 'pants')
        self.assertEqual(setting.default, 'pants')

class TestSecretSetting(TestCase):

    def test_create_secret_setting(self):
        setting = SecretSetting()
        self.assertFalse(setting.has_default)
        self.assertFalse(setting.has_value)

    def test_secret_setting_cannot_have_a_default(self):
        self.assertRaises(TypeError, SecretSetting, default='pants')


text:
package org.joinfaces.autoconfigure.viewscope;

import java.util.concurrent.atomic.AtomicInteger;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PreDestroyViewMapEvent;

import org.joinfaces.test.mock.JsfIT;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.ObjectFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.doCallRealMethod;
import static org.mockito.BDDMockito.mock;
import static org.mockito.BDDMockito.when;

public class ViewScopeTest extends JsfIT {

	private static final String KEY = "key";

	private ViewScope viewScope;

	@BeforeEach
	public void setUp() {
		this.viewScope = new ViewScope();
	}

	@Test
	public void testGet() {

		AtomicInteger count = new AtomicInteger(0);
		ObjectFactory<?> objectFactory = (ObjectFactory<Object>) () -> {
			count.incrementAndGet();
			return new Object();
		};

		Object bean = this.viewScope.get(KEY, objectFactory);
		assertThat(count).hasValue(1);

		bean = this.viewScope.get(KEY, objectFactory);
		assertThat(count).hasValue(1);

		assertThat(this.viewScope.remove(KEY)).isEqualTo(bean);
	}

	@Test
	public void testConversationId() {
		assertThat(this.viewScope.getConversationId()).isNull();
	}

	@Test
	public void testResolveContextualObject() {
		assertThat(this.viewScope.resolveContextualObject(KEY)).isNull();
	}

	@Test
	public void testRegisterDestructionCallback() {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		doCallRealMethod().when(viewRoot).subscribeToViewEvent(any(), any());
		doCallRealMethod().when(viewRoot).unsubscribeFromViewEvent(any(), any());
		when(viewRoot.getViewListenersForEventClass(any())).thenCallRealMethod();

		this.viewScope.registerDestructionCallback(KEY, () -> {
		});

		this.viewScope.remove(KEY);
	}

	@Test
	public void processEvent() {
		PreDestroyViewMapEvent event = mock(PreDestroyViewMapEvent.class);
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		when(event.getSource()).thenReturn(viewRoot);
		this.viewScope.getPreDestroyViewMapListener().processEvent(event);
	}

	@Test
	public void isListenerForSource() {
		assertThat(this.viewScope.getPreDestroyViewMapListener().isListenerForSource(mock(UIViewRoot.class))).isTrue();
		assertThat(this.viewScope.getPreDestroyViewMapListener().isListenerForSource(new Object())).isFalse();
	}
}


text:
'use strict';

/* globals webauthnJSON */

define('forum/account/2factor', ['translator', 'benchpress', 'api', 'alerts'], function (translator, bch, api, alerts) {
	var Settings = {};

	Settings.init = function () {
		if (ajaxify.data.showSetup) {
			$('button[data-action="regenerateTOTP"]').on('click', Settings.setupTotp);
			$('button[data-action="regenerateU2F"]').on('click', Settings.setupAuthn);
		} else {
			$('button[data-action="disassociate"]').on('click', Settings.disassociate);
			$('button[data-action="generateBackupCodes"]').on('click', Settings.generateBackupCodes);
		}
	};

	Settings.setupTotp = function () {
		socket.emit('plugins.2factor.regenerate', function (err, data) {
			if (err) {
				return app.alertError(err);
			}

			bch.parse('partials/2factor/generate', data, function (html) {
				translator.translate(html, function (translatedHTML) {
					translator.translate('[[2factor:generate.title]]', function (title) {
						var modal = bootbox.dialog({
							title: title,
							message: translatedHTML,
						});
						var formEl = modal.find('form');
						var confirmEl = modal.find('button[data-action="confirm"]');
						var codeEl = modal.find('.2fa-confirm');

						confirmEl.on('click', function () {
							Settings.verifyTotp(data.key, codeEl.val(), modal);
						});

						formEl.on('submit', function (e) {
							e.preventDefault();
							Settings.verifyTotp(data.key, codeEl.val(), modal);
						});

						modal.on('shown.bs.modal', function () {
							codeEl.focus();
						});
					});
				});
			});
		});
	};

	Settings.setupAuthn = function () {
		this.classList.add('disabled');
		const modal = bootbox.dialog({
			message: '[[2factor:u2f.modal.content]]',
			closeButton: false,
			className: 'text-center',
		});
		api.get('/plugins/2factor/u2f/register', {}).then(async (request) => {
			try {
				const response = await webauthnJSON.create({
					publicKey: request,
				});
				modal.modal('hide');

				api.post('/plugins/2factor/u2f/register', response).then(() => {
					ajaxify.refresh();
					alerts.success('[[2factor:u2f.success]]');
				}).catch(alerts.error);
			} catch (e) {
				modal.modal('hide');
				this.classList.remove('disabled');
				alerts.alert({
					message: '[[2factor:u2f.error]]',
					timeout: 2500,
				});
			}
		});
	};

	Settings.verifyTotp = function (key, token, modal) {
		socket.emit('plugins.2factor.confirm', {
			key: key,
			token: token,
		}, function (err) {
			if (!err) {
				modal.modal('hide');
				ajaxify.refresh();
				translator.translate('[[2factor:generate.success]]', function (successText) {
					app.alertSuccess(successText);
				});
			} else {
				// Probably a bad validation code
				var inputEl = modal.find('.2fa-confirm');
				inputEl.parent().addClass('has-error');
			}
		});
	};

	Settings.disassociate = function () {
		translator.translate('[[2factor:disable.confirm]]', function (disableText) {
			bootbox.confirm(disableText, function (confirm) {
				if (confirm) {
					socket.emit('plugins.2factor.disassociate', function (err) {
						if (err) {
							return app.alertError(err.message);
						}

						ajaxify.refresh();
					});
				}
			});
		});
	};

	Settings.generateBackupCodes = function () {
		$.ajax(config.relative_path + '/login/2fa/backup', {
			method: 'put',
			headers: {
				'x-csrf-token': config.csrf_token,
			},
		}).done(function (data) {
			bch.parse('partials/2factor/generateBackupCodes', data, function (html) {
				translator.translate(html, function (translatedHTML) {
					translator.translate('[[2factor:backup.generate.title]]', function (title) {
						bootbox.dialog({
							title: title,
							message: translatedHTML,
							onEscape: true,
						});
					});
				});
			});
		});
	};

	return Settings;
});


text:
using System.Threading.Tasks;

using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Tests.Actions.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Deployment.Tests.Actions.Twitter
{
    [TestClass]
    public class TwitterTests
    {
        [TestMethod]
        public async Task ValidateCognitiveKey()
        {
            var ds = new DataStore();

            ds.AddToDataStore("CognitiveServiceKey", "d06016d1b742488eb7ff03edeb5020aa");

            Assert.IsTrue(await TestManager.IsSuccessAsync("Microsoft-ValidateCognitiveKey", ds));
        }

        [TestMethod]
        public async Task ValidateTwitterAccount()
        {
            var ds = new DataStore();

            ds.AddToDataStore("Accounts", "@mohaali45");

            Assert.IsTrue(await TestManager.IsSuccessAsync("Microsoft-ValidateTwitterAccount", ds));
        }
    }
}


text:
__author__ = 'Sergei F. Kliver'
import argparse

from MACE.Parsers.VCF import CollectionVCF

parser = argparse.ArgumentParser()

parser.add_argument("-i", "--input_file", action="store", dest="input", required=True,
                    help="Input vcf file with mutations.")
parser.add_argument("-o", "--output_file", action="store", dest="output", required=True,
                    help="Output file with SNPeff info")
parser.add_argument("-e", "--snpeff_entry", action="store", dest="snpeff_entry", default="ANN",
                    help="SNPeff entry in vcf file. Allowed: ANN, EFF(used by old SNPeff versions). Default: ANN")

args = parser.parse_args()

mutations = CollectionVCF(in_file=args.input, from_file=True)
mutations.extract_snpeff_info(args.output, snpeff_entry=args.snpeff_entry)


text:
<title>Registers - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Data.html#Data" title="Data">
<link rel="prev" href="Convenience-Funs.html#Convenience-Funs" title="Convenience Funs">
<link rel="next" href="Floating-Point-Hardware.html#Floating-Point-Hardware" title="Floating Point Hardware">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Floating Point Hardware,
Previous: Convenience Funs,
Up: Data

10.13 Registers

You can refer to machine register contents, in expressions, as variables
with names starting with `<samp>$</samp>'.  The names of registers are different
for each machine; use info registers to see the names used on
your machine.

info registers
Print the names and values of all registers except floating-point
and vector registers (in the selected stack frame).

info all-registers
Print the names and values of all registers, including floating-point
and vector registers (in the selected stack frame).

info registers <var>regname</var> ...
Print the <dfn>relativized</dfn> value of each specified register <var>regname</var>.
As discussed in detail below, register values are normally relative to
the selected stack frame.  The <var>regname</var> may be any register name valid on
the machine you are using, with or without the initial `<samp>$</samp>'.

gdb has four “standard” register names that are available (in
expressions) on most machines—whenever they do not conflict with an
architecture's canonical mnemonics for registers.  The register names
$pc and $sp are used for the program counter register and
the stack pointer.  $fp is used for a register that contains a
pointer to the current stack frame, and $ps is used for a
register that contains the processor status.  For example,
you could print the program counter in hex with

     p/x $pc

or print the instruction to be executed next with

     x/i $pc

or add four to the stack pointer1 with

     set $sp += 4

Whenever possible, these four standard register names are available on
your machine even though the machine has different canonical mnemonics,
so long as there is no conflict.  The info registers command
shows the canonical names.  For example, on the SPARC, info
registers displays the processor status register as $psr but you
can also refer to it as $ps; and on x86-based machines $ps
is an alias for the eflags register.

gdb always considers the contents of an ordinary register as an
integer when the register is examined in this way.  Some machines have
special registers which can hold nothing but floating point; these
registers are considered to have floating point values.  There is no way
to refer to the contents of an ordinary register as floating point value
(although you can print it as a floating point value with
`<samp>print/f $<var>regname</var></samp>').

Some registers have distinct “raw” and “virtual” data formats.  This
means that the data format in which the register contents are saved by
the operating system is not the same one that your program normally
sees.  For example, the registers of the 68881 floating point
coprocessor are always saved in “extended” (raw) format, but all C
programs expect to work with “double” (virtual) format.  In such
cases, gdb normally works with the virtual format only (the format
that makes sense for your program), but the info registers command
prints the data in both formats.

Some machines have special registers whose contents can be interpreted
in several different ways.  For example, modern x86-based machines
have SSE and MMX registers that can hold several values packed
together in several different formats.  gdb refers to such
registers in struct notation:

     (gdb) print $xmm1
     $1 = {
       v4_float = {0, 3.43859137e-038, 1.54142831e-044, 1.821688e-044},
       v2_double = {9.92129282474342e-303, 2.7585945287983262e-313},
       v16_int8 = "\000\000\000\000\3706;\001\v\000\000\000\r\000\000",
       v8_int16 = {0, 0, 14072, 315, 11, 0, 13, 0},
       v4_int32 = {0, 20657912, 11, 13},
       v2_int64 = {88725056443645952, 55834574859},
       uint128 = 0x0000000d0000000b013b36f800000000
     }

To set values of such registers, you need to tell gdb which
view of the register you wish to change, as if you were assigning
value to a struct member:

      (gdb) set $xmm1.uint128 = 0x000000000000000000000000FFFFFFFF

Normally, register values are relative to the selected stack frame
(see Selecting a Frame).  This means that you get the
value that the register would contain if all stack frames farther in
were exited and their saved registers restored.  In order to see the
true contents of hardware registers, you must select the innermost
frame (with `<samp>frame 0</samp>').

Usually ABIs reserve some registers as not needed to be saved by the
callee (a.k.a.: “caller-saved”, “call-clobbered” or “volatile”
registers).  It may therefore not be possible for gdb to know
the value a register had before the call (in other words, in the outer
frame), if the register value has since been changed by the callee.
gdb tries to deduce where the inner frame saved
(“callee-saved”) registers, from the debug info, unwind info, or the
machine code generated by your compiler.  If some register is not
saved, and gdb knows the register is “caller-saved” (via
its own knowledge of the ABI, or because the debug/unwind info
explicitly says the register's value is undefined), gdb
displays `<samp><not saved></samp>' as the register's value.  With targets
that gdb has no knowledge of the register saving convention,
if a register was not saved by the callee, then its value and location
in the outer frame are assumed to be the same of the inner frame.
This is usually harmless, because if the register is call-clobbered,
the caller either does not care what is in the register after the
call, or has code to restore the value that it does care about.  Note,
however, that if you change such a register in the outer frame, you
may also be affecting the inner frame.  Also, the more “outer” the
frame is you're looking at, the more likely a call-clobbered
register's value is to be wrong, in the sense that it doesn't actually
represent the value the register had just before the call.

Footnotes

[1] This is a way of removing
one word from the stack, on machines where stacks grow downward in
memory (most machines, nowadays).  This assumes that the innermost
stack frame is selected; setting $sp is not allowed when other
stack frames are selected.  To pop entire frames off the stack,
regardless of machine architecture, use return;
see Returning from a Function.


text:
<?php
namespace Everyman\Neo4j\Command;

use Everyman\Neo4j\Command,
	Everyman\Neo4j\Client,
	Everyman\Neo4j\Exception,
	Everyman\Neo4j\PropertyContainer,
	Everyman\Neo4j\SpatialLayer;

/**
 * Add an entity to an a spatial layer
 */
class AddToLayer extends Command
{
	protected $layer    = null;
	protected $entity   = null;
	protected $key      = null;
	protected $value    = null;

	/**
	 * Set the layer to drive the command
	 *
	 * @param Client $client
	 * @param SpatialLayer $layer
	 * @param PropertyContainer $entity
	 * @param string $key
	 * @param string $value
	 */
	public function __construct(Client $client, SpatialLayer $layer, PropertyContainer $entity)
	{
		parent::__construct($client);
		$this->layer = $layer;
		$this->entity = $entity;
	}

	/**
	 * Return the data to pass
	 *
	 * @return mixed
	 */
	protected function getData()
	{
		if (!$this->entity || !$this->entity->hasId()) {
			throw new Exception('No entity to add to layer specified');
		}

		return array(
            'node'  => $this->getTransport()->getEndpoint().'/'. 'node' .'/'.$this->entity->getId(),
            'layer' => $this->layer->getName()
        );
	}

	/**
	 * Return the transport method to call
	 *
	 * @return string
	 */
	protected function getMethod()
	{
		return 'post';
	}

	/**
	 * Return the path to use
	 *
	 * @return string
	 */
	protected function getPath()
	{
		return '/ext/SpatialPlugin/graphdb/addNodeToLayer';
	}

	/**
	 * Use the results
	 *
	 * @param integer $code
	 * @param array   $headers
	 * @param array   $data
	 * @return integer on failure
	 */
	protected function handleResult($code, $headers, $data)
	{
		if ((int)($code / 100) != 2) {
			$this->throwException('Unable to add entity to spatial layer', $code, $headers, $data);
		}
		return true;
	}
}


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

public class ContinueMusic : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		DontDestroyOnLoad(gameObject);
	}
}


text:
<!DOCTYPE HTML>

  <title>Test for Bug 475214</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 475214


text:
package com.compomics.sigpep.model;

import java.util.Set;

/**
 * A peptide that can be mapped to a sequence.
 *

 * Created by IntelliJ IDEA.

 * User: mmueller

 * Date: 19-Feb-2008

 * Time: 19:22:38

 */
public interface FeaturePeptide extends Peptide, FeatureObject<PeptideFeature> {

    /**
     * Returns the sequences the peptide is emitted by using the specified protease.
     *
     * @param protease the protease
     * @return the parent sequences
     */
    Set<ProteinSequence> getParentSequences(Protease protease);

    /**
     * Returns whether or not the peptide is a signature peptide.
     *
     * @return true if the peptide is a signature peptide
     */
    boolean isSignaturePeptide();

    /**
     * Sets whether or not the peptide is a signature peptide.
     *
     * @param isSignaturePeptide whether or not the peptide is a signature peptide
     */
    void setSignaturePeptide(boolean isSignaturePeptide);

    /**
     * Returns the proteases that generate this peptide.
     *
     * @return the proteases
     */
    Set<Protease> getProteases();

    /**
     * Sets the proteases that generate this peptide.
     *
     * @param proteases the proteases
     */
    void setProteases(Set<Protease> proteases);
}


text:
[← Botkit Documentation](../core.md)  [← Platform Index](index.md)

# botbuilder-adapter-web
Connect [Botkit](https://www.npmjs.com/package/botkit) or [BotBuilder](https://www.npmjs.com/package/botbuilder) to the Web.

This package contains an adapter that communicates directly with the web via webhooks or websocket connections.
This package can be used alongside your favorite bot development framework to build bots that work on a website or within an existing app.

## Install Package

Add this package to your project using npm:

```bash
npm install --save botbuilder-adapter-web
```

Import the adapter class into your code:

```javascript
const { WebAdapter } = require('botbuilder-adapter-web');
```

## Get Started

If you are starting a brand new project, [follow these instructions to create a customized application template.](../index.md)

## Use WebAdapter in your App

WebAdapter provides a translation layer for Botkit and BotBuilder so that bot developers can connect directly to users on the web.

### Botkit Basics

When used in concert with Botkit, developers need only pass the configured adapter to the Botkit constructor, as seen below. Botkit will automatically create and configure the webhook endpoints and other options necessary for communicating with the web.

Developers can then bind to Botkit's event emitting system using `controller.on` and `controller.hears` to filter and handle incoming events from the messaging platform. [Learn more about Botkit's core feature →](../index.md).

[A full description of the WebAdapter options and example code can be found in the class reference docs.](../reference/web.md#create-a-new-webadapter)

```javascript
const adapter = new WebAdapter();
const controller = new Botkit({
    adapter,
    // ...other options
});

// TODO: expose chat client

controller.on('message', async(bot, message) => {
    await bot.reply(message, 'I heard a message!');
});
```

### BotBuilder Basics

Alternately, developers may choose to use `WebAdapter` with BotBuilder. With BotBuilder, the adapter is used more directly with a webserver, and all incoming events are handled as [Activities](https://docs.microsoft.com/en-us/javascript/api/botframework-schema/activity?view=botbuilder-ts-latest).

[Read more →](../reference/web.md#create-a-new-webadapter)

## Class Reference

* [WebAdapter](../reference/web.md#webadapter)

## Reference Chat Client

This package includes [a reference implementation of a chat client written in HTML/JS/CSS](https://github.com/howdyai/botkit/tree/master/packages/botbuilder-adapter-web/client/#readme) that serves as a base for building a customized chat widget.

> [Using typing indicators with the reference chat client](https://github.com/howdyai/botkit/tree/master/packages/botbuilder-adapter-web/client/#typing-indicators)

## Event List

| Event | Description
|--- |---
| message | a message sent by the user
| hello | event sent when a user first connects
| welcome_back | event sent when a user reconnects
| identify | an extended user profile is being sent by the client to be associated with the user id

## Botkit Extensions

In Botkit handlers, the `bot` worker for web contains [all of the base methods](../reference/core.md) as well as the following platform-specific extensions:

### [adapter.createSocketServer()](../reference/web.md#createsocketserver)

Configures the webserver to accept websocket connections. This method is called automatically by Botkit, but must be manually called when using with BotBuilder.

## Community & Support

Join our thriving community of Botkit developers and bot enthusiasts at large.
Over 10,000 members strong, [our Github site](https://github.com/howdyai/botkit) is
_the place_ for people interested in the art and science of making bots.
Come to ask questions, share your progress, and commune with your peers!

You can also find help from members of the Botkit team [in our dedicated Cisco Spark room](https://eurl.io/#SyNZuomKx)!

## About Botkit

Botkit is a part of the [Microsoft Bot Framework](https://dev.botframework.com).

Want to contribute? [Read the contributor guide](https://github.com/howdyai/botkit/blob/master/CONTRIBUTING.md)

Botkit is released under the [MIT Open Source license](https://github.com/howdyai/botkit/blob/master/LICENSE.md)


text:
package com.example.myprojectjavaa.Module.Frame;

public class MainEntry
{
    public static void main(String[] args)
    {
        System.out.println("main start");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObjectTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <layouts>
        <layout>EDA Application Layout</layout>
        <sections>
            Enllaços personalitzats

Custom Links

        </sections>
    </layouts>
    <nameFieldLabel>Nom de l'aplicació</nameFieldLabel>
    <standardFields>
        <name>Name</name>
        Nom de l'aplicació
    </standardFields>
</CustomObjectTranslation>


text:
package Mail::SPF::Mech::IP4;

=head1 NAME

Mail::SPF::Mech::IP4 - SPF record C<ip4> mechanism class

=cut

use warnings;
use strict;

use base 'Mail::SPF::SenderIPAddrMech';

use constant TRUE   => (0 == 0);
use constant FALSE  => not TRUE;

use constant name           => 'ip4';
use constant name_pattern   => qr/${\name}/i;

=head1 DESCRIPTION

An object of class B<Mail::SPF::Mech::IP4> represents an SPF record mechanism
of type C<ip4>.

=head2 Constructors

The following constructors are provided:

=over

=item B<new(%options)>: returns I<Mail::SPF::Mech::IP4>

Creates a new SPF record C<ip4> mechanism object.

%options is a list of key/value pairs representing any of the following
options:

=over

=item B<qualifier>

=item B<ip_network>

See L<Mail::SPF::Mech/new>.

=back

=item B<new_from_string($text, %options)>: returns I<Mail::SPF::Mech::IP4>;
throws I<Mail::SPF::ENothingToParse>, I<Mail::SPF::EInvalidMech>

Creates a new SPF record C<ip4> mechanism object by parsing the string and
any options given.

=back

=head2 Class methods

The following class methods are provided:

=over

=item B<default_qualifier>

=item B<default_ipv4_prefix_length>

=item B<qualifier_pattern>

See L<Mail::SPF::Mech/Class methods>.

=item B<name>: returns I<string>

Returns B<'ip4'>.

=item B<name_pattern>: returns I<Regexp>

Returns a regular expression that matches a mechanism name of B<'ip4'>.

=back

See L<Mail::SPF::Mech> for other supported class methods.

=head2 Instance methods

The following instance methods are provided:

=over

=cut

sub parse_params {
    my ($self) = @_;
    $self->parse_ipv4_network(TRUE);
    return;
}

=item B<text>

=item B<qualifier>

=item B<params>

=cut

sub params {
    my ($self) = @_;
    my $params = ':' . $self->{ip_network}->addr;
    $params .= '/' . $self->{ip_network}->masklen
        if $self->{ip_network}->masklen != $self->default_ipv4_prefix_length;
    return $params;
}

=item B<stringify>

See L<Mail::SPF::Mech/Instance methods>.

=item B<ip_network>: returns I<NetAddr::IP>

Returns the IP address network parameter of the mechanism.

=cut

# Make read-only accessors:
__PACKAGE__->make_accessor($_, TRUE)
    foreach qw(ip_network ip_address ipv4_prefix_length);

=item B<match($server, $request)>: returns I<boolean>

Returns B<true> if the mechanism's C<ip_network> equals or contains the given
request's IP address, or B<false> otherwise.  See RFC 4408, 5.6, for details.

=cut

sub match {
    my ($self, $server, $request) = @_;
    my $ip_network_v6 =
        $self->ip_network->version == 4 ?
            Mail::SPF::Util->ipv4_address_to_ipv6($self->ip_network)
        :   $self->ip_network;
    return $ip_network_v6->contains($request->ip_address_v6);
}

=back

=head1 SEE ALSO

L<Mail::SPF>, L<Mail::SPF::Record>, L<Mail::SPF::Term>, L<Mail::SPF::Mech>

L<http://www.ietf.org/rfc/rfc4408.txt>

For availability, support, and license information, see the README file
included with Mail::SPF.

=head1 AUTHORS

Julian Mehnle <julian@mehnle.net>, Shevek <cpan@anarres.org>

=cut

TRUE;


text:
if [ -z "$1" ]; then
    COMPILER=vendor/closure-compiler/compiler.jar
else
    COMPILER=$1
fi

java -jar $COMPILER --js mixpanel.js --js_output_file mixpanel.min.js --compilation_level ADVANCED_OPTIMIZATIONS --output_wrapper "(function() {
%output%
})();"

java -jar $COMPILER --js mixpanel-jslib-snippet.js --js_output_file mixpanel-jslib-snippet.min.js --compilation_level ADVANCED_OPTIMIZATIONS

java -jar $COMPILER --js mixpanel-jslib-snippet.js --js_output_file mixpanel-jslib-snippet.min.test.js --compilation_level ADVANCED_OPTIMIZATIONS --define='MIXPANEL_LIB_URL="../mixpanel.min.js"'


text:
The Aurora source repository and distributions contain several
[binary files](../src/test/resources/org/apache/thermos/root/checkpoints) to
qualify the backwards-compatibility of thermos with checkpoint data. Since
thermos persists state to disk, to be read by the thermos observer), it is important that we have
tests that prevent regressions affecting the ability to parse previously-written data.

## Generating test files
The files included represent persisted checkpoints that exercise different
features of thermos. The existing files should not be modified unless
we are accepting backwards incompatibility, such as with a major release.

It is not practical to write source code to generate these files on the fly,
as source would be vulnerable to drift (e.g. due to refactoring) in ways
that would undermine the goal of ensuring backwards compatibility.

The most common reason to add a new checkpoint file would be to provide
coverage for new thermos features that alter the data format. This is
accomplished by writing and running a
[job configuration](configuration-reference.md) that exercises the feature, and
copying the checkpoint file from the sandbox directory, by default this is
`/var/run/thermos/checkpoints/<aurora task id>`.


text:
package org.gnucash.android.ui.settings.dialog;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation;
import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation;

import org.gnucash.android.R;

/**
 * A fragment for adding an ownCloud account.
 */
public class OwnCloudDialogFragment extends DialogFragment {

    /**
     * Dialog positive button. Ok to save and validate the data
     */
    private Button mOkButton;

    /**
     * Cancel button
     */
    private Button mCancelButton;

    /**
     * ownCloud vars
     */
    private String mOC_server;
    private String mOC_username;
    private String mOC_password;
    private String mOC_dir;

    private EditText mServer;
    private EditText mUsername;
    private EditText mPassword;
    private EditText mDir;

    private TextView mServerError;
    private TextView mUsernameError;
    private TextView mDirError;

    private SharedPreferences mPrefs;
    private Context mContext;

    private static CheckBoxPreference ocCheckBox;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @return A new instance of fragment OwnCloudDialogFragment.
     */
    public static OwnCloudDialogFragment newInstance(Preference pref) {
        OwnCloudDialogFragment fragment = new OwnCloudDialogFragment();
        ocCheckBox = pref == null ? null : (CheckBoxPreference) pref;
        return fragment;
    }

    public OwnCloudDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, 0);

        mContext = getActivity();
        mPrefs = mContext.getSharedPreferences(getString(R.string.owncloud_pref), Context.MODE_PRIVATE);

        mOC_server = mPrefs.getString(getString(R.string.key_owncloud_server), getString(R.string.owncloud_server));
        mOC_username = mPrefs.getString(getString(R.string.key_owncloud_username), null);
        mOC_password = mPrefs.getString(getString(R.string.key_owncloud_password), null);
        mOC_dir = mPrefs.getString(getString(R.string.key_owncloud_dir), getString(R.string.app_name));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.dialog_owncloud_account, container, false);

        mServer = (EditText) view.findViewById(R.id.owncloud_hostname);
        mUsername = (EditText) view.findViewById(R.id.owncloud_username);
        mPassword = (EditText) view.findViewById(R.id.owncloud_password);
        mDir = (EditText) view.findViewById(R.id.owncloud_dir);

        mServer.setText(mOC_server);
        mDir.setText(mOC_dir);
        mPassword.setText(mOC_password); // TODO: Remove - debugging only
        mUsername.setText(mOC_username);

        mServerError = (TextView) view.findViewById(R.id.owncloud_hostname_invalid);
        mUsernameError = (TextView) view.findViewById(R.id.owncloud_username_invalid);
        mDirError = (TextView) view.findViewById(R.id.owncloud_dir_invalid);
        mServerError.setVisibility(View.GONE);
        mUsernameError.setVisibility(View.GONE);
        mDirError.setVisibility(View.GONE);

        mCancelButton = (Button) view.findViewById(R.id.btn_cancel);
        mOkButton = (Button) view.findViewById(R.id.btn_save);
        mOkButton.setText(R.string.btn_test);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setListeners();
    }

    private void saveButton() {
        if (mDirError.getText().toString().equals(getString(R.string.owncloud_dir_ok)) &&
                mUsernameError.getText().toString().equals(getString(R.string.owncloud_user_ok)) &&
                mServerError.getText().toString().equals(getString(R.string.owncloud_server_ok)))
            mOkButton.setText(R.string.btn_save);
        else
            mOkButton.setText(R.string.btn_test);
    }

    private void save() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.clear();
        edit.putString(getString(R.string.key_owncloud_server), mOC_server);
        edit.putString(getString(R.string.key_owncloud_username), mOC_username);
        edit.putString(getString(R.string.key_owncloud_password), mOC_password);
        edit.putString(getString(R.string.key_owncloud_dir), mOC_dir);
        edit.putBoolean(getString(R.string.owncloud_sync), true);
        edit.apply();

        if (ocCheckBox != null) ocCheckBox.setChecked(true);

        dismiss();
    }

    private void checkData() {
        mServerError.setVisibility(View.GONE);
        mUsernameError.setVisibility(View.GONE);
        mDirError.setVisibility(View.GONE);

        mOC_server = mServer.getText().toString().trim();
        mOC_username = mUsername.getText().toString().trim();
        mOC_password = mPassword.getText().toString().trim();
        mOC_dir = mDir.getText().toString().trim();

        Uri serverUri = Uri.parse(mOC_server);
        OwnCloudClient mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, mContext, true);
        mClient.setCredentials(
                OwnCloudCredentialsFactory.newBasicCredentials(mOC_username, mOC_password)
        );

        final Handler mHandler = new Handler();

        OnRemoteOperationListener listener = new OnRemoteOperationListener() {
            @Override
            public void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result) {
                if (!result.isSuccess()) {
                    Log.e("OC", result.getLogMessage(), result.getException());

                    if (caller instanceof GetRemoteStatusOperation) {
                        mServerError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red));
                        mServerError.setText(getString(R.string.owncloud_server_invalid));
                        mServerError.setVisibility(View.VISIBLE);

                    } else if (caller instanceof GetRemoteUserInfoOperation &&
                            mServerError.getText().toString().equals(getString(R.string.owncloud_server_ok))) {
                        mUsernameError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red));
                        mUsernameError.setText(getString(R.string.owncloud_user_invalid));
                        mUsernameError.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (caller instanceof GetRemoteStatusOperation) {
                        mServerError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary));
                        mServerError.setText(getString(R.string.owncloud_server_ok));
                        mServerError.setVisibility(View.VISIBLE);
                    } else if (caller instanceof GetRemoteUserInfoOperation) {
                        mUsernameError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary));
                        mUsernameError.setText(getString(R.string.owncloud_user_ok));
                        mUsernameError.setVisibility(View.VISIBLE);
                    }
                }
                saveButton();
            }
        };

        GetRemoteStatusOperation g = new GetRemoteStatusOperation(mContext);
        g.execute(mClient, listener, mHandler);

        GetRemoteUserInfoOperation gu = new GetRemoteUserInfoOperation();
        gu.execute(mClient, listener, mHandler);

        if (FileUtils.isValidPath(mOC_dir, false)) {
            mDirError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary));
            mDirError.setText(getString(R.string.owncloud_dir_ok));
            mDirError.setVisibility(View.VISIBLE);
        } else {
            mDirError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red));
            mDirError.setText(getString(R.string.owncloud_dir_invalid));
            mDirError.setVisibility(View.VISIBLE);
        }
        saveButton();
    }

    /**
     * Binds click listeners for the dialog buttons
     */
    private void setListeners(){

        mCancelButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mOkButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // If data didn't change
                if(mOkButton.getText().toString().equals(getString(R.string.btn_save)) &&
                        mOC_server.equals(mServer.getText().toString().trim()) &&
                        mOC_username.equals(mUsername.getText().toString().trim()) &&
                        mOC_password.equals(mPassword.getText().toString().trim()) &&
                        mOC_dir.equals(mDir.getText().toString().trim())
                        )
                    save();
                else
                    checkData();
            }
        });
    }
}


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2012. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
//  Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
//  Version 4.4.1.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;

namespace ComponentFactory.Krypton.Ribbon
{
    internal class VisualPopupGroup : VisualPopup
    {
        #region Static Fields
        private static readonly int BOTTOMRIGHT_GAP = 4;
        #endregion

        #region Instance Fields
        private KryptonRibbon _ribbon;
        private KryptonRibbonGroup _ribbonGroup;
        private ViewDrawRibbonGroupsBorder _viewBackground;
        private ViewDrawRibbonGroup _viewGroup;
        private bool _restorePreviousFocus;
        private Button _hiddenFocusTarget;
        #endregion

        #region Identity
        /// <summary>
        /// Initialize a new instance of the VisualPopupGroup class.
        /// </summary>
        /// <param name="ribbon">Reference to owning ribbon control.</param>
        /// <param name="ribbonGroup">Reference to ribbon group for display.</param>
        /// <param name="renderer">Drawing renderer.</param>
        public VisualPopupGroup(KryptonRibbon ribbon,
                                KryptonRibbonGroup ribbonGroup,
                                IRenderer renderer)
            : base(renderer, true)
        {
            Debug.Assert(ribbon != null);
            Debug.Assert(ribbonGroup != null);

            // Remember references needed later
            _ribbon = ribbon;
            _ribbonGroup = ribbonGroup;

            // Create a view element for drawing the group
            _viewGroup = new ViewDrawRibbonGroup(ribbon, ribbonGroup, NeedPaintDelegate);
            _viewGroup.Collapsed = false;

            // Create the background that will contain the actual group instance
            _viewBackground = new ViewDrawRibbonGroupsBorder(ribbon, true, NeedPaintDelegate);
            _viewBackground.Add(_viewGroup);

            // Attach the root to the view manager instance
            ViewManager = new ViewRibbonPopupGroupManager(this, ribbon, _viewBackground, _viewGroup, NeedPaintDelegate);

            // Create and add a hidden button to act as the focus target
            _hiddenFocusTarget = new Button();
            _hiddenFocusTarget.TabStop = false;
            _hiddenFocusTarget.Location = new Point(-_hiddenFocusTarget.Width, -_hiddenFocusTarget.Height);
            CommonHelper.AddControlToParent(this, _hiddenFocusTarget);
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Ensure the manager believes the mouse has left the area
                ViewManager.MouseLeave(EventArgs.Empty);

                // Do we need to restore the previous focus from the ribbon
                if (_restorePreviousFocus)
                    _ribbon.RestorePreviousFocus();

                // Mark the group as no longer showing as a popup
                _ribbonGroup.ShowingAsPopup = false;

                // Remove all child controls so they do not become disposed
                for (int i = Controls.Count - 1; i >= 0; i--)
                    Controls.RemoveAt(0);

                // If this group is being dismissed with key tips showing
                if (_ribbon.InKeyboardMode &&_ribbon.KeyTipMode == KeyTipMode.PopupGroup)
                {
                    // Revert back to key tips for selected tab
                    KeyTipMode mode = (_ribbon.RealMinimizedMode ? KeyTipMode.PopupMinimized : KeyTipMode.SelectedGroups);
                    _ribbon.KeyTipMode = mode;
                    _ribbon.SetKeyTips(_ribbon.GenerateKeyTipsForSelectedTab(), mode);
                }
            }

            base.Dispose(disposing);
        }
        #endregion

        #region ViewGroup
        /// <summary>
        /// Gets the view for the popup group.
        /// </summary>
        public ViewDrawRibbonGroup ViewGroup
        {
            get { return _viewGroup; }
        }
        #endregion

        #region RestorePreviousFocus
        /// <summary>
        /// Gets and sets a flag indicating if previous ribbon focus should be restored on dispose.
        /// </summary>
        public bool RestorePreviousFocus
        {
            get { return _restorePreviousFocus; }
            set { _restorePreviousFocus = value; }
        }
        #endregion

        #region SetFirstFocusItem
        /// <summary>
        /// Set focus to the first focus item inside the popup group.
        /// </summary>
        /// <returns>ViewBase of item; otherwise false.</returns>
        public void SetFirstFocusItem()
        {
            ViewPopupManager.FocusView = _viewGroup.GetFirstFocusItem();
            PerformNeedPaint(false);
        }
        #endregion

        #region SetLastFocusItem
        /// <summary>
        /// Set focus to the last focus item inside the popup group.
        /// </summary>
        /// <returns>ViewBase of item; otherwise false.</returns>
        public void SetLastFocusItem()
        {
            ViewPopupManager.FocusView = _viewGroup.GetLastFocusItem();
            PerformNeedPaint(false);
        }
        #endregion

        #region SetNextFocusItem
        /// <summary>
        /// Set focus to the next focus item inside the popup group.
        /// </summary>
        public void SetNextFocusItem()
        {
            // Find the next item in sequence
            bool matched = false;
            ViewBase view = _viewGroup.GetNextFocusItem(ViewPopupManager.FocusView, ref matched);

            // Rotate around to the first item
            if (view == null)
                SetFirstFocusItem();
            else
            {
                ViewPopupManager.FocusView = view;
                PerformNeedPaint(false);
            }
        }
        #endregion

        #region SetPreviousFocusItem
        /// <summary>
        /// Set focus to the previous focus item inside the popup group.
        /// </summary>
        public void SetPreviousFocusItem()
        {
            // Find the previous item in sequence
            bool matched = false;
            ViewBase view = _viewGroup.GetPreviousFocusItem(ViewPopupManager.FocusView, ref matched);

            // Rotate around to the last item
            if (view == null)
                SetLastFocusItem();
            else
            {
                ViewPopupManager.FocusView = view;
                PerformNeedPaint(false);
            }
        }
        #endregion

        #region ShowCalculatingSize
        /// <summary>
        /// Show the group popup relative to the parent group instance.
        /// </summary>
        /// <param name="parentGroup">Parent group instance.</param>
        /// <param name="parentScreenRect">Screen rectangle of the parent.</param>
        public void ShowCalculatingSize(ViewDrawRibbonGroup parentGroup,
                                        Rectangle parentScreenRect)
        {
            Size popupSize;

            // Prevent ribbon from laying out the same group as we are
            // about to get the preferred size from. This reentrancy can
            // happen if the group has a custom control that is then moved
            // to be reparented to the popup group and so therefore cause
            // a layout of the main ribbon.
            _ribbon.SuspendLayout();
            SuspendLayout();

            try
            {
                // Find the size the group requests to be
                using (ViewLayoutContext context = new ViewLayoutContext(this, Renderer))
                    popupSize = _viewGroup.GetPreferredSize(context);

                // Override the height to enforce the correct group height
                popupSize.Height = _ribbon.CalculatedValues.GroupHeight;

                // Mark the group as showing as a popup
                _ribbonGroup.ShowingAsPopup = true;

                // Request we be shown below the parent screen rect
                Show(CalculateBelowPopupRect(parentScreenRect, popupSize));
            }
            finally
            {
                // Reverse the suspend call
                _ribbon.ResumeLayout();
                ResumeLayout();
            }
        }
        #endregion

        #region HideFocus
        /// <summary>
        /// Hide focus by giving it to the hidden control.
        /// </summary>
        public void HideFocus()
        {
            _hiddenFocusTarget.Focus();
        }
        #endregion

        #region Implementation
        private Rectangle CalculateBelowPopupRect(Rectangle parentScreenRect, Size popupSize)
        {
            // Get the screen that the parent rectangle is mostly within, this is the
            // screen we will attempt to place the entire popup within
            Screen screen = Screen.FromRectangle(parentScreenRect);
            Rectangle workingArea = screen.WorkingArea;
            workingArea.Width -= BOTTOMRIGHT_GAP;
            workingArea.Height -= BOTTOMRIGHT_GAP;

            Point popupLocation = new Point(parentScreenRect.X, parentScreenRect.Bottom);

            // Is there enough room below the parent for the entire popup height?
            if ((parentScreenRect.Bottom + popupSize.Height) <= workingArea.Bottom)
            {
                // Place the popup below the parent
                popupLocation.Y = parentScreenRect.Bottom;
            }
            else
            {
                // Is there enough room above the parent for the enture popup height?
                if ((parentScreenRect.Top - popupSize.Height) >= workingArea.Top)
                {
                    // Place the popup above the parent
                    popupLocation.Y = parentScreenRect.Top - popupSize.Height;
                }
                else
                {
                    // Cannot show entire popup above or below, find which has most space
                    int spareAbove = parentScreenRect.Top - workingArea.Top;
                    int spareBelow = workingArea.Bottom - parentScreenRect.Bottom;

                    // Place it in the area with the most space
                    if (spareAbove > spareBelow)
                        popupLocation.Y = workingArea.Top;
                    else
                        popupLocation.Y = parentScreenRect.Bottom;
                }
            }

            // Prevent the popup from being off the left side of the screen
            if (popupLocation.X < workingArea.Left)
                popupLocation.X = workingArea.Left;

            // Preven the popup from being off the right size of the screen
            if ((popupLocation.X + popupSize.Width) > workingArea.Right)
                popupLocation.X = workingArea.Right - popupSize.Width;

            return new Rectangle(popupLocation, popupSize);
        }
        #endregion

        #region Protected
        /// <summary>
        /// Gets access to the popup group specific view manager.
        /// </summary>
        protected ViewRibbonPopupGroupManager ViewPopupManager
        {
            get { return ViewManager as ViewRibbonPopupGroupManager; }
        }

        /// <summary>
        /// Gets the creation parameters.
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= PI.WS_CLIPCHILDREN;
                return cp;
            }
        }

        /// <summary>
        /// Raises the Layout event.
        /// </summary>
        /// <param name="levent">An EventArgs that contains the event data.</param>
        protected override void OnLayout(LayoutEventArgs levent)
        {
            // Let base class calulcate fill rectangle
            base.OnLayout(levent);

            // Ribbon shape determines the border rounding required
            int borderRounding;
            switch (_ribbon.RibbonShape)
            {
                default:
                case PaletteRibbonShape.Office2007:
                    borderRounding = 2;
                    break;
                case PaletteRibbonShape.Office2010:
                    borderRounding = 1;
                    break;
            }

            // Update the region of the popup to be the border path
            using (GraphicsPath roundPath = CommonHelper.RoundedRectanglePath(ClientRectangle, borderRounding))
                Region = new Region(roundPath);
        }

        /// <summary>
        /// Raises the KeyPress event.
        /// </summary>
        /// <param name="e">An KeyPressEventArgs that contains the event data.</param>
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            // If in keyboard mode then pass character onto the key tips
            if (_ribbon.InKeyboardMode && _ribbon.InKeyTipsMode)
                _ribbon.AppendKeyTipPress(char.ToUpper(e.KeyChar));

            base.OnKeyPress(e);
        }

        /// <summary>
        /// Processes a dialog key.
        /// </summary>
        /// <param name="keyData">One of the Keys values that represents the key to process.</param>
        /// <returns>True is handled; otherwise false.</returns>
        protected override bool ProcessDialogKey(Keys keyData)
        {
            // Grab the controlling control that is a parent
            Control c = _ribbon.GetControllerControl(this);

            // Grab the view manager handling the focus view
            ViewBase focusView = ((ViewRibbonPopupGroupManager)GetViewManager()).FocusView;

            // When in keyboard mode...
            if (focusView != null)
            {
                // We pass movements keys onto the view
                switch (keyData)
                {
                    case Keys.Tab | Keys.Shift:
                    case Keys.Tab:
                    case Keys.Left:
                    case Keys.Right:
                    case Keys.Up:
                    case Keys.Down:
                    case Keys.Space:
                    case Keys.Enter:
                        _ribbon.KillKeyboardKeyTips();
                        focusView.KeyDown(new KeyEventArgs(keyData));
                        return true;
                }
            }

            return base.ProcessDialogKey(keyData);
        }
        #endregion
    }
}


text:
require 'rails_helper'

RSpec.describe DockerManager::AdminController do
  describe 'anonymous user' do
    it 'should be a 404' do
      get '/admin/upgrade'

      expect(response.status).to eq(404)
    end
  end

  describe 'when user is not an admin' do
    it 'should 404' do
      sign_in(Fabricate(:user))

      get '/admin/upgrade'
      expect(response.status).to eq(404)
    end
  end

  describe 'when user is an admin' do
    it 'should return the right response' do
      sign_in(Fabricate(:admin))

      get '/admin/upgrade'
      expect(response.status).to eq(200)
    end
  end

  describe '#repos' do
    it 'should return the right response' do
      sign_in(Fabricate(:admin))

      get '/admin/docker/repos'
      expect(response.status).to eq(200)
      body = JSON.parse(response.body)
      expect(body["repos"].first["official"]).to eq(false)
    end
  end
end


text:
package org.elasticsearch.xpack.ml.dataframe.traintestsplit;

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

/**
 * Given a dependent variable, randomly splits the dataset trying
 * to preserve the proportion of each class in the training sample.
 */
public class StratifiedTrainTestSplitter extends AbstractReservoirTrainTestSplitter {

    private final Map<String, SampleInfo> classSamples;

    public StratifiedTrainTestSplitter(List<String> fieldNames, String dependentVariable, Map<String, Long> classCounts,
                                       double trainingPercent, long randomizeSeed) {
        super(fieldNames, dependentVariable, trainingPercent, randomizeSeed);
        this.classSamples = new HashMap<>();
        classCounts.entrySet().forEach(entry -> classSamples.put(entry.getKey(), new SampleInfo(entry.getValue())));
    }

    @Override
    protected SampleInfo getSampleInfo(String[] row) {
        String classValue = row[dependentVariableIndex];
        SampleInfo sample = classSamples.get(classValue);
        if (sample == null) {
            throw new IllegalStateException("Unknown class [" + classValue + "]; expected one of " + classSamples.keySet());
        }
        return sample;
    }
}


text:
using System;
using System.Windows;
using System.Windows.Data;

namespace SQMReorderer.Gui
{
    public class NullToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && targetType == typeof(Visibility))
            {
                return Visibility.Visible;
            }

            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


text:
/**
 * @file sos_ping.c
 * @brief  sos_ping is for pinging the node.
 * @author Simon Han (simonhan@ee.ucla.edu)
 */
#include <sos.h>
#include <unistd.h>
#include <loader/loader.h>
#include <getopt.h>
#include <management/ping/ping.h>

extern int sos_argc;
extern char** sos_argv;
extern char* sos_emu_short_opts;

mod_header_ptr neighbor_get_header();
mod_header_ptr aodv_get_header();
mod_header_ptr ping_get_header();

static struct option long_options[] = {
	{"node", required_argument, NULL, 1},
	{"count", required_argument, NULL, 2},
	{NULL, 0, NULL, 0},
};

static void tool_help(void)
{
	printf("sos_ping --node=<id> --count=<count>\n");
}

static ping_req_t req;

void sos_start(void)
{
    int ch;
	ker_register_module(neighbor_get_header());
	ker_register_module(aodv_get_header());
	ker_register_module(ping_get_header());

	req.count = 0;
	req.addr  = BCAST_ADDRESS;

    optind = 0;
    while(1){
        int option_index = 0;
        ch = getopt_long_only(sos_argc, sos_argv, sos_emu_short_opts,
                              long_options, &option_index);
        if (ch == -1)
            break;
        switch(ch){
		case 1:
			req.addr = (uint16_t) atoi( optarg );
			break;
		case 2:
			req.count = (uint16_t) atoi( optarg );
			break;
        }
    }
	if( req.addr == BCAST_ADDRESS ) {
		printf("No address is defined\n");
		tool_help();
		exit(1);
	}

	post_long(PING_PID, PING_PID, MSG_SEND_PING, sizeof(ping_req_t), &req, 0);
}


text:
'use strict';
var yeoman = require('yeoman-generator');
var _ = require('lodash');
var yosay = require('yosay');
var updateExport = require('../../helpers/updateIndex').updateExport;

module.exports = yeoman.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    this.argument('routeName', {desc: 'The route name (eg. user)', type: String, required: true});
    this.capitalizedRouteName = _.upperFirst(_.camelCase(this.routeName));

    this.containerName = `${this.capitalizedRouteName}Page`;
    this.indexContainerName = `${this.capitalizedRouteName}IndexPage`;

    this.selectorName = `${this.capitalizedRouteName}PageSelector`;
    this.indexSelectorName = `${this.capitalizedRouteName}IndexPageSelector`;

    this.componentName = `Wrapper${this.capitalizedRouteName}Page`;
    this.indexComponentName = `Wrapper${this.capitalizedRouteName}IndexPage`;

    this.routeNameConstant = _.toUpper(_.snakeCase(this.routeName));
  },

  prompting: function () {
    var done = this.async();

    this.log(yosay('I will scaffold a route'));

    this.prompt([
      {
        type: 'input',
        name: 'routeValue',
        message: 'What is the url of the route',
        default: `/${this.routeName}`
      },
      {
        type: 'confirm',
        name: 'asyncRoute',
        message: 'Should this route be asynchronous?',
        default: true
      },
      {
        type: 'list',
        name: 'routeAccessLevel',
        message: 'What is the required access level',
        choices: ['public', 'user', 'admin'],
        default: 0
      },
      {
        type: 'confirm',
        name: 'scaffoldChildRoutes',
        message: 'Will this route have child route?',
        default: false
      },
      {
        type: 'confirm',
        name: 'scaffoldIndexRoute',
        message: 'Will this route have an IndexRoute?',
        default: false
      },
      {
        type: 'confirm',
        name: 'pureRender',
        message: 'Should the components be pure?',
        default: true
      },
      {
        type: 'confirm',
        name: 'redux',
        message: 'Should the component container include redux?',
        default: true
      },
      {
        type: 'confirm',
        name: 'selector',
        message: 'Should the component container include reselect?',
        default: true
      }
    ]).then(function (answers) {
      this.answers = answers;
      done();
    }.bind(this));
  },

  _updateOrCopyRouteIndex() {
    const exportObject = this.answers.asyncRoute ?
      `gen${this.capitalizedRouteName}Route` :
      `${this.routeName}Route`;

    updateExport.bind(this)('src/routes/routes.js', {
      templateFile: 'routeIndex.js',
      templateOptions: {
        routeName: this.routeName,
        capitalizedRouteName: this.capitalizedRouteName,
        asyncRoute: this.answers.asyncRoute
      },
      exportRegex: new RegExp(`export { default as ${exportObject} } from '\\.\\/${this.routeName}';`, 'g'),
      exportString: `export { default as ${exportObject} } from './${this.routeName}';\n`
    });
  },

  _updateOrCopyRouteConstantIndex() {
    updateExport.bind(this)('src/constants/routes.js', {
      templateFile: 'indexRouteConstant.js',
      templateOptions: {
        routeNameConstant: this.routeNameConstant,
        routeValue: this.answers.routeValue
      },
      exportRegex: new RegExp(`export const ${this.routeNameConstant} = '${this.answers.routeValue}';`, 'g'),
      exportString: `export const ${this.routeNameConstant} = '${this.answers.routeValue}';\n`
    });
  },

  _copyRouteIndex() {
    this.fs.copyTpl(
      this.templatePath('index.js'),
      this.destinationPath(`src/routes/${this.routeName}/index.js`),
      {
        scaffoldChildRoutes: this.answers.scaffoldChildRoutes,
        scaffoldIndexRoute: this.answers.scaffoldIndexRoute,

        asyncRoute: this.answers.asyncRoute,

        routeAccessLevel: this.answers.routeAccessLevel,

        routeName: this.routeName,
        routeNameConstant: this.routeNameConstant,

        containerName: this.containerName,
        indexContainerName: this.indexContainerName
      }
    );
  },

  _copyIndexRouteIndex() {
    this.fs.copyTpl(
      this.templatePath('indexRoute.js'),
      this.destinationPath(`src/routes/${this.routeName}/indexRoute.js`),
      {
        asyncRoute: this.answers.asyncRoute,
        routeName: this.routeName
      }
    );
  },

  _copyRoute() {
    this._updateOrCopyRouteConstantIndex();
    this._copyRouteIndex();

    if (this.answers.scaffoldIndexRoute) {
      this._copyIndexRouteIndex();
    }
  },

  _copyContainerPage() {
    this.fs.copyTpl(
      this.templatePath(`container/page/ContainerPage.js`),
      this.destinationPath(`src/routes/${this.routeName}/container/page/${this.containerName}.js`),
      {
        routeName: this.routeName,

        redux: this.answers.redux,
        pureRender: this.answers.pureRender,
        selector: this.answers.selector,

        containerName: this.containerName,
        componentName: this.componentName,
        selectorName: this.selectorName
      }
    );
    this.fs.copyTpl(
      this.templatePath(`container/page/__tests__/ContainerPage-test.js`),
      this.destinationPath(`src/routes/${this.routeName}/container/page/__tests__/${this.containerName}-test.js`),
      {
        redux: this.answers.redux,
        pureRender: this.answers.pureRender,

        componentName: this.componentName,
        containerName: this.containerName
      }
    );
    this.fs.copyTpl(
      this.templatePath('container/page/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/container/page/index.js`),
      {
        containerName: this.containerName
      }
    );
  },

  _copyContainerIndexPage() {
    this.fs.copyTpl(
      this.templatePath(`container/indexRoute/ContainerIndexPage.js`),
      this.destinationPath(`src/routes/${this.routeName}/container/indexRoute/${this.indexContainerName}.js`),
      {
        routeName: this.routeName,

        redux: this.answers.redux,
        pureRender: this.answers.pureRender,
        selector: this.answers.selector,

        indexContainerName: this.indexContainerName,
        indexComponentName: this.indexComponentName,
        indexSelectorName: this.indexSelectorName
      }
    );
    this.fs.copyTpl(
      this.templatePath(`container/indexRoute/__tests__/ContainerIndexPage-test.js`),
      this.destinationPath(`src/routes/${this.routeName}/container/indexRoute/__tests__/${this.indexContainerName}-test.js`),
      {
        redux: this.answers.redux,
        pureRender: this.answers.pureRender,

        indexContainerName: this.indexContainerName,
        indexComponentName: this.indexComponentName
      }
    );
    this.fs.copyTpl(
      this.templatePath('container/indexRoute/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/container/indexRoute/index.js`),
      {
        indexContainerName: this.indexContainerName
      }
    );
  },

  _copyContainerIndex() {
    this.fs.copyTpl(
      this.templatePath('container/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/container/index.js`),
      {
        scaffoldIndexRoute: this.answers.scaffoldIndexRoute,

        containerName: this.containerName,
        indexContainerName: this.indexContainerName
      }
    );
  },

  _copyContainer() {
    this._copyContainerPage();

    if (this.answers.scaffoldIndexRoute) {
      this._copyContainerIndexPage();
    }

    this._copyContainerIndex();
  },

  _copyComponentPage() {
    this.fs.copyTpl(
      this.templatePath(`component/page/WrapperPage.js`),
      this.destinationPath(`src/routes/${this.routeName}/component/page/${this.componentName}.js`),
      {
        pureRender: this.answers.pureRender,

        componentName: this.componentName
      }
    );
    this.fs.copyTpl(
      this.templatePath(`component/page/__tests__/WrapperPage-test.js`),
      this.destinationPath(`src/routes/${this.routeName}/component/page/__tests__/${this.componentName}-test.js`),
      {
        pureRender: this.answers.pureRender,

        componentName: this.componentName
      }
    );
    this.fs.copyTpl(
      this.templatePath('component/page/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/component/page/index.js`),
      {
        componentName: this.componentName
      }
    );
  },

  _copyComponentIndexPage() {
    this.fs.copyTpl(
      this.templatePath(`component/indexRoute/ComponentIndexPage.js`),
      this.destinationPath(`src/routes/${this.routeName}/component/indexRoute/${this.indexComponentName}.js`),
      {
        pureRender: this.answers.pureRender,

        indexComponentName: this.indexComponentName
      }
    );
    this.fs.copyTpl(
      this.templatePath(`component/indexRoute/__tests__/ComponentIndexPage-test.js`),
      this.destinationPath(`src/routes/${this.routeName}/component/indexRoute/__tests__/${this.indexComponentName}-test.js`),
      {
        pureRender: this.answers.pureRender,

        indexComponentName: this.indexComponentName
      }
    );
    this.fs.copyTpl(
      this.templatePath('component/indexRoute/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/component/indexRoute/index.js`),
      {
        indexComponentName: this.indexComponentName
      }
    );
  },

  _copyComponentIndex() {
    this.fs.copyTpl(
      this.templatePath('component/index.js'),
      this.destinationPath(`src/routes/${this.routeName}/component/index.js`),
      {
        scaffoldIndexRoute: this.answers.scaffoldIndexRoute,

        componentName: this.componentName,
        indexComponentName: this.indexComponentName
      }
    );
  },

  _copyComponents() {
    this._copyComponentPage();

    if (this.answers.scaffoldIndexRoute) {
      this._copyComponentIndexPage();
    }

    this._copyComponentIndex();
  },

  _copyContainerSelector() {
    this.fs.copyTpl(
      this.templatePath(`selector/page/ContainerSelector.js`),
      this.destinationPath(`src/routes/${this.routeName}/selector/page/${this.selectorName}.js`),
      {}
    );
    this.fs.copyTpl(
      this.templatePath(`selector/page/index.js`),
      this.destinationPath(`src/routes/${this.routeName}/selector/page/index.js`),
      {
        selectorName: this.selectorName
      }
    );
  },

  _copyContainerIndexSelector() {
    this.fs.copyTpl(
      this.templatePath(`selector/indexRoute/IndexPageSelector.js`),
      this.destinationPath(`src/routes/${this.routeName}/selector/indexRoute/${this.indexSelectorName}.js`),
      {}
    );

    this.fs.copyTpl(
      this.templatePath(`selector/indexRoute/index.js`),
      this.destinationPath(`src/routes/${this.routeName}/selector/indexRoute/index.js`),
      {
        indexSelectorName: this.indexSelectorName
      }
    );
  },

  _copySelectorIndex() {
    this.fs.copyTpl(
      this.templatePath(`selector/index.js`),
      this.destinationPath(`src/routes/${this.routeName}/selector/index.js`),
      {
        scaffoldIndexRoute: this.answers.scaffoldIndexRoute,

        selectorName: this.selectorName,
        indexSelectorName: this.indexSelectorName
      }
    );
  },

  _copySelector() {
    this._copyContainerSelector();

    if (this.answers.scaffoldIndexRoute) {
      this._copyContainerIndexSelector();
    }

    this._copySelectorIndex();
  },

  writing: function () {
    this._copyRoute();

    this._copyContainer();

    this._copyComponents();

    if (this.answers.selector) {
      this._copySelector();
    }

    this._updateOrCopyRouteIndex();
  },

  end: function () {
    this.log('The route has been initialized.');
  }
});


text:
namespace crypto { POD_CLASS hash; }

class message_writer
{
public:
  message_writer(epee::log_space::console_colors color = epee::log_space::console_color_default, bool bright = false,
                 std::string&& prefix = std::string(), int log_level = LOG_LEVEL_2);

  message_writer(message_writer&& rhs);

  template<typename T>
  std::ostream& operator<<(const T& val)
  {
    m_oss << val;
    return m_oss;
  }

  ~message_writer();

private:
  message_writer(message_writer& rhs);
  message_writer& operator=(message_writer& rhs);
  message_writer& operator=(message_writer&& rhs);

private:
  bool m_flush;
  std::stringstream m_oss;
  epee::log_space::console_colors m_color;
  bool m_bright;
  int m_log_level;
};

message_writer success_msg_writer(bool color = false);
message_writer fail_msg_writer();

void capturing_exceptions(const std::function<void()>&& f);