text:
/** @file SimpleChat.cpp
	@brief */

#include <iostream>
#include <string>

#include "kNet.h"
#include "kNet/DebugMemoryLeakCheck.h"

//#undef _MSC_VER

using namespace std;
using namespace kNet;

const unsigned long cChatMessageID = 42;

class NetworkApp : public INetworkServerListener, public IMessageHandler
{
	Network network;
	// If we are the server, this pointer will be nonzero.
	NetworkServer *server;
	// If we are the client, this pointer will be nonzero.
	Ptr(MessageConnection) connection;

	// Will contain the chat message as it is being typed on the command line.
	std::string inputText;

public:
	NetworkApp()
	:server(0)
	{
	}

	// The server must implement this message.
	bool NewConnectionAttempt(const EndPoint & UNUSED(endPoint), const char * UNUSED(data), size_t UNUSED(numBytes))
	{
		// Allow the client to connect.
		return true;
	}

	/// Called to notify the listener that a new connection has been established.
	void NewConnectionEstablished(MessageConnection *connection)
	{
		cout << "New connection from " << connection->ToString() << "." << endl;
		connection->RegisterInboundMessageHandler(this);
	}

	void HandleMessage(MessageConnection *source, packet_id_t /*packetId*/, message_id_t messageId, const char *data, size_t numBytes)
	{
		if (messageId == cChatMessageID)
			OnChatMessageReceived(source, data, numBytes);
	}

	void RunServer(unsigned short port, SocketTransportLayer transport)
	{
		// Start the server either in TCP or UDP mode.
		server = network.StartServer(port, transport, this, true);
		if (!server)
		{
			cout << "Unable to start server in port " << port << "!" << endl;
			return;
		}

		cout << "Server waiting for connection in port " << port << "." << endl;

		while(server->GetConnections().size() == 0)
		{
			server->Process();
			Clock::Sleep(100);
		}

		Ptr(MessageConnection) clientConnection = server->GetConnections().begin()->second;

		// Stop accepting any further connections.
//		server->SetAcceptNewConnections(false);

		RunChat(clientConnection);
	}

	void RunClient(const char *address, unsigned short port, SocketTransportLayer transport)
	{
		connection = network.Connect(address, port, transport, 0);
		if (!connection)
		{
			cout << "Unable to connect to " << address << ":" << port << "." << endl;
			return;
		}

		cout << "Waiting for connection.." << endl;
		bool success = connection->WaitToEstablishConnection();
		if (!success)
		{
			cout << "Failed to connect to server!" << endl;
			return;
		}

		cout << "Connected to " << connection->GetSocket()->ToString() << "." << endl;

		RunChat(connection);
	}

	void OnChatMessageReceived(MessageConnection *connection, const char *message, int numBytes)
	{
		char str[1025] = {};
		strncpy(str, message, numBytes-1); // '-1' to take into account the null byte in the message.
		// Note: We can't assume the sender sent the null byte in the message, it might be an ill-crafted message!
		if (inputText.length() > 0)
			cout << endl;
		cout << connection->RemoteEndPoint().ToString() << " says: " << str << endl;
		if (inputText.length() > 0)
			cout << "> " << inputText;

		// If we are the server, make the received message go to all other connected clients as well.
		if (server)
			server->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, numBytes, connection);
	}

	void SendChatMessage(const char *message)
	{
		// Always remember to sanitize data at both ends.
		const unsigned long cMaxMsgSize = 1024;
		if (strlen(message) >= cMaxMsgSize)
			throw NetException("Tried to send too large chat message!");

		const size_t messageLength = strlen(message)+1; // Add one to the length to guarantee a null byte to the stream.
		if (server)
			server->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, messageLength);
		else if (connection && connection->IsWriteOpen())
			connection->SendMessage(cChatMessageID, true, true, 100, 0, message, messageLength);
	}

#ifdef _MSC_VER // On windows, poll for new messages to send from the console instead of blocking.
	void Win32PeekConsoleInput()
	{
		// Get the standard input handle.
		HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
		if (hStdin == INVALID_HANDLE_VALUE)
			throw std::exception("Failed to get stdin handle!");

		// Wait for the events.
		INPUT_RECORD irInBuf[128];
		DWORD numRead = 0;
		if (!PeekConsoleInput(hStdin, irInBuf, 1, &numRead))
			throw std::exception("PeekConsoleInput failed!");
		if (numRead > 0)
		{
			if (!ReadConsoleInput(hStdin, irInBuf, 128, &numRead))
				throw std::exception("ReadConsoleInput failed!");
			for (DWORD i = 0; i < numRead; i++)
				if (irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown == TRUE)
					if (irInBuf[i].Event.KeyEvent.wVirtualKeyCode == VK_RETURN) // Enter key
					{
						if (inputText == "exit" || inputText == "quit" || inputText == "q")
						{
							if (connection)
								connection->Close();
							if (server)
								server->Close(500);
						}
						else if (inputText.length() > 0)
							SendChatMessage(inputText.c_str());
						inputText = "";
						cout << endl;
					}
					else
					{
						char str[2] = {};
						str[0] = irInBuf[i].Event.KeyEvent.uChar.AsciiChar;
						if (str[0] >= 32 && str[0] <= 127)
						{
							if (inputText.length() == 0)
								cout << "> ";
							cout << str[0]; // Echo the character we inputted back to console (yes, there might be a flag for this)
							inputText += std::string(str);
						}
					}
		}
	}
#endif

	void RunChat(Ptr(MessageConnection) connection)
	{
#ifdef _MSC_VER
		// Get the standard input handle.
		HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
		if (hStdin == INVALID_HANDLE_VALUE)
			throw std::exception("Failed to get stdin handle!");

		// Save the current input mode, to be restored on exit.
		DWORD oldInputMode;
		if (!GetConsoleMode(hStdin, &oldInputMode))
			throw std::exception("GetConsoleMode failed!");

		// Enable the window and mouse input events.
		if (!SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT))
			throw std::exception("SetConsoleMode failed!");
#endif

		cout << "Chat running. Type messages and send them by pressing Enter. Type 'q'/'exit'/'quit' to disconnect." << endl;

		while((server && server->GetConnections().size() > 0) || (connection && connection->IsReadOpen()))
		{
			if (server)
				server->Process();

			if (!connection->IsReadOpen())
				connection->Disconnect();

			for(int i = 0; i < 100; ++i) // Process a maximum of 100 messages at one go.
			{
				NetworkMessage *msg = connection->ReceiveMessage(50);
				if (!msg)
					break;

				if (msg->id == cChatMessageID && msg->Size() > 0)
					OnChatMessageReceived(connection, &msg->data[0], msg->Size());
				connection->FreeMessage(msg);
			}

#ifdef _MSC_VER
			Win32PeekConsoleInput();
#else
			char inputText[256] = {};
			cout << "Enter a text to say: ";
			cin.getline(inputText, 255, '\n');
			if (strlen(inputText) > 0)
			{
				if (!strcmp(inputText, "quit") || !strcmp(inputText, "exit") || !strcmp(inputText, "q"))
					connection->Close();
				else
					SendChatMessage(inputText);
			}
#endif
			// Nothing in the above sleeps or blocks to wait for any events. Sleep() to keep the CPU use down.
			kNet::Clock::Sleep(1);
		}
		cout << "Disconnected." << endl;
	}
};

void PrintUsage()
{
	cout << "Usage: " << endl;
	cout << "       tcp|udp server port" << endl;
	cout << "       tcp|udp client hostname port" << endl;
}

BottomMemoryAllocator bma;

int main(int argc, char **argv)
{
	if (argc < 4)
	{
		PrintUsage();
		return 0;
	}

	kNet::SetLogChannels(LogUser | LogInfo | LogError);

	EnableMemoryLeakLoggingAtExit();

	SocketTransportLayer transport = StringToSocketTransportLayer(argv[1]);
	if (transport == InvalidTransportLayer)
	{
		cout << "The first parameter is either 'tcp' or 'udp'!" << endl;
		return 0;
	}
	NetworkApp app;
	if (!_stricmp(argv[2], "server"))
	{
		unsigned short port = (unsigned short)atoi(argv[3]);

		app.RunServer(port, transport);
	}
	else if (!_stricmp(argv[2], "client"))
	{
		if (argc < 5)
		{
			PrintUsage();
			return 0;
		}

		unsigned short port = (unsigned short)atoi(argv[4]);
		app.RunClient(argv[3], port, transport);
	}
	else
	{
		cout << "The second parameter is either 'server' or 'client'!" << endl;
		return 0;
	}
}


text:
import asynctest
import mock
import pytest

from paasta_tools.monitoring.check_mesos_duplicate_frameworks import (
    check_mesos_no_duplicate_frameworks,
)

def test_check_mesos_no_duplicate_frameworks_ok(capfd):
    with mock.patch(
        "paasta_tools.monitoring.check_mesos_duplicate_frameworks.parse_args",
        autospec=True,
    ) as mock_parse_args, mock.patch(
        "paasta_tools.monitoring.check_mesos_duplicate_frameworks.get_mesos_master",
        autospec=True,
    ) as mock_get_mesos_master:
        mock_opts = mock.MagicMock()
        mock_opts.check = "marathon"
        mock_parse_args.return_value = mock_opts
        mock_master = mock.MagicMock()
        mock_master.state = asynctest.CoroutineMock(
            func=asynctest.CoroutineMock(),  # https://github.com/notion/a_sync/pull/40
            return_value={
                "frameworks": [
                    {"name": "marathon"},
                    {"name": "marathon1"},
                    {"name": "foobar"},
                    {"name": "foobar"},
                ]
            },
        )
        mock_get_mesos_master.return_value = mock_master

        with pytest.raises(SystemExit) as error:
            check_mesos_no_duplicate_frameworks()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert "Framework: marathon count: 2" in out
        assert "foobar" not in out
        assert error.value.code == 0

def test_check_mesos_no_duplicate_frameworks_critical(capfd):
    with mock.patch(
        "paasta_tools.monitoring.check_mesos_duplicate_frameworks.parse_args",
        autospec=True,
    ) as mock_parse_args, mock.patch(
        "paasta_tools.monitoring.check_mesos_duplicate_frameworks.get_mesos_master",
        autospec=True,
    ) as mock_get_mesos_master:
        mock_opts = mock.MagicMock()
        mock_opts.check = "marathon"
        mock_parse_args.return_value = mock_opts
        mock_master = mock.MagicMock()
        mock_master.state = asynctest.CoroutineMock(
            func=asynctest.CoroutineMock(),  # https://github.com/notion/a_sync/pull/40
            return_value={
                "frameworks": [
                    {"name": "marathon"},
                    {"name": "marathon1"},
                    {"name": "marathon1"},
                    {"name": "foobar"},
                    {"name": "foobar"},
                ]
            },
        )
        mock_get_mesos_master.return_value = mock_master

        with pytest.raises(SystemExit) as error:
            check_mesos_no_duplicate_frameworks()
        out, err = capfd.readouterr()
        assert (
            "CRITICAL: There are 2 connected marathon1 frameworks! (Expected 1)" in out
        )
        assert "marathon" in out
        assert "foobar" not in out
        assert error.value.code == 2

redpajama_set_name: RedPajamaGithub


text:
var apiHelper = require('./helper'),
  keys = require('./../pg/keys'),
  ss = require('socketstream'),
  pgHelper = require('./../pg/helper'),
  market = require('./../pg/market'),
  snapshot = require('./../pg/snapshot'),
  Counter = function () {
    this.totalCount = 0;
    this.runningCount = 0;
    this.apiCallTime = new Date();
  },

// All of our outstanding or inprogress contracts should be updated
snapshotContracts = function (characterid, keygroup, theCounter) {

  theCounter.runningCount++;
  if (theCounter.totalCount === theCounter.runningCount) {
    pgHelper.fetchRow('evefinancial', 'Get Contract Snapshot', "SELECT sum(price) as total, date FROM contract WHERE date = $1 AND keygroup = $2 and characterid = $3 GROUP BY date", [theCounter.apiCallTime, keygroup, characterid], function (result) {
      snapshot.insertSnapshot(keygroup, characterid, 'contract', result.total ? parseFloat(result.total) : 0, theCounter.apiCallTime, function (result) {

      });
    });
  }

},

getContractItems = function (keygroup, characterid, result, keyinfo, contractid, theCounter) {
  var rowset,
      i = 0,
      rowsetLength,
      params;

  keyinfo.contractID = contractid;
  theCounter.totalCount++;

  // Obtain all the items inside a contract
  apiHelper.callApi('/' + keyinfo.callType + '/ContractItems.xml.aspx', keyinfo, function (result) {
    if (!result || result.eveapi.error || !result.eveapi.result[0].rowset[0].row) {
      return false;
    }

    rowset = result.eveapi.result[0].rowset[0];
    rowsetLength = rowset.row.length;

    // Loop through all the contract items and add them to the db
    for (i; i < rowsetLength; i++) {
        params = apiHelper.constructParams(rowset.row[i].$);
        params.characterid = characterid;
        params.keygroup = keygroup;
        params.date = theCounter.apiCallTime;
        insertNewContractItem(params, characterid, keygroup, theCounter);
    }

  });

};

exports.getContracts = function (keygroup, characterid, result, keyinfo, cb) {

  var rowset = result.eveapi.result[0].rowset[0],
      i = 0,
      rowsetLength = rowset.row.length,
      theCounter = new Counter(),
      params;

  theCounter.apiCallTime = result.eveapi.currentTime;

  for (i; i < rowsetLength; i++) {

    params = apiHelper.constructParams(rowset.row[i].$);
    params.characterid = characterid;
    params.keygroup = keygroup;
    params.date = result.eveapi.currentTime;

    if (params.status === 'Outstanding' || params.status === 'InProgress') {
      getContractItems(keygroup, characterid, result, keyinfo, params.contractid, theCounter);
    }
  }

  // If there's nothing in here, then snapshot it anyway so we have an entry in the table
  if (rowsetLength === 0) {
    theCounter.totalCount++;
    snapshotContracts(characterid, keygroup, theCounter);
  }

  cb(result.eveapi.cachedUntil, result.eveapi.currentTime);

};

exports.insertNewContractItem = insertNewContractItem = function (params, characterid, keygroup, theCounter) {

  var price = 0;

  // The asset costs should already be in the database - the api queue takes care of that for us
  market.getItemCost(params.typeid, function (result) {
    if (result) {

      // Don't set the price if the item is a BPC
      if (params.rawquantity !== '-2') {
        params.price = result;
      }

      pgHelper.insert('evefinancial', 'Insert new contract item', 'contract', params, false, function (result) {
        if (!result) {
          console.log('➙'.cyan, 'contractItemInsert'.grey, result);
        } else {
          snapshotContracts(characterid, keygroup, theCounter);
        }
      });
    } else {
      snapshotContracts(characterid, keygroup, theCounter);
    }

  });

};


text:
package org.myrobotlab.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis;
import org.myrobotlab.service.config.PollyConfig;
import org.myrobotlab.service.data.AudioData;
import org.slf4j.Logger;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPolly;
import com.amazonaws.services.polly.AmazonPollyClient;
import com.amazonaws.services.polly.AmazonPollyClientBuilder;
import com.amazonaws.services.polly.model.AmazonPollyException;
import com.amazonaws.services.polly.model.DescribeVoicesRequest;
import com.amazonaws.services.polly.model.DescribeVoicesResult;
import com.amazonaws.services.polly.model.SynthesizeSpeechRequest;
import com.amazonaws.services.polly.model.SynthesizeSpeechResult;
import com.amazonaws.services.polly.model.TextType;

/**
 * Amazon's cloud speech service
 *
 * Free Tier The Amazon Polly free tier includes 5 million characters per month,
 * for the first 12 months, starting from the first request for speech.
 *
 * Polly Pricing Pay-as-you-go $4.00 per 1 million characters (when outside the
 * free tier).
 *
 * Ssml - https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html
 * https://docs.amazonaws.cn/en_us/polly/latest/dg/polly-dg.pdf
 *
 * @author GroG
 *
 */
public class Polly extends AbstractSpeechSynthesis {

  private static final long serialVersionUID = 1L;

  public final static Logger log = LoggerFactory.getLogger(Polly.class);

  public final static String AMAZON_POLLY_USER_KEY = "amazon.polly.user.key";
  public final static String AMAZON_POLLY_USER_SECRET = "amazon.polly.user.secret";

  private transient AWSCredentials credentials;
  private transient AmazonPolly polly;

  Regions defaultRegion;

  public Polly(String n, String id) {
    super(n, id);
  }

  /**
   * for the user's convenience for amazon other cloud providers have single
   * keys or different details
   *
   * @param keyId
   *          aws polly user key
   * @param keyIdSecret
   *          aws polly user secret
   */
  public void setKeys(String keyId, String keyIdSecret) {
    setKey(AMAZON_POLLY_USER_KEY, keyId);
    setKey(AMAZON_POLLY_USER_SECRET, keyIdSecret);
    loadVoices();
  }

  /**
   * loadVoices - must be loaded by SpeechSynthesis class - contract of
   * AbstractSpeechSynthesis
   */
  @Override
  protected void loadVoices() {
    getPolly();

    if (polly == null) {
      error("cannot load voices - polly not initialized");
      return;
    } else {
      setReady(true);
    }

    // Create describe voices request.
    DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
    DescribeVoicesResult describeVoicesResult = polly.describeVoices(describeVoicesRequest);
    List<com.amazonaws.services.polly.model.Voice> awsVoices = describeVoicesResult.getVoices();
    log.info("found {} voices", awsVoices.size());
    for (int i = 0; i < awsVoices.size(); ++i) {
      com.amazonaws.services.polly.model.Voice awsImpl = awsVoices.get(i);
      log.info("{} voice {}", i, awsImpl);
      // stripAccents : Voices with accent seem no worky ( anymore )
      addVoice(StringUtils.stripAccents(awsImpl.getName()), awsImpl.getGender(), awsImpl.getLanguageCode(), awsImpl);
    }
    broadcastState();
  }

  /**
   * @param regionName
   *          set default region for polly
   */
  public void setRegion(String regionName) {
    defaultRegion = Regions.fromName(regionName);
  }

  /**
   * For a cloud provider we have to make sure certain dependencies are met,
   * inter-net connect, keys, and the population of AbstractSpeechSynthesis
   * voices.
   *
   * @return polly client
   */
  private AmazonPolly getPolly() {

    if (defaultRegion == null) {
      defaultRegion = Regions.DEFAULT_REGION;
    }

    String key = getKey(AMAZON_POLLY_USER_KEY);
    String secret = getKey(AMAZON_POLLY_USER_SECRET);

    if (key == null || secret == null) {
      error("this service requires a key and a secret");
      return null;
    }

    if (polly == null) {
      try {

        if (credentials == null) {
          // try credential chain - in case they have set env vars
          credentials = new BasicAWSCredentials(key, secret);
        }

        polly = AmazonPollyClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(defaultRegion).build();

      } catch (Exception e) {
        try {
          log.error("could not get client with keys supplied - trying default chain", e);
          polly = AmazonPollyClient.builder().withCredentials(new DefaultAWSCredentialsProviderChain()).withClientConfiguration(new ClientConfiguration()).withRegion(defaultRegion)
              .build();
        } catch (Exception e2) {

          error("could not get Polly client - did you set the keys?");
          log.error("giving up", e2);

          polly = null;
          credentials = null;
        }
      }
    }
    if (polly != null) {
      // check for credentials OK, because this is not catch upper
      try {
        DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
        polly.describeVoices(describeVoicesRequest);
      } catch (AmazonPollyException e3) {
        error("The keys are invalid");
        polly = null;
        credentials = null;
      }
    }
    return polly;
  }

  @Override
  public String[] getKeyNames() {
    return new String[] { AMAZON_POLLY_USER_KEY, AMAZON_POLLY_USER_SECRET };
  }

  /*
   * Proxy works in 3 modes client - consumer of mrl services relay - proxy
   * (running as cloud service) direct - goes direct to service In Polly's case
   * - client - would be an end user using a client key relay - is the mrl proxy
   * service direct would be from a users, by-passing mrl and going directly to
   * Amazon with amazon keys cache file - caches file locally (both client or
   * relay)
   */
  @Override
  public AudioData generateAudioData(AudioData audioData, String toSpeak) throws IOException {
    PollyConfig c = (PollyConfig) config;
    getPolly();
    Voice voice = getVoice();
    if (voice == null) {
      error("invalid voice - have keys been set ?");
      return null;
    }
    // com.amazonaws.services.polly.model.Voice awsVoice =
    // ((com.amazonaws.services.polly.model.Voice) voice.getVoiceProvider());
    SynthesizeSpeechRequest synthReq = new SynthesizeSpeechRequest().withText(toSpeak).withVoiceId(voice.getName()).withOutputFormat("mp3");

    if (toSpeak.contains("<speak") && c.autoDetectSsml) {
      c.ssml = true;
    } else if (!toSpeak.contains("<speak") && c.autoDetectSsml) {
      c.ssml = false;
    }

    if (c.ssml) {
      synthReq.setTextType(TextType.Ssml);
    }
    SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq);
    InputStream data = synthRes.getAudioStream();
    byte[] d = FileIO.toByteArray(data);
    // could just save it to file ...
    // return new AudioData(data);
    FileIO.toFile(audioData.getFileName(), d);
    return audioData;
  }

  public boolean setSsml(boolean ssml) {
    PollyConfig c = (PollyConfig) config;
    c.ssml = ssml;
    return ssml;
  }

  public boolean setAutoDetectSsml(boolean ssml) {
    PollyConfig c = (PollyConfig) config;
    c.ssml = ssml;
    return ssml;
  }

  public static void main(String[] args) {
    try {
      LoggingFactory.init("INFO");

      Runtime.start("polly", "Polly");
      // Runtime runtime = Runtime.getInstance();
      // runtime.save();

      // Runtime.start("python", "Python");

      // Plan plan = Runtime.load("webgui", "WebGui");
      // // Plan plan = Runtime.load("polly", "Polly");
      //
      // WebGuiConfig webgui = (WebGuiConfig)plan.get("webgui");
      // webgui.autoStartBrowser = false;
      //
      // Runtime.setConfig("default");
      // Runtime.load("polly");
      //
      // Runtime.startConfig("webgui");
      // Runtime.startConfig("polly");

      WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
      webgui.autoStartBrowser(false);
      webgui.startService();

      boolean b = true;
      if (b) {
        return;
      }

      // iterate through all speech services
      // all will "load" voices and adhere to the AbtractSpeechSynthesis
      // processing of data

      // test all caching

      // test all effects

      // test default

      // test overriding default

      // test setting Runtime.locale
      // Platform.setVirtual(true);

      // LoggingFactory.init(Level.INFO);

      // set language universally
      // Runtime.setLanguage("pt");
      // Runtime.start("gui", "SwingGui");

      Polly polly = (Polly) Runtime.start("polly", "Polly");
      // polly.setKey(keyName, keyValue);
      // polly.setKeys("XXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXX");

      // polly.setLanguage("de");
      log.info("polly voice is {}", polly.getVoice());
      // polly.speak(String.format("allo there my name is %s",
      // polly.getVoice().getName()));

      // Runtime.start("gui", "SwingGui");
      // add your amazon access key & secret
      // use gui to do this, or force it here only ONCE :
      // polly.setKeys("key","secret");

      List<Voice> voices = polly.getVoices();
      for (Voice voice : voices) {
        // polly.setVoice(voice); String lang = polly.getLanguage();
        log.info("{}", voice);
      }

      polly.speak(String.format("Hello my name is %s I will be your voice today", polly.getVoice().getName()));
      polly.speakBlocking("or to take arms against a see of troubles");
      polly.speak("the slings and arrows of ourtrageous fortune");
      polly.speak("#THROAT01_M# hi! it works.");

      for (Voice voice : voices) {
        polly.setVoice((String) voice.getVoiceProvider());
        String lang = voice.getLanguage();
        log.info("{} speaks {}", voice, lang);

        if (lang.startsWith("es")) {
          polly.speak(String.format("Hola, mi nombre es %s y creo que myrobotlab es genial!", voice));
        } else if (lang.startsWith("en")) {
          polly.speak(String.format("Hi my name is %s and I think myrobotlab is great!", voice));
        } else if (lang.startsWith("fr")) {
          polly.speak(String.format("Bonjour, mon nom est %s et je pense que myrobotlab est génial!!", voice));
        } else if (lang.startsWith("nl")) {
          polly.speak(String.format("Hallo, mijn naam is %s en ik denk dat myrobotlab is geweldig!", voice));
        } else if (lang.startsWith("ru")) {
          polly.speak(String.format("Привет, меня зовут %s, и я думаю, что myrobotlab - это здорово!", voice));
        } else if (lang.startsWith("ro")) {
          polly.speak(String.format("Buna ziua, numele meu este %s și cred că myrobotlab este mare!", voice));
        } else if (lang.startsWith("ro")) {
          polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
        } else if (lang.startsWith("it")) {
          polly.speak(String.format("Ciao, il mio nome è %s e penso myrobotlab è grande!", voice));
        } else if (lang.startsWith("is")) {
          polly.speak(String.format("Halló, Nafn mitt er %s og ég held myrobotlab er frábært!", voice));
        } else if (lang.startsWith("cy")) {
          polly.speak(String.format("Helo, fy enw i yw %s a fi yn meddwl myrobotlab yn wych!", voice));
        } else if (lang.startsWith("de")) {
          polly.speak(String.format("Hallo, mein Name ist %s und ich denke, myrobotlab ist toll!", voice));
        } else if (lang.startsWith("da")) {
          polly.speak(String.format("Hej, mit navn er %s og jeg tror myrobotlab er fantastisk!", voice));
        } else if (lang.startsWith("sv")) {
          polly.speak(String.format("Hej, mitt namn %s och jag tror ElektronikWikin är stor!", voice));
        } else if (lang.startsWith("pl")) {
          polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
        } else if (lang.startsWith("tr")) {
          polly.speak(String.format("Merhaba, adım adım %s ve myrobotlab'ın harika olduğunu düşünüyorum!", voice));
        } else if (lang.startsWith("pt")) {
          polly.speak(String.format("Olá, meu nome é %s e eu acho que myrobotlab é ótimo!!", voice));
        } else if (lang.startsWith("ja")) {
          polly.speak(String.format("こんにちは、私の名前は%sで、私はmyrobotlabが素晴らしいと思います!", voice));
        } else {
          log.info("dunno");
        }
      }

      polly.setVoice("Russel");
      polly.setVoice("Nicole");

      polly.setVoice("Brian");
      polly.setVoice("Amy");
      polly.setVoice("Emma");

      polly.setVoice("Brian");
      polly.setVoice("Kimberly");

      polly.setVoice("Justin");
      polly.setVoice("Joey");
      polly.setVoice("Raveena");
      polly.setVoice("Ivy");
      polly.setVoice("Kendra");

      polly.speak("this is a new thing");

      polly.speak("Hello there, i am a cloud service .. i probably sound like the echo");
      polly.speak("Here is another sentence");
      polly.speak("To be or not to be that is the question");
      polly.speakBlocking("now i am blocking my speech");
      polly.speakBlocking("put one foot in front of the other and"); // xxx
      polly.speakBlocking("soon you'll be walking out the door");
      polly.speak("this is a new sentence");
      polly.speak("to be or not to be that is the question");
      polly.speak("weather tis nobler in the mind to suffer");
      polly.speak("the slings and arrows of ourtrageous fortune");
      polly.speak("or to take arms against a see of troubles");

      log.info("finished");
    } catch (Exception e) {
      log.error("main threw", e);
    }
  }

  @Override
  public void releaseService() {
    super.releaseService();
    if (polly != null) {
      polly.shutdown();
    }
  }

  @Override
  public boolean isReady() {
    setReady(polly != null ? true : false);
    return ready;
  }

  // @Override
  // public ServiceConfig getConfig() {
  // PollyConfig config = (PollyConfig) super.getConfig();
  // return config;
  // }

}


text:
const ProvinceCard = require('../../../build/server/game/provincecard.js');

describe('ProvinceCard', function () {
    beforeEach(function () {
        this.testCard = { code: '111', label: 'test 1(some pack)', name: 'test 1' };
        this.gameSpy = jasmine.createSpyObj('game', ['emitEvent', 'on']);
        this.card = new ProvinceCard({ game: this.gameSpy }, this.testCard);
        this.card.type = 'province';
    });

    describe('moveTo()', function() {
        it('should set the location', function() {
            this.card.moveTo('stronghold province');
            expect(this.card.location).toBe('stronghold province');
        });

        describe('when the card is facedown', function() {
            beforeEach(function() {
                this.card.facedown = true;
            });

            describe('when moved to a province', function() {
                beforeEach(function() {
                    this.card.moveTo('province 1');
                });

                it('should not flip the card', function() {
                    expect(this.card.facedown).toBe(true);
                });
            });
        });

        describe('when the card has a reaction', function() {
            beforeEach(function() {
                this.card.reaction({
                    title: 'Force opponent to discard cards equal to the number of attackers',
                    when: {
                        onProvinceRevealed: event => event.card === this && this.controller.opponent.hand.size() > 0
                    },
                    handler: () => {
                        this.game.doSomething();
                    }
                });
                spyOn(this.card.abilities.reactions[0], 'registerEvents');
                spyOn(this.card.abilities.reactions[0], 'unregisterEvents');
            });

            describe('when in a non-event handling area', function() {
                beforeEach(function() {
                    this.card.location = 'province deck';
                });

                describe('and moving to an event handling area', function() {
                    beforeEach(function() {
                        this.card.moveTo('stronghold province');
                    });

                    it('should register events', function() {
                        expect(this.card.abilities.reactions[0].registerEvents).toHaveBeenCalled();
                    });

                    it('should not unregister events', function() {
                        expect(this.card.abilities.reactions[0].unregisterEvents).not.toHaveBeenCalled();
                    });
                });
            });

            describe('when in an event handling area', function() {
                beforeEach(function() {
                    this.card.location = 'province 1';
                });

                describe('and moving to another event handling area', function() {
                    beforeEach(function() {
                        this.card.moveTo('province 2');
                    });

                    it('should not register events', function() {
                        expect(this.card.abilities.reactions[0].registerEvents).not.toHaveBeenCalled();
                    });

                    it('should not unregister events', function() {
                        expect(this.card.abilities.reactions[0].unregisterEvents).not.toHaveBeenCalled();
                    });
                });

                describe('and moving to a non-event handling area', function() {
                    beforeEach(function() {
                        this.card.moveTo('province deck');
                    });

                    it('should not register events', function() {
                        expect(this.card.abilities.reactions[0].registerEvents).not.toHaveBeenCalled();
                    });

                    it('should unregister events', function() {
                        expect(this.card.abilities.reactions[0].unregisterEvents).toHaveBeenCalled();
                    });
                });
            });
        });
    });
});


text:
"""The test the Honeywell thermostat module."""
import socket
import unittest
from unittest import mock

import voluptuous as vol
import somecomfort

from homeassistant.const import (
    CONF_USERNAME, CONF_PASSWORD, TEMP_CELSIUS, TEMP_FAHRENHEIT)
import homeassistant.components.climate.honeywell as honeywell

class TestHoneywell(unittest.TestCase):
    """A test class for Honeywell themostats."""

    @mock.patch('somecomfort.SomeComfort')
    @mock.patch('homeassistant.components.climate.'
                'honeywell.HoneywellUSThermostat')
    def test_setup_us(self, mock_ht, mock_sc):
        """Test for the US setup."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_REGION: 'us',
        }
        bad_pass_config = {
            CONF_USERNAME: 'user',
            honeywell.CONF_REGION: 'us',
        }
        bad_region_config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_REGION: 'un',
        }

        with self.assertRaises(vol.Invalid):
            honeywell.PLATFORM_SCHEMA(None)

        with self.assertRaises(vol.Invalid):
            honeywell.PLATFORM_SCHEMA({})

        with self.assertRaises(vol.Invalid):
            honeywell.PLATFORM_SCHEMA(bad_pass_config)

        with self.assertRaises(vol.Invalid):
            honeywell.PLATFORM_SCHEMA(bad_region_config)

        hass = mock.MagicMock()
        add_devices = mock.MagicMock()

        locations = [
            mock.MagicMock(),
            mock.MagicMock(),
        ]
        devices_1 = [mock.MagicMock()]
        devices_2 = [mock.MagicMock(), mock.MagicMock]
        mock_sc.return_value.locations_by_id.values.return_value = \
            locations
        locations[0].devices_by_id.values.return_value = devices_1
        locations[1].devices_by_id.values.return_value = devices_2

        result = honeywell.setup_platform(hass, config, add_devices)
        self.assertTrue(result)
        mock_sc.assert_called_once_with('user', 'pass')
        mock_ht.assert_has_calls([
            mock.call(mock_sc.return_value, devices_1[0]),
            mock.call(mock_sc.return_value, devices_2[0]),
            mock.call(mock_sc.return_value, devices_2[1]),
        ])

    @mock.patch('somecomfort.SomeComfort')
    def test_setup_us_failures(self, mock_sc):
        """Test the US setup."""
        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_REGION: 'us',
        }

        mock_sc.side_effect = somecomfort.AuthError
        result = honeywell.setup_platform(hass, config, add_devices)
        self.assertFalse(result)
        self.assertFalse(add_devices.called)

        mock_sc.side_effect = somecomfort.SomeComfortError
        result = honeywell.setup_platform(hass, config, add_devices)
        self.assertFalse(result)
        self.assertFalse(add_devices.called)

    @mock.patch('somecomfort.SomeComfort')
    @mock.patch('homeassistant.components.climate.'
                'honeywell.HoneywellUSThermostat')
    def _test_us_filtered_devices(self, mock_ht, mock_sc, loc=None, dev=None):
        """Test for US filtered thermostats."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_REGION: 'us',
            'location': loc,
            'thermostat': dev,
        }
        locations = {
            1: mock.MagicMock(locationid=mock.sentinel.loc1,
                              devices_by_id={
                                  11: mock.MagicMock(
                                      deviceid=mock.sentinel.loc1dev1),
                                  12: mock.MagicMock(
                                      deviceid=mock.sentinel.loc1dev2),
                              }),
            2: mock.MagicMock(locationid=mock.sentinel.loc2,
                              devices_by_id={
                                  21: mock.MagicMock(
                                      deviceid=mock.sentinel.loc2dev1),
                              }),
            3: mock.MagicMock(locationid=mock.sentinel.loc3,
                              devices_by_id={
                                  31: mock.MagicMock(
                                      deviceid=mock.sentinel.loc3dev1),
                              }),
        }
        mock_sc.return_value = mock.MagicMock(locations_by_id=locations)
        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        self.assertEqual(True,
                         honeywell.setup_platform(hass, config, add_devices))

        return mock_ht.call_args_list, mock_sc

    def test_us_filtered_thermostat_1(self):
        """Test for US filtered thermostats."""
        result, client = self._test_us_filtered_devices(
            dev=mock.sentinel.loc1dev1)
        devices = [x[0][1].deviceid for x in result]
        self.assertEqual([mock.sentinel.loc1dev1], devices)

    def test_us_filtered_thermostat_2(self):
        """Test for US filtered location."""
        result, client = self._test_us_filtered_devices(
            dev=mock.sentinel.loc2dev1)
        devices = [x[0][1].deviceid for x in result]
        self.assertEqual([mock.sentinel.loc2dev1], devices)

    def test_us_filtered_location_1(self):
        """Test for US filtered locations."""
        result, client = self._test_us_filtered_devices(
            loc=mock.sentinel.loc1)
        devices = [x[0][1].deviceid for x in result]
        self.assertEqual([mock.sentinel.loc1dev1,
                          mock.sentinel.loc1dev2], devices)

    def test_us_filtered_location_2(self):
        """Test for US filtered locations."""
        result, client = self._test_us_filtered_devices(
            loc=mock.sentinel.loc2)
        devices = [x[0][1].deviceid for x in result]
        self.assertEqual([mock.sentinel.loc2dev1], devices)

    @mock.patch('evohomeclient.EvohomeClient')
    @mock.patch('homeassistant.components.climate.honeywell.'
                'RoundThermostat')
    def test_eu_setup_full_config(self, mock_round, mock_evo):
        """Test the EU setup with complete configuration."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_AWAY_TEMPERATURE: 20.0,
            honeywell.CONF_REGION: 'eu',
        }
        mock_evo.return_value.temperatures.return_value = [
            {'id': 'foo'}, {'id': 'bar'}]
        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        self.assertTrue(honeywell.setup_platform(hass, config, add_devices))
        mock_evo.assert_called_once_with('user', 'pass')
        mock_evo.return_value.temperatures.assert_called_once_with(
            force_refresh=True)
        mock_round.assert_has_calls([
            mock.call(mock_evo.return_value, 'foo', True, 20.0),
            mock.call(mock_evo.return_value, 'bar', False, 20.0),
        ])
        self.assertEqual(2, add_devices.call_count)

    @mock.patch('evohomeclient.EvohomeClient')
    @mock.patch('homeassistant.components.climate.honeywell.'
                'RoundThermostat')
    def test_eu_setup_partial_config(self, mock_round, mock_evo):
        """Test the EU setup with partial configuration."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_REGION: 'eu',
        }

        mock_evo.return_value.temperatures.return_value = [
            {'id': 'foo'}, {'id': 'bar'}]
        config[honeywell.CONF_AWAY_TEMPERATURE] = \
            honeywell.DEFAULT_AWAY_TEMPERATURE

        hass = mock.MagicMock()
        add_devices = mock.MagicMock()
        self.assertTrue(honeywell.setup_platform(hass, config, add_devices))
        mock_round.assert_has_calls([
            mock.call(mock_evo.return_value, 'foo', True, 16),
            mock.call(mock_evo.return_value, 'bar', False, 16),
        ])

    @mock.patch('evohomeclient.EvohomeClient')
    @mock.patch('homeassistant.components.climate.honeywell.'
                'RoundThermostat')
    def test_eu_setup_bad_temp(self, mock_round, mock_evo):
        """Test the EU setup with invalid temperature."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_AWAY_TEMPERATURE: 'ponies',
            honeywell.CONF_REGION: 'eu',
        }

        with self.assertRaises(vol.Invalid):
            honeywell.PLATFORM_SCHEMA(config)

    @mock.patch('evohomeclient.EvohomeClient')
    @mock.patch('homeassistant.components.climate.honeywell.'
                'RoundThermostat')
    def test_eu_setup_error(self, mock_round, mock_evo):
        """Test the EU setup with errors."""
        config = {
            CONF_USERNAME: 'user',
            CONF_PASSWORD: 'pass',
            honeywell.CONF_AWAY_TEMPERATURE: 20,
            honeywell.CONF_REGION: 'eu',
        }
        mock_evo.return_value.temperatures.side_effect = socket.error
        add_devices = mock.MagicMock()
        hass = mock.MagicMock()
        self.assertFalse(honeywell.setup_platform(hass, config, add_devices))

class TestHoneywellRound(unittest.TestCase):
    """A test class for Honeywell Round thermostats."""

    def setup_method(self, method):
        """Test the setup method."""
        def fake_temperatures(force_refresh=None):
            """Create fake temperatures."""
            temps = [
                {'id': '1', 'temp': 20, 'setpoint': 21,
                 'thermostat': 'main', 'name': 'House'},
                {'id': '2', 'temp': 21, 'setpoint': 22,
                 'thermostat': 'DOMESTIC_HOT_WATER'},
            ]
            return temps

        self.device = mock.MagicMock()
        self.device.temperatures.side_effect = fake_temperatures
        self.round1 = honeywell.RoundThermostat(self.device, '1',
                                                True, 16)
        self.round2 = honeywell.RoundThermostat(self.device, '2',
                                                False, 17)

    def test_attributes(self):
        """Test the attributes."""
        self.assertEqual('House', self.round1.name)
        self.assertEqual(TEMP_CELSIUS, self.round1.temperature_unit)
        self.assertEqual(20, self.round1.current_temperature)
        self.assertEqual(21, self.round1.target_temperature)
        self.assertFalse(self.round1.is_away_mode_on)

        self.assertEqual('Hot Water', self.round2.name)
        self.assertEqual(TEMP_CELSIUS, self.round2.temperature_unit)
        self.assertEqual(21, self.round2.current_temperature)
        self.assertEqual(None, self.round2.target_temperature)
        self.assertFalse(self.round2.is_away_mode_on)

    def test_away_mode(self):
        """Test setting the away mode."""
        self.assertFalse(self.round1.is_away_mode_on)
        self.round1.turn_away_mode_on()
        self.assertTrue(self.round1.is_away_mode_on)
        self.device.set_temperature.assert_called_once_with('House', 16)

        self.device.set_temperature.reset_mock()
        self.round1.turn_away_mode_off()
        self.assertFalse(self.round1.is_away_mode_on)
        self.device.cancel_temp_override.assert_called_once_with('House')

    def test_set_temperature(self):
        """Test setting the temperature."""
        self.round1.set_temperature(temperature=25)
        self.device.set_temperature.assert_called_once_with('House', 25)

    def test_set_operation_mode(self: unittest.TestCase) -> None:
        """Test setting the system operation."""
        self.round1.set_operation_mode('cool')
        self.assertEqual('cool', self.round1.current_operation)
        self.assertEqual('cool', self.device.system_mode)

        self.round1.set_operation_mode('heat')
        self.assertEqual('heat', self.round1.current_operation)
        self.assertEqual('heat', self.device.system_mode)

class TestHoneywellUS(unittest.TestCase):
    """A test class for Honeywell US thermostats."""

    def setup_method(self, method):
        """Test the setup method."""
        self.client = mock.MagicMock()
        self.device = mock.MagicMock()
        self.honeywell = honeywell.HoneywellUSThermostat(
            self.client, self.device)

        self.device.fan_running = True
        self.device.name = 'test'
        self.device.temperature_unit = 'F'
        self.device.current_temperature = 72
        self.device.setpoint_cool = 78
        self.device.setpoint_heat = 65
        self.device.system_mode = 'heat'
        self.device.fan_mode = 'auto'

    def test_properties(self):
        """Test the properties."""
        self.assertTrue(self.honeywell.is_fan_on)
        self.assertEqual('test', self.honeywell.name)
        self.assertEqual(72, self.honeywell.current_temperature)

    def test_unit_of_measurement(self):
        """Test the unit of measurement."""
        self.assertEqual(TEMP_FAHRENHEIT, self.honeywell.temperature_unit)
        self.device.temperature_unit = 'C'
        self.assertEqual(TEMP_CELSIUS, self.honeywell.temperature_unit)

    def test_target_temp(self):
        """Test the target temperature."""
        self.assertEqual(65, self.honeywell.target_temperature)
        self.device.system_mode = 'cool'
        self.assertEqual(78, self.honeywell.target_temperature)

    def test_set_temp(self):
        """Test setting the temperature."""
        self.honeywell.set_temperature(temperature=70)
        self.assertEqual(70, self.device.setpoint_heat)
        self.assertEqual(70, self.honeywell.target_temperature)

        self.device.system_mode = 'cool'
        self.assertEqual(78, self.honeywell.target_temperature)
        self.honeywell.set_temperature(temperature=74)
        self.assertEqual(74, self.device.setpoint_cool)
        self.assertEqual(74, self.honeywell.target_temperature)

    def test_set_operation_mode(self: unittest.TestCase) -> None:
        """Test setting the operation mode."""
        self.honeywell.set_operation_mode('cool')
        self.assertEqual('cool', self.honeywell.current_operation)
        self.assertEqual('cool', self.device.system_mode)

        self.honeywell.set_operation_mode('heat')
        self.assertEqual('heat', self.honeywell.current_operation)
        self.assertEqual('heat', self.device.system_mode)

    def test_set_temp_fail(self):
        """Test if setting the temperature fails."""
        self.device.setpoint_heat = mock.MagicMock(
            side_effect=somecomfort.SomeComfortError)
        self.honeywell.set_temperature(temperature=123)

    def test_attributes(self):
        """Test the attributes."""
        expected = {
            honeywell.ATTR_FAN: 'running',
            honeywell.ATTR_FANMODE: 'auto',
            honeywell.ATTR_SYSTEM_MODE: 'heat',
        }
        self.assertEqual(expected, self.honeywell.device_state_attributes)
        expected['fan'] = 'idle'
        self.device.fan_running = False
        self.assertEqual(expected, self.honeywell.device_state_attributes)

    def test_with_no_fan(self):
        """Test if there is on fan."""
        self.device.fan_running = False
        self.device.fan_mode = None
        expected = {
            honeywell.ATTR_FAN: 'idle',
            honeywell.ATTR_FANMODE: None,
            honeywell.ATTR_SYSTEM_MODE: 'heat',
        }
        self.assertEqual(expected, self.honeywell.device_state_attributes)


text:
import agglomerate
import json

class SimpleJSON(agglomerate.Format):
    """
    A simple JSON output
    """
    supports = {
                "rotation": True,
                "cropping": False,
               }
    suggested_extension = "json"

    def generate(self, sprites, settings):
        # list (array) of sprites that will be converted to json
        sprite_array = []

        for s in sprites:
            # dict (object) that represents a sprite
            sprite_object = {
                "name": s.name,
                "x": s.position.x,
                "y": s.position.y,
                "w": s.size.x,
                "h": s.size.y,
                "rotated": s.rotated
            }
            sprite_array.append(sprite_object)

        # Dump the array into a json string, indented by 4 spaces
        return json.dumps(sprite_array, indent=4)

format_class = SimpleJSON


text:
package com.drumonii.loltrollbuild.api.service;

import com.drumonii.loltrollbuild.model.Champion;
import com.drumonii.loltrollbuild.repository.ChampionsRepository;
import com.drumonii.loltrollbuild.repository.specification.ExampleSpecification;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Sort;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class ChampionsApiServiceTest {

    @InjectMocks
    private ChampionsApiService apiService = new ChampionsApiServiceImpl();

    @Mock
    private ChampionsRepository championsRepository;

    @Nested
    @DisplayName("query by example")
    class Qbe {

        @Test
        void qbe() {
            ExampleSpecification<Champion> specification = mock(ExampleSpecification.class);
            Sort sort = mock(Sort.class);

            apiService.qbe(specification, sort);

            verify(championsRepository, times(1)).findAll(eq(specification), eq(sort));
        }

    }

    @Nested
    @DisplayName("find by id")
    class FindById {

        @Test
        void findsById() {
            apiService.find("48162");

            verify(championsRepository, times(1)).findById(eq(48162));
        }

    }

    @Nested
    @DisplayName("find by name")
    class FindByName {

        @Test
        void findsByName() {
            apiService.find("name");

            verify(championsRepository, times(1)).findByName(eq("name"));
        }

    }

    @Nested
    @DisplayName("get tags")
    class GetTags {

        @Test
        void getsTags() {
            apiService.getTags();

            verify(championsRepository, times(1)).getTags();
        }

    }

}


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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.mybatis.generator.config.*;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.ObjectFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

/**
 * This class parses configuration files into the new Configuration API
 *
 * @author Jeff Butler
 */
public class MyBatisGeneratorConfigurationParser {
    private Properties properties;

    public MyBatisGeneratorConfigurationParser(Properties properties) {
        super();
        if (properties == null) {
            this.properties = System.getProperties();
        } else {
            this.properties = properties;
        }
    }

    public Configuration parseConfiguration(Element rootNode)
            throws XMLParserException {

        Configuration configuration = new Configuration();

        NodeList nodeList = rootNode.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("properties".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperties(configuration, childNode);
            } else if ("classPathEntry".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseClassPathEntry(configuration, childNode);
            } else if ("context".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseContext(configuration, childNode);
            }
        }

        return configuration;
    }

    private void parseProperties(Configuration configuration, Node node)
            throws XMLParserException {
        Properties attributes = parseAttributes(node);
        String resource = attributes.getProperty("resource"); //$NON-NLS-1$
        String url = attributes.getProperty("url"); //$NON-NLS-1$

        if (!stringHasValue(resource)
                && !stringHasValue(url)) {
            throw new XMLParserException(getString("RuntimeError.14")); //$NON-NLS-1$
        }

        if (stringHasValue(resource)
                && stringHasValue(url)) {
            throw new XMLParserException(getString("RuntimeError.14")); //$NON-NLS-1$
        }

        URL resourceUrl;

        try {
            if (stringHasValue(resource)) {
                resourceUrl = ObjectFactory.getResource(resource);
                if (resourceUrl == null) {
                    throw new XMLParserException(getString(
                            "RuntimeError.15", resource)); //$NON-NLS-1$
                }
            } else {
                resourceUrl = new URL(url);
            }

            InputStream inputStream = resourceUrl.openConnection()
                    .getInputStream();

            properties.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            if (stringHasValue(resource)) {
                throw new XMLParserException(getString(
                        "RuntimeError.16", resource)); //$NON-NLS-1$
            } else {
                throw new XMLParserException(getString(
                        "RuntimeError.17", url)); //$NON-NLS-1$
            }
        }
    }

    private void parseContext(Configuration configuration, Node node) {

        Properties attributes = parseAttributes(node);
        String defaultModelType = attributes.getProperty("defaultModelType"); //$NON-NLS-1$
        String targetRuntime = attributes.getProperty("targetRuntime"); //$NON-NLS-1$
        String introspectedColumnImpl = attributes
                .getProperty("introspectedColumnImpl"); //$NON-NLS-1$
        String id = attributes.getProperty("id"); //$NON-NLS-1$

        ModelType mt = defaultModelType == null ? null : ModelType
                .getModelType(defaultModelType);

        Context context = new Context(mt);
        context.setId(id);
        if (stringHasValue(introspectedColumnImpl)) {
            context.setIntrospectedColumnImpl(introspectedColumnImpl);
        }
        if (stringHasValue(targetRuntime)) {
            context.setTargetRuntime(targetRuntime);
        }

        configuration.addContext(context);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(context, childNode);
            } else if ("plugin".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parsePlugin(context, childNode);
            } else if ("commentGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseCommentGenerator(context, childNode);
            } else if ("jdbcConnection".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseJdbcConnection(context, childNode);
            } else if ("javaModelGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseJavaModelGenerator(context, childNode);
            } else if ("javaTypeResolver".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseJavaTypeResolver(context, childNode);
            } else if ("sqlMapGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseSqlMapGenerator(context, childNode);
            } else if ("javaClientGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseJavaClientGenerator(context, childNode);
            } else if ("table".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseTable(context, childNode);
            }
        }
    }

    private void parseSqlMapGenerator(Context context, Node node) {
        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();

        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

        Properties attributes = parseAttributes(node);
        String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
        String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$

        sqlMapGeneratorConfiguration.setTargetPackage(targetPackage);
        sqlMapGeneratorConfiguration.setTargetProject(targetProject);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(sqlMapGeneratorConfiguration, childNode);
            }
        }
    }

    private void parseTable(Context context, Node node) {
        TableConfiguration tc = new TableConfiguration(context);
        context.addTableConfiguration(tc);

        Properties attributes = parseAttributes(node);
        String catalog = attributes.getProperty("catalog"); //$NON-NLS-1$
        String schema = attributes.getProperty("schema"); //$NON-NLS-1$
        String tableName = attributes.getProperty("tableName"); //$NON-NLS-1$
        String domainObjectName = attributes.getProperty("domainObjectName"); //$NON-NLS-1$
		String daoSuffix=attributes.getProperty("daoSuffix");
		String dmoSuffix=attributes.getProperty("dmoSuffix");
        String alias = attributes.getProperty("alias"); //$NON-NLS-1$
        String enableInsert = attributes.getProperty("enableInsert"); //$NON-NLS-1$
        String enableSelectByPrimaryKey = attributes
                .getProperty("enableSelectByPrimaryKey"); //$NON-NLS-1$
        String enableSelectByExample = attributes
                .getProperty("enableSelectByExample"); //$NON-NLS-1$
        String enableUpdateByPrimaryKey = attributes
                .getProperty("enableUpdateByPrimaryKey"); //$NON-NLS-1$
        String enableDeleteByPrimaryKey = attributes
                .getProperty("enableDeleteByPrimaryKey"); //$NON-NLS-1$
        String enableDeleteByExample = attributes
                .getProperty("enableDeleteByExample"); //$NON-NLS-1$
        String enableCountByExample = attributes
                .getProperty("enableCountByExample"); //$NON-NLS-1$
        String enableUpdateByExample = attributes
                .getProperty("enableUpdateByExample"); //$NON-NLS-1$
        String selectByPrimaryKeyQueryId = attributes
                .getProperty("selectByPrimaryKeyQueryId"); //$NON-NLS-1$
        String selectByExampleQueryId = attributes
                .getProperty("selectByExampleQueryId"); //$NON-NLS-1$
        String modelType = attributes.getProperty("modelType"); //$NON-NLS-1$
        String escapeWildcards = attributes.getProperty("escapeWildcards"); //$NON-NLS-1$
        String delimitIdentifiers = attributes
                .getProperty("delimitIdentifiers"); //$NON-NLS-1$
        String delimitAllColumns = attributes.getProperty("delimitAllColumns"); //$NON-NLS-1$

        if (stringHasValue(catalog)) {
            tc.setCatalog(catalog);
        }

        if (stringHasValue(schema)) {
            tc.setSchema(schema);
        }

        if (stringHasValue(tableName)) {
            tc.setTableName(tableName);
        }

        if (stringHasValue(domainObjectName)) {
            tc.setDomainObjectName(domainObjectName);
        }

		if(stringHasValue(dmoSuffix)){
			tc.setDmoSuffix(dmoSuffix);
		}

		if(stringHasValue(daoSuffix)){
			tc.setDaoSuffix(daoSuffix);
		}

        if (stringHasValue(alias)) {
            tc.setAlias(alias);
        }

        if (stringHasValue(enableInsert)) {
            tc.setInsertStatementEnabled(isTrue(enableInsert));
        }

        if (stringHasValue(enableSelectByPrimaryKey)) {
            tc.setSelectByPrimaryKeyStatementEnabled(
                    isTrue(enableSelectByPrimaryKey));
        }

        if (stringHasValue(enableSelectByExample)) {
            tc.setSelectByExampleStatementEnabled(
                    isTrue(enableSelectByExample));
        }

        if (stringHasValue(enableUpdateByPrimaryKey)) {
            tc.setUpdateByPrimaryKeyStatementEnabled(
                    isTrue(enableUpdateByPrimaryKey));
        }

        if (stringHasValue(enableDeleteByPrimaryKey)) {
            tc.setDeleteByPrimaryKeyStatementEnabled(
                    isTrue(enableDeleteByPrimaryKey));
        }

        if (stringHasValue(enableDeleteByExample)) {
            tc.setDeleteByExampleStatementEnabled(
                    isTrue(enableDeleteByExample));
        }

        if (stringHasValue(enableCountByExample)) {
            tc.setCountByExampleStatementEnabled(
                    isTrue(enableCountByExample));
        }

        if (stringHasValue(enableUpdateByExample)) {
            tc.setUpdateByExampleStatementEnabled(
                    isTrue(enableUpdateByExample));
        }

        if (stringHasValue(selectByPrimaryKeyQueryId)) {
            tc.setSelectByPrimaryKeyQueryId(selectByPrimaryKeyQueryId);
        }

        if (stringHasValue(selectByExampleQueryId)) {
            tc.setSelectByExampleQueryId(selectByExampleQueryId);
        }

        if (stringHasValue(modelType)) {
            tc.setConfiguredModelType(modelType);
        }

        if (stringHasValue(escapeWildcards)) {
            tc.setWildcardEscapingEnabled(isTrue(escapeWildcards));
        }

        if (stringHasValue(delimitIdentifiers)) {
            tc.setDelimitIdentifiers(isTrue(delimitIdentifiers));
        }

        if (stringHasValue(delimitAllColumns)) {
            tc.setAllColumnDelimitingEnabled(isTrue(delimitAllColumns));
        }

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(tc, childNode);
            } else if ("columnOverride".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseColumnOverride(tc, childNode);
            } else if ("ignoreColumn".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseIgnoreColumn(tc, childNode);
            } else if ("generatedKey".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseGeneratedKey(tc, childNode);
            } else if ("columnRenamingRule".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseColumnRenamingRule(tc, childNode);
            } else if ("selectSql".equals(childNode.getNodeName())) { // generator sql
				parseSelectSql(tc,childNode);
			}
		}
    }

	private void parseSelectSql(TableConfiguration tc, Node node) {
		Properties attributes = parseAttributes(node);

		String name = attributes.getProperty("name");
		String sql = attributes.getProperty("sql"); //$NON-NLS-1$
		String returnType = attributes.getProperty("returnType"); //$NON-NLS-1$

		SelectSql selectSql = new SelectSql(name, sql, returnType);

		tc.addSelectSql(selectSql);
	}

	private void parseColumnOverride(TableConfiguration tc, Node node) {
        Properties attributes = parseAttributes(node);
        String column = attributes.getProperty("column"); //$NON-NLS-1$
        String property = attributes.getProperty("property"); //$NON-NLS-1$
        String javaType = attributes.getProperty("javaType"); //$NON-NLS-1$
        String jdbcType = attributes.getProperty("jdbcType"); //$NON-NLS-1$
        String typeHandler = attributes.getProperty("typeHandler"); //$NON-NLS-1$
        String delimitedColumnName = attributes
                .getProperty("delimitedColumnName"); //$NON-NLS-1$

        ColumnOverride co = new ColumnOverride(column);

        if (stringHasValue(property)) {
            co.setJavaProperty(property);
        }

        if (stringHasValue(javaType)) {
            co.setJavaType(javaType);
        }

        if (stringHasValue(jdbcType)) {
            co.setJdbcType(jdbcType);
        }

        if (stringHasValue(typeHandler)) {
            co.setTypeHandler(typeHandler);
        }

        if (stringHasValue(delimitedColumnName)) {
            co.setColumnNameDelimited(isTrue(delimitedColumnName));
        }

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(co, childNode);
            }
        }

        tc.addColumnOverride(co);
    }

    private void parseGeneratedKey(TableConfiguration tc, Node node) {
        Properties attributes = parseAttributes(node);

        String column = attributes.getProperty("column"); //$NON-NLS-1$
        boolean identity = isTrue(attributes
                .getProperty("identity")); //$NON-NLS-1$
        String sqlStatement = attributes.getProperty("sqlStatement"); //$NON-NLS-1$
        String type = attributes.getProperty("type"); //$NON-NLS-1$

        GeneratedKey gk = new GeneratedKey(column, sqlStatement, identity, type);

        tc.setGeneratedKey(gk);
    }

    private void parseIgnoreColumn(TableConfiguration tc, Node node) {
        Properties attributes = parseAttributes(node);
        String column = attributes.getProperty("column"); //$NON-NLS-1$
        String delimitedColumnName = attributes
                .getProperty("delimitedColumnName"); //$NON-NLS-1$

        IgnoredColumn ic = new IgnoredColumn(column);

        if (stringHasValue(delimitedColumnName)) {
            ic.setColumnNameDelimited(isTrue(delimitedColumnName));
        }

        tc.addIgnoredColumn(ic);
    }

    private void parseColumnRenamingRule(TableConfiguration tc, Node node) {
        Properties attributes = parseAttributes(node);
        String searchString = attributes.getProperty("searchString"); //$NON-NLS-1$
        String replaceString = attributes.getProperty("replaceString"); //$NON-NLS-1$

        ColumnRenamingRule crr = new ColumnRenamingRule();

        crr.setSearchString(searchString);

        if (stringHasValue(replaceString)) {
            crr.setReplaceString(replaceString);
        }

        tc.setColumnRenamingRule(crr);
    }

    private void parseJavaTypeResolver(Context context, Node node) {
        JavaTypeResolverConfiguration javaTypeResolverConfiguration = new JavaTypeResolverConfiguration();

        context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration);

        Properties attributes = parseAttributes(node);
        String type = attributes.getProperty("type"); //$NON-NLS-1$

        if (stringHasValue(type)) {
            javaTypeResolverConfiguration.setConfigurationType(type);
        }

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(javaTypeResolverConfiguration, childNode);
            }
        }
    }

    private void parsePlugin(Context context, Node node) {
        PluginConfiguration pluginConfiguration = new PluginConfiguration();

        context.addPluginConfiguration(pluginConfiguration);

        Properties attributes = parseAttributes(node);
        String type = attributes.getProperty("type"); //$NON-NLS-1$

        pluginConfiguration.setConfigurationType(type);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(pluginConfiguration, childNode);
            }
        }
    }

    private void parseJavaModelGenerator(Context context, Node node) {
        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();

        context
                .setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

        Properties attributes = parseAttributes(node);
        String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
        String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$

        javaModelGeneratorConfiguration.setTargetPackage(targetPackage);
        javaModelGeneratorConfiguration.setTargetProject(targetProject);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(javaModelGeneratorConfiguration, childNode);
            }
        }
    }

    private void parseJavaClientGenerator(Context context, Node node) {
        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();

        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

        Properties attributes = parseAttributes(node);
        String type = attributes.getProperty("type"); //$NON-NLS-1$
        String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
        String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$
        String implementationPackage = attributes
                .getProperty("implementationPackage"); //$NON-NLS-1$

        javaClientGeneratorConfiguration.setConfigurationType(type);
        javaClientGeneratorConfiguration.setTargetPackage(targetPackage);
        javaClientGeneratorConfiguration.setTargetProject(targetProject);
        javaClientGeneratorConfiguration
                .setImplementationPackage(implementationPackage);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(javaClientGeneratorConfiguration, childNode);
            }
        }
    }

    private void parseJdbcConnection(Context context, Node node) {
        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();

        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

        Properties attributes = parseAttributes(node);
        String driverClass = attributes.getProperty("driverClass"); //$NON-NLS-1$
        String connectionURL = attributes.getProperty("connectionURL"); //$NON-NLS-1$
        String userId = attributes.getProperty("userId"); //$NON-NLS-1$
        String password = attributes.getProperty("password"); //$NON-NLS-1$

        jdbcConnectionConfiguration.setDriverClass(driverClass);
        jdbcConnectionConfiguration.setConnectionURL(connectionURL);

        if (stringHasValue(userId)) {
            jdbcConnectionConfiguration.setUserId(userId);
        }

        if (stringHasValue(password)) {
            jdbcConnectionConfiguration.setPassword(password);
        }

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(jdbcConnectionConfiguration, childNode);
            }
        }
    }

    private void parseClassPathEntry(Configuration configuration, Node node) {
        Properties attributes = parseAttributes(node);

        configuration.addClasspathEntry(attributes.getProperty("location")); //$NON-NLS-1$
    }

    private void parseProperty(PropertyHolder propertyHolder, Node node) {
        Properties attributes = parseAttributes(node);

        String name = attributes.getProperty("name"); //$NON-NLS-1$
        String value = attributes.getProperty("value"); //$NON-NLS-1$

        propertyHolder.addProperty(name, value);
    }

    private Properties parseAttributes(Node node) {
        Properties attributes = new Properties();
        NamedNodeMap nnm = node.getAttributes();
        for (int i = 0; i < nnm.getLength(); i++) {
            Node attribute = nnm.item(i);
            String value = parsePropertyTokens(attribute.getNodeValue());
            attributes.put(attribute.getNodeName(), value);
        }

        return attributes;
    }

    private String parsePropertyTokens(String string) {
        final String OPEN = "${"; //$NON-NLS-1$
        final String CLOSE = "}"; //$NON-NLS-1$

        String newString = string;
        if (newString != null) {
            int start = newString.indexOf(OPEN);
            int end = newString.indexOf(CLOSE);

            while (start > -1 && end > start) {
                String prepend = newString.substring(0, start);
                String append = newString.substring(end + CLOSE.length());
                String propName = newString.substring(start + OPEN.length(),
                        end);
                String propValue = properties.getProperty(propName);
                if (propValue != null) {
                    newString = prepend + propValue + append;
                }

                start = newString.indexOf(OPEN, end);
                end = newString.indexOf(CLOSE, end);
            }
        }

        return newString;
    }

    private void parseCommentGenerator(Context context, Node node) {
        CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();

        context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);

        Properties attributes = parseAttributes(node);
        String type = attributes.getProperty("type"); //$NON-NLS-1$

        if (stringHasValue(type)) {
            commentGeneratorConfiguration.setConfigurationType(type);
        }

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(commentGeneratorConfiguration, childNode);
            }
        }
    }
}


text:
Smart PhonesUp To 15% Discount

Top 10 LatestMobile & Accessories

Showing Results: 0-1

		<?php include 'page/list/sorting.php'; ?>

Smart Phone

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Smart Phone" />
						<input type="hidden" name="amount" value="245.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

New

Audio-speaker

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Audio-speaker" />
						<input type="hidden" name="amount" value="45.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

Red Mobile

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Red Mobile" />
						<input type="hidden" name="amount" value="65.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

Headphone

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Headphone"/>
						<input type="hidden" name="amount" value="245.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

Wireless Speaker

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Wireless Speaker" />
						<input type="hidden" name="amount" value="86.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

Asus Tablet

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Asus Tablet" />
						<input type="hidden" name="amount" value="425.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

New

Music MP3 Player

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Ultra MP3 Player" />
						<input type="hidden" name="amount" value="58.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

New

Golden Tablet

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Golden Tablet" />
						<input type="hidden" name="amount" value="550.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>

Wireless Phone

					<form action="#" method="post">
						<input type="hidden" name="cmd" value="_cart" />
						<input type="hidden" name="add" value="1" />
						<input type="hidden" name="w3ls_item" value="Wireless Phone" />
						<input type="hidden" name="amount" value="210.00"/>
						<button type="submit" class="w3ls-cart">Nhận báo giá</button>
					</form>


text:
package com.vaadin.tests.data.converter;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.vaadin.data.ValueContext;
import com.vaadin.data.converter.StringToFloatConverter;

public class StringToFloatConverterTest extends AbstractStringConverterTest {

    @Override
    protected StringToFloatConverter getConverter() {
        return new StringToFloatConverter(getErrorMessage());
    }

    @Override
    @Test
    public void testNullConversion() {
        assertValue(null,
                getConverter().convertToModel(null, new ValueContext()));
    }

    @Override
    @Test
    public void testEmptyStringConversion() {
        assertValue(null,
                getConverter().convertToModel("", new ValueContext()));
    }

    @Test
    public void testValueConversion() {
        assertValue(Float.valueOf(10),
                getConverter().convertToModel("10", new ValueContext()));
    }

    @Test
    public void customEmptyValue() {
        StringToFloatConverter converter = new StringToFloatConverter(
                (float) 0.0, getErrorMessage());

        assertValue((float) 0.0,
                converter.convertToModel("", new ValueContext()));
        assertEquals("0", converter.convertToPresentation((float) 0.0,
                new ValueContext()));
    }
}