text:
package org.kuali.kpme.tklm.utils;

import org.apache.log4j.Logger;
import org.joda.time.*;
import org.junit.Assert;
import org.kuali.kpme.core.api.assignment.Assignment;
import org.kuali.kpme.core.api.job.Job;
import org.kuali.kpme.core.calendar.entry.CalendarEntryBo;
import org.kuali.kpme.core.service.HrServiceLocator;
import org.kuali.kpme.core.util.HrConstants;
import org.kuali.kpme.core.util.TKUtils;
import org.kuali.kpme.tklm.api.time.timeblock.TimeBlock;
import org.kuali.kpme.tklm.api.time.timeblock.TimeBlockService;
import org.kuali.kpme.tklm.api.time.timehourdetail.TimeHourDetail;
import org.kuali.kpme.tklm.time.flsa.FlsaDay;
import org.kuali.kpme.tklm.time.flsa.FlsaWeek;
import org.kuali.kpme.tklm.time.service.TkServiceLocator;
import org.kuali.kpme.tklm.time.timeblock.TimeBlockBo;
import org.kuali.kpme.tklm.time.timehourdetail.TimeHourDetailBo;
import org.kuali.kpme.tklm.time.timesheet.TimesheetDocument;
import org.kuali.kpme.tklm.time.util.TkTimeBlockAggregate;
import org.kuali.rice.kew.api.exception.WorkflowException;

import java.math.BigDecimal;
import java.util.*;

public class TkTestUtils {

	private static final Logger LOG = Logger.getLogger(TkTestUtils.class);

	public static TimesheetDocument populateBlankTimesheetDocument(DateTime calDate, String principalId) {
		try {
			TimesheetDocument timesheet = TkServiceLocator.getTimesheetService().openTimesheetDocument(principalId,
							 HrServiceLocator.getCalendarEntryService().getCurrentCalendarDates(principalId,
                                    calDate));
			for(TimeBlock timeBlock : timesheet.getTimeBlocks()){
				TkServiceLocator.getTimeBlockService().deleteTimeBlock(timeBlock);
			}

			return timesheet;
		} catch (WorkflowException e) {
			throw new RuntimeException("Problem fetching document");
		}
	}

	public static TimesheetDocument populateTimesheetDocument(DateTime calDate, String principalId) {
		try {
			TimesheetDocument timesheet = TkServiceLocator.getTimesheetService().openTimesheetDocument(principalId,
							 HrServiceLocator.getCalendarEntryService().getCurrentCalendarDates(principalId,
									calDate));
			for(TimeBlock timeBlock : timesheet.getTimeBlocks()){
				TkServiceLocator.getTimeBlockService().deleteTimeBlock(timeBlock);
			}

			//refetch clean document
			timesheet = TkServiceLocator.getTimesheetService().openTimesheetDocument(principalId,
					 HrServiceLocator.getCalendarEntryService().getCurrentCalendarDates(principalId, calDate));
			List<TimeBlock> timeBlocks = new LinkedList<TimeBlock>();
			for(int i = 0;i<5;i++){
				TimeBlock timeBlock = createTimeBlock(timesheet, i+1, 10);
				timeBlocks.add(timeBlock);
				timesheet.setTimeBlocks(timeBlocks);
			}

			//Add a TEX accrual earn code
			TimeBlock timeBlock = createTimeBlock(timesheet, 1, 4,"TEX");
			timeBlocks.add(timeBlock);
			timesheet.setTimeBlocks(timeBlocks);
			return timesheet;

		} catch (WorkflowException e) {
			throw new RuntimeException("Problem fetching document");
		}
	}

	/**
	 * Helper method to create regular time blocks for use in testing.
	 *
	 * @param start
	 * @param days
	 * @param hours
	 * @param earnCode
	 * @param jobNumber
	 * @param workArea
	 * @return
	 */
	public static List<TimeBlock> createUniformTimeBlocks(DateTime start, int days, BigDecimal hours, String earnCode, Long jobNumber, Long workArea) {
		return TkTestUtils.createUniformTimeBlocks(start, days, hours, earnCode, jobNumber, workArea, null, null, null);
	}

	public static List<TimeBlock> createUniformTimeBlocks(DateTime start, int days, BigDecimal hours, String earnCode, Long jobNumber, Long workArea, Long task, String groupKeyCode, String documentId) {
		List<TimeBlock> blocks = new ArrayList<TimeBlock>();

		for (int i=0; i<days; i++) {
			DateTime ci = start.plusDays(i);
			DateTime co = ci.plusHours(hours.intValue());
			TimeBlockBo block = TkTestUtils.createDummyTimeBlock(ci, co, hours, earnCode, jobNumber, workArea);
			block.setTask(task);
            block.setGroupKeyCode(groupKeyCode);
			block.setDocumentId(documentId);
            blocks.add(TimeBlockBo.to(block));

		}

		return blocks;
	}

	public static TimeBlockBo createDummyTimeBlock(DateTime clockIn, DateTime clockOut, BigDecimal hours, String earnCode) {
		return TkTestUtils.createDummyTimeBlock(clockIn, clockOut, hours, earnCode, -1L, -1L);
	}

	public static TimeBlockBo createDummyTimeBlock(DateTime clockIn, DateTime clockOut, BigDecimal hours, String earnCode, Long jobNumber, Long workArea) {
		TimeBlockBo block = new TimeBlockBo();
		block.setBeginDateTime(clockIn);
		block.setEndDateTime(clockOut);
		block.setHours(hours);
        block.setBeginTimeDisplay(clockIn);
        block.setEndTimeDisplay(clockOut);

        block.setEarnCode(earnCode);
		block.setJobNumber(jobNumber);
		block.setWorkArea(workArea);

		TimeHourDetailBo thd = new TimeHourDetailBo();
		thd.setHours(hours);
		thd.setEarnCode(earnCode);
		List<TimeHourDetailBo> timeHourDetails = new ArrayList<TimeHourDetailBo>();
		timeHourDetails.add(thd);
		block.setTimeHourDetails(timeHourDetails);

		return block;
	}

	public static TimeBlock createTimeBlock(TimesheetDocument timesheetDocument, int dayInPeriod, int numHours){
		return createTimeBlock(timesheetDocument, dayInPeriod, numHours,"RGN");
	}
	public static TimeBlock createTimeBlock(TimesheetDocument timesheetDocument, int dayInPeriod, int numHours, String earnCode){
		TimeBlockBo timeBlock = new TimeBlockBo();
		DateTime beginPeriodDateTime = timesheetDocument.getCalendarEntry().getBeginPeriodFullDateTime();
		DateTime beginDateTime = beginPeriodDateTime.plusDays(dayInPeriod).withHourOfDay(8).withMinuteOfHour(0);
		DateTime endDateTime = beginDateTime.plusHours(numHours);

		timeBlock.setDocumentId(timesheetDocument.getDocumentId());
		timeBlock.setBeginDateTime(beginDateTime);
		timeBlock.setBeginTimeDisplay(beginDateTime);
		timeBlock.setEndDateTime(endDateTime);
		timeBlock.setEndTimeDisplay(endDateTime);
		timeBlock.setEarnCode(earnCode);
        timeBlock.setGroupKeyCode("IU-BL");
		timeBlock.setJobNumber(1L);
		timeBlock.setWorkArea(1234L);
		timeBlock.setTask(1L);
		timeBlock.setHours((new BigDecimal(numHours)).setScale(HrConstants.BIG_DECIMAL_SCALE, HrConstants.BIG_DECIMAL_SCALE_ROUNDING));

		return TimeBlockBo.to(timeBlock);
	}

	public static List<Job> getJobs(LocalDate calDate, String principalId){
		return HrServiceLocator.getJobService().getJobs(principalId, calDate);
	}

	@SuppressWarnings("serial")
	public static void verifyAggregateHourSumsFlatList(String msg, final Map<String,BigDecimal> ecToHoursMap, TkTimeBlockAggregate aggregate) {
		// Initializes sum map to zeros, since we only care about the entires
		// that were passed in.
		Map<String,BigDecimal> ecToSumMap = new HashMap<String,BigDecimal>() {{ for (String ec : ecToHoursMap.keySet()) { put(ec, BigDecimal.ZERO); }}};

		for (TimeBlock bl : aggregate.getFlattenedTimeBlockList()) {
			for (TimeHourDetail thd : bl.getTimeHourDetails()) {
				if (ecToSumMap.containsKey(thd.getEarnCode())) {
					ecToSumMap.put(thd.getEarnCode(), ecToSumMap.get(thd.getEarnCode()).add(thd.getHours()));
                }
            }
        }

		// Assert that our values are correct.
		for (String key : ecToHoursMap.keySet()) {
			Assert.assertEquals(
					msg + " >> ("+key+") Wrong number of hours expected: " + ecToHoursMap.get(key) + " found: " + ecToSumMap.get(key) + " :: ",
					0,
					ecToHoursMap.get(key).compareTo(ecToSumMap.get(key)));
        }
	}

	/**
	 * Helper method to verify that the aggregate contains the correct sums as
	 * indicated in the ecToHoursMapping, on a SINGLE given flsaWeek.
	 *
	 * Warning! Contains Assertions, use only with Test Cases.
	 *
	 * @param ecToHoursMap ex: { 'REG' => 40, 'OVT' => 10 }
	 * @param aggregate An aggregate object containing the time blocks
	 * @param flsaWeek 0 indexed start week (pulling from aggregate)
	 */
	@SuppressWarnings("serial")
	public static void verifyAggregateHourSums(String principalId, String msg, final Map<String,BigDecimal> ecToHoursMap, TkTimeBlockAggregate aggregate, int flsaWeek) {
		// Initializes sum map to zeros, since we only care about the entires
		// that were passed in.
		Map<String,BigDecimal> ecToSumMap = new HashMap<String,BigDecimal>() {{ for (String ec : ecToHoursMap.keySet()) { put(ec, BigDecimal.ZERO); }}};

		List<FlsaWeek> flsaWeeks = aggregate.getFlsaWeeks(DateTimeZone.forID(HrServiceLocator.getTimezoneService().getUserTimezone(principalId)), 0, false);
		Assert.assertTrue(msg + " >> Not enough FLSA weeks to verify aggregate hours, max: " + (flsaWeeks.size() - 1), flsaWeeks.size() > flsaWeek);

		// Build our Sum Map.
		FlsaWeek week = flsaWeeks.get(flsaWeek);
		List<FlsaDay> flsaDays = week.getFlsaDays();
		for (FlsaDay day : flsaDays) {
			for (TimeBlock bl : day.getAppliedTimeBlocks()) {
				for (TimeHourDetail thd : bl.getTimeHourDetails()) {
					if (ecToSumMap.containsKey(thd.getEarnCode())) {
						ecToSumMap.put(thd.getEarnCode(), ecToSumMap.get(thd.getEarnCode()).add(thd.getHours()));
                    }
                }
            }
        }

		// Assert that our values are correct.
		for (String key : ecToHoursMap.keySet()) {
			Assert.assertEquals(
					msg + " >> ("+key+") Wrong number of hours expected: " + ecToHoursMap.get(key) + " found: " + ecToSumMap.get(key) + " :: ",
					0,
					ecToHoursMap.get(key).compareTo(ecToSumMap.get(key)));
        }
	}

	public static void verifyAggregateHourSums(final Map<String,BigDecimal> ecToHoursMap, TkTimeBlockAggregate aggregate, int flsaWeek) {
		TkTestUtils.verifyAggregateHourSums("admin", "", ecToHoursMap, aggregate, flsaWeek);
	}

	/**
	 * Helper method to generate time blocks suitable for db persistence in
	 * unit tests.
	 */
	public static List<TimeBlock> createUniformActualTimeBlocks(TimesheetDocument timesheetDocument, Assignment assignment, String earnCode, DateTime start, int days, BigDecimal hours, BigDecimal amount, String principalId) {
		TimeBlockService service = TkServiceLocator.getTimeBlockService();
		List<TimeBlock> blocks = new ArrayList<TimeBlock>();

		for (int i=0; i<days; i++) {
			DateTime ci = start.plusDays(i);
			DateTime co = ci.plusHours(hours.intValue());

			blocks.addAll(service.buildTimeBlocks(timesheetDocument.getPrincipalId(), timesheetDocument.getCalendarEntry(),
                    assignment, earnCode, timesheetDocument.getDocumentId(), ci, co, hours, amount,
                    false, false, principalId, null, null));
		}

		return blocks;
	}

	public static Map<DateTime, BigDecimal> getDateToHoursMap(TimeBlockBo timeBlock, TimeHourDetailBo timeHourDetail) {
		Map<DateTime, BigDecimal> dateToHoursMap = new HashMap<DateTime, BigDecimal>();
		DateTime beginTime = timeBlock.getBeginDateTime();
		DateTime endTime = timeBlock.getEndDateTime();

		Days d = Days.daysBetween(beginTime, endTime);
		int numberOfDays = d.getDays();
		if (numberOfDays < 1) {
			dateToHoursMap.put(timeBlock.getBeginDateTime(), timeHourDetail.getHours());
			return dateToHoursMap;
		}
		DateTime currentTime = beginTime;
		for (int i = 0; i < numberOfDays; i++) {
			DateTime nextDayAtMidnight = currentTime.plusDays(1);
			nextDayAtMidnight = nextDayAtMidnight.hourOfDay().setCopy(12);
			nextDayAtMidnight = nextDayAtMidnight.minuteOfDay().setCopy(0);
			nextDayAtMidnight = nextDayAtMidnight.secondOfDay().setCopy(0);
			nextDayAtMidnight = nextDayAtMidnight.millisOfSecond().setCopy(0);
			Duration dur = new Duration(currentTime, nextDayAtMidnight);
			long duration = dur.getStandardSeconds();
			BigDecimal hrs = new BigDecimal(duration / 3600, HrConstants.MATH_CONTEXT);
			dateToHoursMap.put(currentTime, hrs);
			currentTime = nextDayAtMidnight;
		}
		Duration dur = new Duration(currentTime, endTime);
		long duration = dur.getStandardSeconds();
		BigDecimal hrs = new BigDecimal(duration / 3600, HrConstants.MATH_CONTEXT);
		dateToHoursMap.put(currentTime, hrs);

		return dateToHoursMap;
	}

}


text:
// Write a method that checks if the element at given position
// in given array of integers is bigger than its two neighbors (when such exist).

using System;
using System.Collections.Generic;
class NumberBiggerThanItsNeighbors
{
    static void Main()
    {
        // make and fill new array of integers
        int[] givenArray = MakeIntArray();

        // print the elements in a row
        foreach (var item in givenArray)
        {
            Console.Write("{0} ", item);
        }
        // take the wanted position
        Console.Write("\nEnter position that will be checked: ");
        int position = int.Parse(Console.ReadLine());

        Console.WriteLine();

        // check the neighbors and print the result
        CheckNeighbors(givenArray, position);
    }
    /// <summary>
    /// Method that checkes if the neighbors of the element array[position] are bigger that it.
    /// </summary>
    /// <param name="array">Array of integers.</param>
    /// <param name="position">The position of the element that is checked.</param>
    public static void CheckNeighbors(int[] array, int position)
    {
        // if 'position' is less than 0 or bigger that the size of the array
        if (position < 0 || position > array.Length)
        {
            // msg to the user
            Console.WriteLine("Given position is outside the bounds of the array!");
        }
        else
        {
            // if there is only one neighbor to the right of the element
            if (position == 0)
            {
                Console.WriteLine("There is only one neighbor that is {0} than {1}!", array[position] < array[position + 1] ? "bigger" : "not bigger", array[position]);
            }
            // else if there is only on neightbor to the left of the element
            else if (position == array.Length)
            {
                Console.WriteLine("There is only one neighbor that is {0} than {1}!", array[position] < array[position - 1] ? "bigger" : "not bigger", array[position]);
            }
            // if thre two neighbors
            else
            {
                // check if the element to the left is bigger than the element at [position] and print the result on the screen
                Console.WriteLine("Left neighbor is {0} than {1}!", array[position] < array[position - 1] ? "bigger" : "not bigger", array[position]);
                // check if the element to the right is bigger than the element at [position] and print the result on the screen
                Console.WriteLine("Right neighbor is {0} than {1}!", array[position] < array[position + 1] ? "bigger" : "not bigger", array[position]);
            }
        }
    }

    /// <summary>
    /// Method that makes and fills an integer array with unknown size.
    /// </summary>
    /// <returns>Returns integer array</returns>
    public static int[] MakeIntArray()
    {
        Console.WriteLine("Enter an array (anything else than integer to stop):");
        int number = 0;
        // make a list of integers
        List<int> list = new List<int>();
        // filling the list with integers from the console
        // if anything else thatn integer is given the loop will break
        while (int.TryParse(Console.ReadLine(), out number))
        {
            list.Add(number);
        }

        int[] intArray = new int[list.Count];
        // converting the list to array
        for (int index = 0; index < intArray.Length; index++)
        {
            intArray[index] = list[index];
        }
        return intArray;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html><title>index</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content=""><meta name="groc-document-path" content="index"><meta name="groc-project-path" content="README.md"><link rel="stylesheet" type="text/css" media="all" href="assets/style.css">

README.md

UCI

NOTE:This version is not backwards compatible with 0.2.x series of releases.

UCI is a thin wrapper on a uci
interface chess engine.

Installation

Make sure you have node.js installed. Then do:

$ npm install uci

Example

var Engine = require('uci');
var engine = new Engine('<path to engine executable>');
engine.runProcess().then(function () {
    console.log('Started');
    return engine.uciCommand();
}).then(function (idAndOptions) {
    console.log('Engine name - ' + idAndOptions.id.name);
    return engine.isReadyCommand();
}).then(function () {
    console.log('Ready');
    return engine.uciNewGameCommand();
}).then(function () {
    console.log('New game started');
    return engine.positionCommand('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1');
}).then(function () {
    console.log('Starting position set');
    console.log('Starting analysis');
    return engine.goInfiniteCommand(function infoHandler(info) {
        console.log(info);
    });
}).delay(2000).then(function () {
    console.log('Stopping analysis');
    return engine.stopCommand();
}).then(function (bestmove) {
    console.log('Bestmove: ');
    console.log(bestmove);
    return engine.quitCommand();
}).then(function () {
    console.log('Stopped');
}).fail(function (error) {
    console.log(error);
    process.exit();
}).done();

API

See here for API reference.

Contributing

Fork, pick an issue to fix from issues or
add a missing feature and send a pull request.

License

UCI is released under the MIT License. See the bundled LICENSE file for details.


text:
TestProf comes with the [RuboCop](https://github.com/bbatsov/rubocop) cops that help you write more performant tests.

To enable them, require `test_prof/rubocop` in your RuboCop configuration:

```yml
# .rubocop.yml
require:
 - 'test_prof/rubocop'
```

To configure cops to your needs:

```yml
RSpec/AggregateExamples:
  AddAggregateFailuresMetadata: false
```

Or you can just require it dynamically:

```sh
bundle exec rubocop -r 'test_prof/rubocop' --only RSpec/AggregateExamples
```

## RSpec/AggregateExamples

This cop encourages you to use one of the greatest features of the recent RSpec – aggregating failures within an example.

Instead of writing one example per assertion, you can group _independent_ assertions together, thus running all setup hooks only once.
That can dramatically increase your performance (by reducing the total number of examples).

Consider an example:

```ruby
# bad
it { is_expected.to be_success }
it { is_expected.to have_header("X-TOTAL-PAGES", 10) }
it { is_expected.to have_header("X-NEXT-PAGE", 2) }
its(:status) { is_expected.to eq(200) }

# good
it "returns the second page", :aggregate_failures do
  is_expected.to be_success
  is_expected.to have_header("X-TOTAL-PAGES", 10)
  is_expected.to have_header("X-NEXT-PAGE", 2)
  expect(subject.status).to eq(200)
end
```

Auto-correction will typically add `:aggregate_failures` to examples, but if your project enables it globally, or selectively by e.g. deriving metadata from file location, you may opt-out of adding it using `AddAggregateFailuresMetadata` config option.

This cop supports auto-correct feature, so you can automatically refactor you legacy tests!

**NOTE**: `its` examples shown here have been deprecated as of RSpec 3, but users of the [rspec-its gem](https://github.com/rspec/rspec-its) can leverage this cop to cut out that dependency.

**NOTE**: auto-correction of examples using block matchers, such as `change` is deliberately not supported.


text:
package com.weisong.trading.portfolio.strategy;

import java.util.Map;

public class NetProfitSystemFilter2 extends NetProfitSystemFilter {

	static public class Config extends NetProfitSystemFilter.Config {

		public Config() {
		}

		public Config(Map<String, String> props) {
			super(props);
		}

		@Override
		public String getName() {
			return "net-profit-2";
		}
	}

	static public class Builder extends SystemFilter.Builder<NetProfitSystemFilter2> {
		@Override
		public NetProfitSystemFilter2 create(Map<String, String> props) {
			return new NetProfitSystemFilter2(new Config(props));
		}

		@Override
		public NetProfitSystemFilter2 createDefault() {
			Config config = new Config();
			config.setPeriod(12);
			return new NetProfitSystemFilter2(config);
		}
	}

	public NetProfitSystemFilter2(Config config) {
		super(config);
	}
}


text:
update_package(){
	# update package
	sudo apt update
	sudo apt -y upgrade

	# update firmware
	sudo rpi-update
}

# install apt-get package
apt_get_install(){
	# setup JAPANESE environment
	sudo apt install -y fonts-vlgothic
	sudo apt install -y ibus-mozc

	# install editor
	sudo apt install -y vim
	sudo apt install -y vim-gtk

	# install gnome-terminal
	sudo apt install -y gnome-terminal

	# install partition setup tool
	sudo apt install -y gparted

	# install virtual terminal
	sudo apt install -y byobu

	# install screen capture tool
	sudo apt install -y scrot

	sudo apt install -y curl
}

# setup dotfiles
setup_dotfiles(){
	curl -l https://raw.githubusercontent.com/karaage0703/ubuntu-setup/master/bashrc.patch >> ~/.bashrc
}

START_TIME=`date +%s`

# change directory here
cd `dirname $0`

update_package
apt_get_install
setup_dotfiles

END_TIME=`date +%s`

SS=`expr ${END_TIME} - ${START_TIME}`
HH=`expr ${SS} / 3600`
SS=`expr ${SS} % 3600`
MM=`expr ${SS} / 60`
SS=`expr ${SS} % 60`

echo "Total Time: ${HH}:${MM}:${SS} (h:m:s)"

echo "Please reboot"


text:
"""
Source: https://github.com/bottlepy/bottle-extras/tree/master/redis

Copyright (c) 2013 Sean M. Collins

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

"""
import inspect
from urlparse import urlparse

import redis
from bottle import PluginError

class RedisPlugin(object):
    name = 'redis'
    api = 2

    def __init__(self, redis_url='redis://localhost:6379/0', keyword='rdb'):
        url = urlparse(redis_url)
        assert url.scheme == 'redis' or not url.scheme
        self.host = url.hostname
        self.port = int(url.port or 6379)
        self.password = url.password or None
        try:
            self.database = int(url.path.replace('/', ''))
        except (AttributeError, ValueError):
            self.database = 0
        self.keyword = keyword
        self.redisdb = None

    def setup(self, app):
        for other in app.plugins:
            if not isinstance(other, RedisPlugin):
                continue
            if other.keyword == self.keyword:
                raise PluginError("Found another redis plugin with " +
                        "conflicting settings (non-unique keyword).")
        if self.redisdb is None:
            self.redisdb = redis.ConnectionPool(host=self.host, port=self.port,
                                                password=self.password, db=self.database)

    def apply(self, callback, route):
        conf = route.config.get('redis') or {}
        args = inspect.getargspec(route.callback)[0]
        keyword = conf.get('keyword', self.keyword)
        if keyword not in args:
            return callback

        def wrapper(*args, **kwargs):
            kwargs[self.keyword] = redis.StrictRedis(connection_pool=self.redisdb)
            rv = callback(*args, **kwargs)
            return rv
        return wrapper

Plugin = RedisPlugin


text:
package org.mybatis.spring.support;

import static org.junit.Assert.assertEquals;

import java.sql.SQLException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mybatis.spring.AbstractMyBatisSpringTest;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @version $Id$
 */
public final class SqlSessionDaoSupportTest extends AbstractMyBatisSpringTest {
  private SqlSessionDaoSupport sqlSessionDaoSupport;

  private GenericApplicationContext applicationContext;

  @Before
  public void setup() {
    sqlSessionDaoSupport = new MockSqlSessionDao();
  }

  @After
  public void closeConnection() throws SQLException {
    connection.close();
  }

  @Test
  public void testWithSqlSessionTemplate() {
    SqlSessionTemplate sessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
    sqlSessionDaoSupport.setSqlSessionTemplate(sessionTemplate);
    sqlSessionDaoSupport.afterPropertiesSet();

    assertEquals("should store the Template", sessionTemplate, sqlSessionDaoSupport.getSqlSession());
  }

  @Test
  public void testWithSqlSessionFactory() {
    sqlSessionDaoSupport.setSqlSessionFactory(sqlSessionFactory);
    sqlSessionDaoSupport.afterPropertiesSet();

    assertEquals("should store the Factory", sqlSessionFactory, ((SqlSessionTemplate) sqlSessionDaoSupport
        .getSqlSession()).getSqlSessionFactory());
  }

  @Test
  public void testWithBothFactoryAndTemplate() {
    SqlSessionTemplate sessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
    sqlSessionDaoSupport.setSqlSessionTemplate(sessionTemplate);
    sqlSessionDaoSupport.setSqlSessionFactory(sqlSessionFactory);
    sqlSessionDaoSupport.afterPropertiesSet();

    assertEquals("should ignore the Factory", sessionTemplate, sqlSessionDaoSupport.getSqlSession());
  }

  @Test(expected = IllegalArgumentException.class)
  public void testWithNoFactoryOrSession() {
    sqlSessionDaoSupport.afterPropertiesSet();
  }

  @Test(expected = BeanCreationException.class)
  public void testAutowireWithNoFactoryOrSession() {
    setupContext();
    startContext();
  }

  @Test(expected = BeanCreationException.class)
  public void testAutowireWithTwoFactories() {
    setupContext();

    setupSqlSessionFactory("factory1");
    setupSqlSessionFactory("factory2");

    startContext();
  }

  private void setupContext() {
    applicationContext = new GenericApplicationContext();

    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(MockSqlSessionDao.class);
    applicationContext.registerBeanDefinition("dao", definition);

    // add support for autowiring fields
    AnnotationConfigUtils.registerAnnotationConfigProcessors(applicationContext);
  }

  private void startContext() {
    applicationContext.refresh();
    applicationContext.start();

    sqlSessionDaoSupport = applicationContext.getBean(MockSqlSessionDao.class);
  }

  private void setupSqlSessionFactory(String name) {
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionFactoryBean.class);
    definition.getPropertyValues().add("dataSource", dataSource);

    applicationContext.registerBeanDefinition(name, definition);
  }

  private static final class MockSqlSessionDao extends SqlSessionDaoSupport {
  }
}


text:
package com.hazelcast.internal.management.operation;

import com.hazelcast.core.HazelcastException;
import com.hazelcast.internal.management.ManagementCenterService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.executionservice.ExecutionService;
import com.hazelcast.spi.impl.operationservice.AbstractLocalOperation;

import java.util.concurrent.Future;

import static com.hazelcast.internal.util.ConcurrencyUtil.CALLER_RUNS;
import static com.hazelcast.internal.util.ExceptionUtil.peel;
import static com.hazelcast.internal.util.ExceptionUtil.withTryCatch;
import static com.hazelcast.internal.util.StringUtil.isNullOrEmpty;

/**
 *  Operation to run console command. The command is executed on {@link ExecutionService#MC_EXECUTOR} executor.
 */
public class RunConsoleCommandOperation extends AbstractLocalOperation {

    private final String command;
    private final String namespace;

    public RunConsoleCommandOperation(String command, String namespace) {
        this.command = command;
        this.namespace = namespace;
    }

    @Override
    public void run() throws Exception {
        final ManagementCenterService mcs = ((NodeEngineImpl) getNodeEngine()).getManagementCenterService();
        if (mcs == null) {
            sendResponse(new HazelcastException("ManagementCenterService is not initialized yet"));
            return;
        }
        final ILogger logger = getNodeEngine().getLogger(getClass());
        final ExecutionService executionService = getNodeEngine().getExecutionService();

        Future<String> future = executionService.submit(
                ExecutionService.MC_EXECUTOR,
                () -> {
                    try {
                        final String ns = namespace;
                        String cmd = command;
                        if (!isNullOrEmpty(ns)) {
                            // set namespace as a part of the command
                            cmd = ns + "__" + cmd;
                        }
                        return mcs.runConsoleCommand(cmd);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw e;
                    }
                });

        executionService.asCompletableFuture(future).whenCompleteAsync(
                withTryCatch(
                        logger,
                        (output, error) -> sendResponse(error != null ? peel(error) : output)
                ), CALLER_RUNS
        );
    }

    @Override
    public final Object getResponse() {
        throw new UnsupportedOperationException();
    }

    @Override
    public String getServiceName() {
        return ManagementCenterService.SERVICE_NAME;
    }

    @Override
    public boolean returnsResponse() {
        return false;
    }
}


text:
"""Driver for RackScale Design."""

import json

from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import units
from packaging import version
try:
    from rsd_lib import RSDLib
    from sushy import exceptions as sushy_exceptions
except ImportError:
    # Used for tests, when no rsd-lib is installed
    RSDLib = None
    sushy_exceptions = None

from cinder.common import constants
from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder import utils
from cinder.volume import driver
from cinder.volume import volume_utils

LOG = logging.getLogger(__name__)

RSD_OPTS = [
    cfg.StrOpt('podm_url',
               default='',
               help='URL of PODM service'),
    cfg.StrOpt('podm_username',
               default='',
               help='Username of PODM service'),
    cfg.StrOpt('podm_password',
               default='',
               help='Password of PODM service',
               secret=True),
]

class RSDRetryableException(exception.VolumeDriverException):
    message = _("RSD retryable exception: %(reason)s")

def get_volume_metadata(volume):
    metadata = volume.get('volume_metadata')
    if metadata:
        ret = {data['key']: data['value'] for data in metadata}
    else:
        ret = volume.get('metadata', {})
    return ret

class RSDClient(object):
    def __init__(self, rsdlib):
        self.rsdlib = rsdlib

    @classmethod
    def initialize(cls, url, username, password, verify):
        if not RSDLib:
            raise exception.VolumeBackendAPIException(
                data=(_("RSDLib is not available, please install rsd-lib.")))

        try:
            rsdlib = RSDLib(url, username, password, verify=verify).factory()
        except Exception:
            # error credentials may throw unexpected exception
            LOG.exception("Cannot connect to RSD PODM")
            raise exception.VolumeBackendAPIException(
                data=_("initialize: Cannot connect to RSD PODM."))

        rsd_api_version = version.parse(rsdlib._rsd_api_version)
        if rsd_api_version < version.parse("2.4.0"):
            raise exception.VolumeBackendAPIException(
                data=(_("initialize: Unsupported rsd_api version: "
                        "%(current)s < %(expected)s.")
                      % {'current': rsdlib._rsd_api_version,
                         'expected': "2.4.0"}))

        if version.parse(rsdlib._redfish_version) < version.parse("1.1.0"):
            raise exception.VolumeBackendAPIException(
                data=(_("initialize: Unsupported rsd_lib version: "
                        "%(current)s < %(expected)s.")
                      % {'current': rsdlib._redfish_version,
                         'expected': "1.1.0"}))

        LOG.info("initialize: Connected to %s at version %s.",
                 url, rsdlib._rsd_api_version)
        return cls(rsdlib)

    def _get_storage(self, storage_url):
        ss_url = "/".join(storage_url.split("/", 5)[:5])
        storage_service = self.rsdlib.get_storage_service(ss_url)
        return storage_service

    def _get_storages(self, filter_nvme=True):
        ret = []
        for storage in (self.rsdlib
                        .get_storage_service_collection().get_members()):
            if filter_nvme:
                drives = storage.drives.get_members()
                if drives and (any(map(lambda drive:
                                       False if not drive.protocol
                                       else 'nvme' in drive.protocol.lower(),
                                       drives))):
                    ret.append(storage)
            else:
                ret.append(storage)
        return ret

    def _get_node(self, node_url):
        return self.rsdlib.get_node(node_url)

    def _get_volume(self, volume_url):
        ss = self._get_storage(volume_url)
        volume = ss.volumes.get_member(volume_url)
        return volume

    def _get_providing_pool(self, volume):
        len_cs = len(volume.capacity_sources)
        if len_cs != 1:
            raise exception.ValidationError(
                detail=(_("Volume %(vol)s has %(len_cs)d capacity_sources!")
                        % {'vol': volume.path,
                           'len_cs': len_cs}))
        len_pp = len(volume.capacity_sources[0].providing_pools)
        if len_pp != 1:
            raise exception.ValidationError(
                detail=(_("Volume %(vol)s has %(len_pp)d providing_pools!")
                        % {'vol': volume.path,
                           'len_pp': len_pp}))
        providing_pool = volume.capacity_sources[0].providing_pools[0]
        return providing_pool.get_members()[0].path

    def _create_vol_or_snap(self,
                            storage,
                            size_in_bytes,
                            pool_url=None,
                            source_snap=None,
                            source_vol=None):
        capacity_sources = None
        if pool_url:
            capacity_sources = [{
                "ProvidingPools": [{
                    "@odata.id": pool_url
                }]
            }]

        replica_infos = None
        if source_snap:
            replica_infos = [{
                "ReplicaType": "Clone",
                "Replica": {"@odata.id": source_snap}
            }]
            if source_vol:
                raise exception.InvalidInput(
                    reason=(_("Cannot specify both source_snap=%(snap)s and "
                              "source_vol=%(vol)s!")
                            % {'snap': source_snap,
                               'vol': source_vol}))
        elif source_vol:
            replica_infos = [{
                "ReplicaType": "Snapshot",
                "Replica": {"@odata.id": source_vol}
            }]

        LOG.debug("Creating... with size_byte=%s, "
                  "capacity_sources=%s, replica_infos=%s",
                  size_in_bytes, capacity_sources, replica_infos)
        volume_url = storage.volumes.create_volume(
            size_in_bytes,
            capacity_sources=capacity_sources,
            replica_infos=replica_infos)
        LOG.debug("Created volume_url=%s", volume_url)
        return volume_url

    def create_volume(self, size_in_gb):
        size_in_bytes = size_in_gb * units.Gi
        try:
            for storage in self._get_storages():
                try:
                    volume_url = self._create_vol_or_snap(
                        storage, size_in_bytes)
                    LOG.info("RSD volume %s created, with size %s GiB",
                             volume_url, size_in_gb)
                    return volume_url
                # NOTE(Yingxin): Currently, we capture sushy_exception to
                # identify that volume creation is failed at RSD backend.
                except (sushy_exceptions.HTTPError,
                        sushy_exceptions.ConnectionError) as e:
                    LOG.warning("skipped storage %s for creation error %s",
                                storage.path, e)
        except Exception:
            LOG.exception("Create volume failed")

        raise exception.VolumeBackendAPIException(
            data=(_('Unable to create new volume with %d GiB') % size_in_gb))

    def create_snap(self, volume_url):
        try:
            ss = self._get_storage(volume_url)
            volume = self._get_volume(volume_url)
            pool_url = self._get_providing_pool(volume)
            snap_url = self._create_vol_or_snap(
                ss, volume.capacity_bytes,
                pool_url=pool_url,
                source_vol=volume_url)
            LOG.info("RSD snapshot %s created, from volume %s",
                     snap_url, volume_url)
            return snap_url
        except Exception:
            LOG.exception("Create snapshot failed")
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to create snapshot from volume %s')
                      % volume_url))

    def create_volume_from_snap(self, snap_url, size_in_gb=None):
        try:
            ss = self._get_storage(snap_url)
            snap = self._get_volume(snap_url)
            if not size_in_gb:
                size_in_bytes = snap.capacity_bytes
            else:
                size_in_bytes = size_in_gb * units.Gi
            pool_url = self._get_providing_pool(snap)
            volume_url = self._create_vol_or_snap(
                ss, size_in_bytes,
                pool_url=pool_url,
                source_snap=snap_url)
            LOG.info("RSD volume %s created, from snap %s, "
                     "with size %s GiB.",
                     volume_url, snap_url,
                     size_in_bytes / units.Gi)
            return volume_url
        except Exception:
            LOG.exception("Create volume from snapshot failed")
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to create volume from snapshot %s')
                      % snap_url))

    def clone_volume(self, volume_url, size_in_gb=None):
        try:
            ss = self._get_storage(volume_url)
            origin_volume = self._get_volume(volume_url)
            pool_url = self._get_providing_pool(origin_volume)
            snap_url = self._create_vol_or_snap(
                ss, origin_volume.capacity_bytes,
                pool_url=pool_url,
                source_vol=volume_url)
        except Exception:
            LOG.exception("Clone volume failed (create snapshot phase)")
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to create volume from volume %s, snapshot '
                        'creation failed.')
                      % volume_url))
        try:
            if not size_in_gb:
                size_in_bytes = origin_volume.capacity_bytes
            else:
                size_in_bytes = size_in_gb * units.Gi
            new_vol_url = self._create_vol_or_snap(
                ss, size_in_bytes,
                pool_url=pool_url,
                source_snap=snap_url)
            LOG.info("RSD volume %s created, from volume %s and snap %s, "
                     "with size %s GiB.",
                     new_vol_url, volume_url, snap_url,
                     size_in_bytes / units.Gi)
            return new_vol_url, snap_url
        except Exception:
            LOG.exception("Clone volume failed (clone volume phase)")
            try:
                self.delete_vol_or_snap(snap_url)
            except Exception:
                LOG.exception("Clone volume failed (undo snapshot)")
                raise exception.VolumeBackendAPIException(
                    data=(_('Unable to delete the temp snapshot %(snap)s, '
                            'during a failure to clone volume %(vol)s.')
                          % {'snap': snap_url,
                             'vol': volume_url}))
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to create volume from volume %s, volume '
                        'creation failed.')
                      % volume_url))

    def extend_volume(self, volume_url, size_in_gb):
        size_in_bytes = size_in_gb * units.Gi
        try:
            volume = self._get_volume(volume_url)
            volume.resize(size_in_bytes)
            LOG.info("RSD volume %s resized to %s Bytes",
                     volume.path, size_in_bytes)
        except Exception:
            LOG.exception("Extend volume failed")
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to extend volume %s.') % volume_url))

    def delete_vol_or_snap(self, volume_url,
                           volume_name='', ignore_non_exist=False):
        try:
            try:
                volume = self._get_volume(volume_url)
            except sushy_exceptions.ResourceNotFoundError:
                if ignore_non_exist:
                    LOG.warning("Deleted non existent vol/snap %s", volume_url)
                else:
                    raise
            if volume.links.endpoints:
                LOG.warning("Delete vol/snap failed, attached: %s", volume_url)
                raise exception.VolumeIsBusy(_("Volume is already attached"),
                                             volume_name=volume_name)
            volume.delete()
        except sushy_exceptions.BadRequestError as e:
            try:
                msg = e.body['@Message.ExtendedInfo'][0]['Message']
                if (msg == "Cannot delete source snapshot volume when "
                           "other clone volumes are based on this snapshot."):
                    LOG.warning("Delete vol/snap failed, has-deps: %s",
                                volume_url)
                    raise exception.SnapshotIsBusy(snapshot_name=volume_name)
            except Exception:
                LOG.exception("Delete vol/snap failed")
                raise exception.VolumeBackendAPIException(
                    data=(_('Unable to delete volume %s.') % volume_url))
        except Exception:
            LOG.exception("Delete vol/snap failed")
            raise exception.VolumeBackendAPIException(
                data=(_('Unable to delete volume %s.') % volume_url))
        LOG.info("RSD volume deleted: %s", volume_url)

    def get_node_url_by_uuid(self, uuid):
        uuid = uuid.upper()
        try:
            nodes = self.rsdlib.get_node_collection().get_members()
            for node in nodes:
                node_system = None
                if node:
                    node_system = self.rsdlib.get_system(
                        node.links.computer_system)
                if (node and
                        node_system and
                        node_system.uuid and
                        node_system.uuid.upper() == uuid):
                    return node.path
        except Exception:
            LOG.exception("Get node url failed")
        return ""

    def get_stats(self):
        free_capacity_gb = 0
        total_capacity_gb = 0
        allocated_capacity_gb = 0
        total_volumes = 0
        try:
            storages = self._get_storages()
            for storage in storages:
                for pool in storage.storage_pools.get_members():
                    total_capacity_gb += (
                        float(pool.capacity.allocated_bytes or 0) / units.Gi)
                    allocated_capacity_gb += (
                        float(pool.capacity.consumed_bytes or 0) / units.Gi)
                total_volumes += len(storage.volumes.members_identities)
            free_capacity_gb = total_capacity_gb - allocated_capacity_gb
            LOG.info("Got RSD stats: free_gb:%s, total_gb:%s, "
                     "allocated_gb:%s, volumes:%s",
                     free_capacity_gb,
                     total_capacity_gb,
                     allocated_capacity_gb,
                     total_volumes)
        except Exception:
            LOG.exception("Get stats failed")

        return (free_capacity_gb,
                total_capacity_gb,
                allocated_capacity_gb,
                total_volumes)

    def _get_nqn_endpoints(self, endpoint_urls):
        ret = []
        for endpoint_url in endpoint_urls:
            endpoint_json = (
                json.loads(self.rsdlib._conn.get(endpoint_url).text))
            for ident in endpoint_json["Identifiers"]:
                if ident["DurableNameFormat"] == "NQN":
                    nqn = ident["DurableName"]
                    ret.append((nqn, endpoint_json))
                    break
        return ret

    @utils.retry(RSDRetryableException,
                 interval=4,
                 retries=5,
                 backoff_rate=2)
    def attach_volume_to_node(self, volume_url, node_url):
        LOG.info('Trying attach from node %s to volume %s',
                 node_url, volume_url)
        try:
            volume = self._get_volume(volume_url)
            node = self._get_node(node_url)
            if len(volume.links.endpoints) > 0:
                raise exception.ValidationError(
                    detail=(_("Volume %s already attached") % volume_url))

            node.attach_endpoint(volume.path)
        except sushy_exceptions.InvalidParameterValueError:
            LOG.exception("Attach volume failed (not allowable)")
            raise RSDRetryableException(
                reason=(_("Not allowed to attach from "
                          "%(node)s to %(volume)s.")
                        % {'node': node_url,
                           'volume': volume_url}))
        except Exception:
            LOG.exception("Attach volume failed (attach phase)")
            raise exception.VolumeBackendAPIException(
                data=(_("Attach failed from %(node)s to %(volume)s.")
                      % {'node': node_url,
                         'volume': volume_url}))
        try:
            volume.refresh()
            node.refresh()

            v_endpoints = volume.links.endpoints
            v_endpoints = self._get_nqn_endpoints(v_endpoints)
            if len(v_endpoints) != 1:
                raise exception.ValidationError(
                    detail=(_("Attach volume error: %d target nqns")
                            % len(v_endpoints)))
            target_nqn, v_endpoint = v_endpoints[0]
            ip_transports = v_endpoint["IPTransportDetails"]
            if len(ip_transports) != 1:
                raise exception.ValidationError(
                    detail=(_("Attach volume error: %d target ips")
                            % len(ip_transports)))
            ip_transport = ip_transports[0]
            target_ip = ip_transport["IPv4Address"]["Address"]
            target_port = ip_transport["Port"]

            node_system = self.rsdlib.get_system(node.links.computer_system)
            n_endpoints = tuple(
                val["@odata.id"]
                for val in node_system.json["Links"]["Endpoints"])
            n_endpoints = self._get_nqn_endpoints(n_endpoints)
            if len(n_endpoints) == 0:
                raise exception.ValidationError(
                    detail=(_("Attach volume error: %d host nqns")
                            % len(n_endpoints)))
            host_nqn, v_endpoint = n_endpoints[0]

            LOG.info('Attachment successful: Retrieved target IP %s, '
                     'target Port %s, target NQN %s and initiator NQN %s',
                     target_ip, target_port, target_nqn, host_nqn)
            return (target_ip, target_port, target_nqn, host_nqn)
        except Exception as e:
            LOG.exception("Attach volume failed (post-attach)")
            try:
                node.refresh()
                node.detach_endpoint(volume.path)
                LOG.info('Detached from node %s to volume %s',
                         node_url, volume_url)
            except Exception:
                LOG.exception("Attach volume failed (undo attach)")
                raise exception.VolumeBackendAPIException(
                    data=(_("Undo-attach failed from %(node)s to %(volume)s.")
                          % {'node': node_url,
                             'volume': volume_url}))
            if isinstance(e, exception.ValidationError):
                raise RSDRetryableException(
                    reason=(_("Validation error during post-attach from "
                              "%(node)s to %(volume)s.")
                            % {'node': node_url,
                               'volume': volume_url}))
            else:
                raise exception.VolumeBackendAPIException(
                    data=(_("Post-attach failed from %(node)s to %(volume)s.")
                          % {'node': node_url,
                             'volume': volume_url}))

    def detach_volume_from_node(self, volume_url, node_url):
        LOG.info('Trying detach from node %s for volume %s',
                 node_url, volume_url)
        try:
            volume = self._get_volume(volume_url)
            node = self._get_node(node_url)
            node.detach_endpoint(volume.path)
        except Exception:
            LOG.exception("Detach volume failed")
            raise exception.VolumeBackendAPIException(
                data=(_("Detach failed from %(node)s for %(volume)s.")
                      % {'node': node_url,
                         'volume': volume_url}))

    def detach_all_node_connections_for_volume(self, volume_url):
        try:
            volume = self._get_volume(volume_url)
            nodes = self.rsdlib.get_node_collection().get_members()
            for node in nodes:
                if node:
                    if volume.path in node.get_allowed_detach_endpoints():
                        node.detach_endpoint(volume.path)
        except Exception:
            LOG.exception("Detach failed for volume from all host "
                          "connections")
            raise exception.VolumeBackendAPIException(
                data=(_("Detach failed for %(volume)s from all host "
                        "connections.")
                      % {'volume': volume_url}))

@interface.volumedriver
class RSDDriver(driver.VolumeDriver):
    """Openstack driver to perform NVMe-oF volume management in RSD Solution

    .. code-block:: none

    Version History:
        1.0.0: Initial driver
    """

    VERSION = '1.0.0'
    CI_WIKI_NAME = 'INTEL-RSD-CI'

    def __init__(self, *args, **kwargs):
        super(RSDDriver, self).__init__(*args, **kwargs)

        self.configuration.append_config_values(RSD_OPTS)
        self.rsdClient = None

    @staticmethod
    def get_driver_options():
        return RSD_OPTS

    @volume_utils.trace
    def do_setup(self, context):
        self.rsdClient = RSDClient.initialize(
            self.configuration.podm_url,
            self.configuration.podm_username,
            self.configuration.podm_password,
            self.configuration.suppress_requests_ssl_warnings)

    def check_for_setup_error(self):
        pass

    @volume_utils.trace
    def create_volume(self, volume):
        size_in_gb = int(volume['size'])
        volume_url = self.rsdClient.create_volume(size_in_gb)
        return {'provider_location': volume_url}

    @volume_utils.trace
    def delete_volume(self, volume):
        volume_url = volume['provider_location']
        if not volume_url:
            return
        self.rsdClient.delete_vol_or_snap(volume_url,
                                          volume_name=volume.name,
                                          ignore_non_exist=True)
        provider_snap_url = volume.metadata.get("rsd_provider_snap")
        if provider_snap_url:
            self.rsdClient.delete_vol_or_snap(provider_snap_url,
                                              volume_name=volume.name,
                                              ignore_non_exist=True)

    @volume_utils.trace
    def _update_volume_stats(self):
        backend_name = (
            self.configuration.safe_get('volume_backend_name') or 'RSD')

        ret = self.rsdClient.get_stats()
        (free_capacity_gb,
         total_capacity_gb,
         allocated_capacity_gb,
         total_volumes) = ret

        spool = {}
        spool['pool_name'] = backend_name
        spool['total_capacity_gb'] = total_capacity_gb
        spool['free_capacity_gb'] = free_capacity_gb
        spool['allocated_capacity_gb'] = allocated_capacity_gb
        spool['thin_provisioning_support'] = True
        spool['thick_provisioning_support'] = True
        spool['multiattach'] = False

        self._stats['volume_backend_name'] = backend_name
        self._stats['vendor_name'] = 'Intel'
        self._stats['driver_version'] = self.VERSION
        self._stats['storage_protocol'] = constants.NVMEOF_VARIANT_2
        # SinglePool
        self._stats['pools'] = [spool]

    @volume_utils.trace
    def initialize_connection(self, volume, connector, **kwargs):
        uuid = connector.get("system uuid")
        if not uuid:
            msg = _("initialize_connection error: no uuid available!")
            LOG.exception(msg)
            raise exception.VolumeBackendAPIException(msg)
        node_url = self.rsdClient.get_node_url_by_uuid(uuid)
        if not node_url:
            msg = (_("initialize_connection error: no node_url from uuid %s!")
                   % uuid)
            LOG.exception(msg)
            raise exception.VolumeBackendAPIException(msg)

        volume_url = volume['provider_location']
        target_ip, target_port, target_nqn, initiator_nqn = (
            self.rsdClient.attach_volume_to_node(volume_url, node_url))
        conn_info = {
            'driver_volume_type': 'nvmeof',
            'data': {
                'transport_type': 'rdma',
                'host_nqn': initiator_nqn,
                'nqn': target_nqn,
                'target_port': target_port,
                'target_portal': target_ip,
            }
        }
        return conn_info

    @volume_utils.trace
    def terminate_connection(self, volume, connector, **kwargs):
        if connector is None:
            # None connector means force-detach
            volume_url = volume['provider_location']
            self.rsdClient.detach_all_node_connections_for_volume(volume_url)
            return

        uuid = connector.get("system uuid")
        if not uuid:
            msg = _("terminate_connection error: no uuid available!")
            LOG.exception(msg)
            raise exception.VolumeBackendAPIException(msg)
        node_url = self.rsdClient.get_node_url_by_uuid(uuid)
        if not node_url:
            msg = (_("terminate_connection error: no node_url from uuid %s!")
                   % uuid)
            LOG.exception(msg)
            raise exception.VolumeBackendAPIException(msg)

        volume_url = volume['provider_location']
        self.rsdClient.detach_volume_from_node(volume_url, node_url)

    def ensure_export(self, context, volume):
        pass

    def create_export(self, context, volume, connector):
        pass

    def remove_export(self, context, volume):
        pass

    @volume_utils.trace
    def create_volume_from_snapshot(self, volume, snapshot):
        snap_url = snapshot.provider_location
        old_size_in_gb = snapshot.volume_size
        size_in_gb = volume.size
        volume_url = self.rsdClient.create_volume_from_snap(snap_url)
        if size_in_gb != old_size_in_gb:
            try:
                self.rsdClient.extend_volume(volume_url, size_in_gb)
            except Exception:
                self.rsdClient.delete_vol_or_snap(volume_url,
                                                  volume_name=volume.name)
                raise
        return {'provider_location': volume_url}

    @volume_utils.trace
    def create_snapshot(self, snapshot):
        volume_url = snapshot.volume.provider_location
        snap_url = self.rsdClient.create_snap(volume_url)
        snapshot.provider_location = snap_url
        snapshot.save()

    @volume_utils.trace
    def delete_snapshot(self, snapshot):
        snap_url = snapshot.provider_location
        if not snap_url:
            return
        self.rsdClient.delete_vol_or_snap(snap_url,
                                          volume_name=snapshot.name,
                                          ignore_non_exist=True)

    @volume_utils.trace
    def extend_volume(self, volume, new_size):
        volume_url = volume.provider_location
        self.rsdClient.extend_volume(volume_url, new_size)

    def clone_image(self, context, volume,
                    image_location, image_meta,
                    image_service):
        return None, False

    @volume_utils.trace
    def create_cloned_volume(self, volume, src_vref):
        volume_url = src_vref.provider_location
        old_size_in_gb = src_vref.size
        size_in_gb = volume.size
        new_vol_url, provider_snap_url = self.rsdClient.clone_volume(
            volume_url)
        metadata = get_volume_metadata(volume)
        metadata["rsd_provider_snap"] = provider_snap_url
        if size_in_gb != old_size_in_gb:
            try:
                self.rsdClient.extend_volume(new_vol_url, size_in_gb)
            except Exception:
                self.rsdClient.delete_vol_or_snap(new_vol_url,
                                                  volume_name=volume.name)
                self.rsdClient.delete_vol_or_snap(provider_snap_url,
                                                  volume_name=volume.name)
                raise
        return {'provider_location': new_vol_url,
                'metadata': metadata}


text:
import puppeteer from 'puppeteer';

const URL = 'http://localhost:5002';

let browser;
beforeAll(async () => {
  browser = await puppeteer.launch({
    headless: false,
    devtools: true,
    slowMo: 250,
  });
});

afterAll(async () => {
  await browser.close();
});

let page;
beforeEach(async () => {
  page = await browser.newPage();

  page.emulate({
    viewport: {
      width: 500,
      height: 900,
    },
    userAgent: '',
  });
});

afterEach(async () => {
  await page.close();
});

it('Can login successfully', async () => {
  await page.goto(`${URL}/signin`);

  await expect(page).toFillForm('form', { username: 'James', password: 'Doe' });
  await page.click('button[type=submit]');

  await page.waitForSelector('[data-testid="homepage"]');
});


text:
package org.optaplanner.constraint.streams.bavet;

import static org.assertj.core.api.Assertions.assertThatCode;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.count;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.countBi;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.countQuad;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.countTri;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.sum;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.toMap;
import static org.optaplanner.core.api.score.stream.ConstraintCollectors.toSet;
import static org.optaplanner.core.api.score.stream.Joiners.equal;
import static org.optaplanner.core.api.score.stream.Joiners.filtering;
import static org.optaplanner.core.impl.testdata.util.PlannerTestUtils.asMap;

import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;

import org.junit.jupiter.api.TestTemplate;
import org.optaplanner.constraint.streams.common.AbstractAdvancedGroupByConstraintStreamTest;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.api.score.stream.Joiners;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.testdata.domain.score.lavish.TestdataLavishEntity;
import org.optaplanner.core.impl.testdata.domain.score.lavish.TestdataLavishEntityGroup;
import org.optaplanner.core.impl.testdata.domain.score.lavish.TestdataLavishSolution;
import org.optaplanner.core.impl.util.Pair;

final class BavetAdvancedGroupByConstraintStreamTest extends AbstractAdvancedGroupByConstraintStreamTest {

    public BavetAdvancedGroupByConstraintStreamTest(boolean constraintMatchEnabled) {
        super(new BavetConstraintStreamImplSupport(constraintMatchEnabled));
    }

    @TestTemplate
    void collectedDowngradedAndFiltered() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 5, 1, 7);
        TestdataLavishEntity entity = new TestdataLavishEntity("MyEntity 1", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector = buildScoreDirector(
                factory -> factory.forEach(TestdataLavishEntity.class)
                        .groupBy(e -> e.getCode().substring(0, 1), count())
                        .groupBy(Pair::of)
                        .filter(pair -> !pair.getKey().equals("G"))
                        .penalize(SimpleScore.ONE, Pair::getValue)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector, assertMatch(Pair.of("M", 1)));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector);
    }

    @TestTemplate
    void collectedAndFiltered() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 5, 1, 7);
        TestdataLavishEntityGroup entityGroup1 = new TestdataLavishEntityGroup("MyEntityGroup");
        solution.getEntityGroupList().add(entityGroup1);
        TestdataLavishEntity entity1 = new TestdataLavishEntity("MyEntity 1", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity1);
        TestdataLavishEntity entity2 = new TestdataLavishEntity("MyEntity 2", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity2);
        TestdataLavishEntity entity3 = new TestdataLavishEntity("MyEntity 3", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity3);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                        .groupBy(count())
                        .filter(count -> count == 10)
                        .penalize(SimpleScore.ONE, i -> i)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector, assertMatchWithScore(-10, 10));

        // Incremental
        Stream.of(entity1, entity2).forEach(entity -> {
            scoreDirector.beforeEntityRemoved(entity);
            solution.getEntityList().remove(entity);
            scoreDirector.afterEntityRemoved(entity);
        });
        assertScore(scoreDirector); // There is less than 10 entities, and therefore there are no penalties.
    }

    @TestTemplate
    void collectedFilteredRecollected() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 2);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                        .groupBy(toSet())
                        .groupBy(sum(Set::size))
                        .penalize(SimpleScore.ONE, count -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector, assertMatchWithScore(-2, 2));

        // Incremental
        TestdataLavishEntity entity = solution.getFirstEntity();
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, 1));
    }

    @TestTemplate
    void uniGroupByRecollected() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 2);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                        .groupBy(TestdataLavishEntity::getEntityGroup)
                        .groupBy(toSet())
                        .penalize(SimpleScore.ONE, Set::size)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity1 = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-2, asSet(entity1.getEntityGroup(), entity2.getEntityGroup())));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity1);
        solution.getEntityList().remove(entity1);
        scoreDirector.afterEntityRemoved(entity1);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, asSet(entity2.getEntityGroup())));
    }

    @TestTemplate
    void biGroupByRecollected() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 3, 2, 5);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        // Stream of all unique entity bi tuples that share a group
                        .groupBy((a, b) -> a.getEntityGroup(), countBi())
                        .groupBy(toMap((g, c) -> g, (g, c) -> c, Integer::sum))
                        .penalize(SimpleScore.ONE)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getFirstEntityGroup(), 3, solution.getEntityGroupList().get(1), 1)));

        // Incremental
        TestdataLavishEntity entity = solution.getFirstEntity();
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getFirstEntityGroup(), 1, solution.getEntityGroupList().get(1), 1)));
    }

    @TestTemplate
    void triGroupByRecollected() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 3, 2, 6);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        // Stream of all unique entity tri tuples that share a group
                        .groupBy((a, b, c) -> a.getEntityGroup(), countTri())
                        .groupBy(toMap((g, c) -> g, (g, c) -> c, Integer::sum))
                        .penalize(SimpleScore.ONE)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getFirstEntityGroup(), 3, solution.getEntityGroupList().get(1), 3)));

        // Incremental
        TestdataLavishEntity entity = solution.getFirstEntity();
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getEntityGroupList().get(1), 3)));
    }

    @TestTemplate
    void quadGroupByRecollected() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 3, 2, 8);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        .join(TestdataLavishEntity.class,
                                equal((a, b, c) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c, d) -> !Objects.equals(a, d) && !Objects.equals(b, d)
                                        && !Objects.equals(c, d)))
                        // Stream of all unique entity quad tuples that share a group
                        .groupBy((a, b, c, d) -> a.getEntityGroup(), countQuad())
                        .groupBy(toMap((g, c) -> g, (g, c) -> c, Integer::sum))
                        .penalize(SimpleScore.ONE)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getFirstEntityGroup(), 12, solution.getEntityGroupList().get(1), 12)));

        // Incremental
        TestdataLavishEntity entity = solution.getFirstEntity();
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector,
                assertMatchWithScore(-1,
                        asMap(solution.getEntityGroupList().get(1), 12)));
    }

    @TestTemplate
    void biGroupByRegrouped() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 4);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .groupBy((a, b) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .penalize(SimpleScore.ONE, (group, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, entity.getEntityGroup(), 1),
                assertMatchWithScore(-1, entity2.getEntityGroup(), 1));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, entity2.getEntityGroup(), 1));
    }

    @TestTemplate
    void triGroupByRegrouped() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 6);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        // Stream of all unique entity tri tuples that share a group
                        .groupBy((a, b, c) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .penalize(SimpleScore.ONE, (group, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, entity.getEntityGroup(), 1),
                assertMatchWithScore(-1, entity2.getEntityGroup(), 1));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, entity2.getEntityGroup(), 1));
    }

    @TestTemplate
    void quadGroupByRegrouped() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 8);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        .join(TestdataLavishEntity.class,
                                equal((a, b, c) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c, d) -> !Objects.equals(a, d) && !Objects.equals(b, d)
                                        && !Objects.equals(c, d)))
                        // Stream of all unique entity quad tuples that share a group
                        .groupBy((a, b, c, d) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .penalize(SimpleScore.ONE, (group, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, entity.getEntityGroup(), 1),
                assertMatchWithScore(-1, entity2.getEntityGroup(), 1));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, entity2.getEntityGroup(), 1));
    }

    @TestTemplate
    void biGroupByRegroupedDouble() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 4);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .groupBy((a, b) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .groupBy((group, count) -> group.toString(), countBi())
                        .penalize(SimpleScore.ONE, (groupName, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, new Object[] { entity.getEntityGroup().toString(), 1 }),
                assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));
    }

    @TestTemplate
    void triGroupByRegroupedDouble() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 6);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        // Stream of all unique entity tri tuples that share a group
                        .groupBy((a, b, c) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .groupBy((group, count) -> group.toString(), countBi())
                        .penalize(SimpleScore.ONE, (groupName, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, new Object[] { entity.getEntityGroup().toString(), 1 }),
                assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));
    }

    @TestTemplate
    void quadGroupByRegroupedDouble() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(2, 2, 2, 8);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory
                        .forEachUniquePair(TestdataLavishEntity.class, equal(TestdataLavishEntity::getEntityGroup))
                        .join(TestdataLavishEntity.class,
                                equal((a, b) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c) -> !Objects.equals(a, c) && !Objects.equals(b, c)))
                        .join(TestdataLavishEntity.class,
                                equal((a, b, c) -> a.getEntityGroup(), TestdataLavishEntity::getEntityGroup),
                                filtering((a, b, c, d) -> !Objects.equals(a, d) && !Objects.equals(b, d)
                                        && !Objects.equals(c, d)))
                        // Stream of all unique entity quad tuples that share a group
                        .groupBy((a, b, c, d) -> a.getEntityGroup())
                        .groupBy(Function.identity(), count())
                        .groupBy((group, count) -> group.toString(), countBi())
                        .penalize(SimpleScore.ONE, (groupName, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        TestdataLavishEntity entity = solution.getFirstEntity();
        TestdataLavishEntity entity2 = solution.getEntityList().get(1);

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, new Object[] { entity.getEntityGroup().toString(), 1 }),
                assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));

        // Incremental
        scoreDirector.beforeEntityRemoved(entity);
        solution.getEntityList().remove(entity);
        scoreDirector.afterEntityRemoved(entity);
        assertScore(scoreDirector, assertMatchWithScore(-1, new Object[] { entity2.getEntityGroup().toString(), 1 }));
    }

    @TestTemplate
    void existsAfterGroupBy() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(1, 1, 1, 1);
        TestdataLavishEntityGroup entityGroup1 = new TestdataLavishEntityGroup("MyEntityGroup");
        solution.getEntityGroupList().add(entityGroup1);
        TestdataLavishEntity entity1 = new TestdataLavishEntity("MyEntity 1", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity1);
        TestdataLavishEntity entity2 = new TestdataLavishEntity("MyEntity 2", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity2);
        TestdataLavishEntity entity3 = new TestdataLavishEntity("MyEntity 3", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity3);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                        .groupBy(TestdataLavishEntity::getEntityGroup, count())
                        .ifExists(TestdataLavishEntityGroup.class, equal((groupA, count) -> groupA, Function.identity()))
                        .penalize(SimpleScore.ONE, (groupA, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-2, solution.getFirstEntityGroup(), 2),
                assertMatchWithScore(-2, entityGroup1, 2));

        // Incremental
        scoreDirector.beforeProblemFactRemoved(entityGroup1);
        solution.getEntityGroupList().remove(entityGroup1);
        scoreDirector.afterProblemFactRemoved(entityGroup1);
        assertScore(scoreDirector,
                assertMatchWithScore(-2, solution.getFirstEntityGroup(), 2));
    }

    @TestTemplate
    void groupByAfterExists() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(1, 1, 1, 1);
        TestdataLavishEntityGroup entityGroup1 = new TestdataLavishEntityGroup("MyEntityGroup");
        solution.getEntityGroupList().add(entityGroup1);
        TestdataLavishEntity entity1 = new TestdataLavishEntity("MyEntity 1", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity1);
        TestdataLavishEntity entity2 = new TestdataLavishEntity("MyEntity 2", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity2);
        TestdataLavishEntity entity3 = new TestdataLavishEntity("MyEntity 3", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity3);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                        .ifExists(TestdataLavishEntityGroup.class,
                                equal(TestdataLavishEntity::getEntityGroup, Function.identity()))
                        .groupBy(TestdataLavishEntity::getEntityGroup, count())
                        .penalize(SimpleScore.ONE, (groupA, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-2, solution.getFirstEntityGroup(), 2),
                assertMatchWithScore(-2, entityGroup1, 2));

        // Incremental
        scoreDirector.beforeProblemFactRemoved(entityGroup1);
        solution.getEntityGroupList().remove(entityGroup1);
        scoreDirector.afterProblemFactRemoved(entityGroup1);
        assertScore(scoreDirector,
                assertMatchWithScore(-2, solution.getFirstEntityGroup(), 2));
    }

    @TestTemplate
    void groupByAfterExistsBi() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(1, 1, 1, 1);
        TestdataLavishEntityGroup entityGroup1 = new TestdataLavishEntityGroup("MyEntityGroup");
        solution.getEntityGroupList().add(entityGroup1);
        TestdataLavishEntity entity1 = new TestdataLavishEntity("MyEntity 1", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity1);
        TestdataLavishEntity entity2 = new TestdataLavishEntity("MyEntity 2", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity2);
        TestdataLavishEntity entity3 = new TestdataLavishEntity("MyEntity 3", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity3);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEachUniquePair(TestdataLavishEntity.class)
                        .ifExists(TestdataLavishEntityGroup.class,
                                equal((e1, e2) -> e1.getEntityGroup(), Function.identity()))
                        .groupBy((e1, e2) -> e1.getEntityGroup(), countBi())
                        .penalize(SimpleScore.ONE, (groupA, count) -> count)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-3, solution.getFirstEntityGroup(), 3),
                assertMatchWithScore(-3, entityGroup1, 3));

        // Incremental
        scoreDirector.beforeProblemFactRemoved(entityGroup1);
        solution.getEntityGroupList().remove(entityGroup1);
        scoreDirector.afterProblemFactRemoved(entityGroup1);
        assertScore(scoreDirector,
                assertMatchWithScore(-3, solution.getFirstEntityGroup(), 3));
    }

    @TestTemplate
    void filteredFromUniquePair() {
        TestdataLavishSolution solution = TestdataLavishSolution.generateSolution(1, 1, 1, 1);
        TestdataLavishEntityGroup entityGroup1 = new TestdataLavishEntityGroup("MyEntityGroup");
        solution.getEntityGroupList().add(entityGroup1);
        TestdataLavishEntity entity1 = new TestdataLavishEntity("MyEntity 1", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity1);
        TestdataLavishEntity entity2 = new TestdataLavishEntity("MyEntity 2", entityGroup1, solution.getFirstValue());
        solution.getEntityList().add(entity2);
        TestdataLavishEntity entity3 = new TestdataLavishEntity("MyEntity 3", solution.getFirstEntityGroup(),
                solution.getFirstValue());
        solution.getEntityList().add(entity3);

        InnerScoreDirector<TestdataLavishSolution, SimpleScore> scoreDirector =
                buildScoreDirector(factory -> factory.forEachUniquePair(TestdataLavishEntity.class,
                        Joiners.equal(TestdataLavishEntity::getEntityGroup),
                        Joiners.filtering((e1, e2) -> !e1.getCode().contains("My"))) // Filtering() caused PLANNER-2139.
                        .penalize(SimpleScore.ONE)
                        .asConstraint(TEST_CONSTRAINT_NAME));

        // From scratch
        scoreDirector.setWorkingSolution(solution);
        assertScore(scoreDirector,
                assertMatchWithScore(-1, entity3, solution.getFirstEntity()));

        // Incremental
        scoreDirector.beforeProblemFactRemoved(entity3);
        solution.getEntityList().remove(entity3);
        scoreDirector.afterProblemFactRemoved(entity3);
        assertScore(scoreDirector);
    }

    @TestTemplate
    void groupByThenJoinThenGroupBy() { // PLANNER-2270
        assertThatCode(() -> buildScoreDirector(factory -> factory.forEach(TestdataLavishEntity.class)
                .groupBy(TestdataLavishEntity::getEntityGroup, TestdataLavishEntity::getValue)
                .join(TestdataLavishEntity.class)
                .groupBy((group, value, entity) -> group,
                        (group, value, entity) -> entity,
                        sum((group, count, entity) -> 1))
                .penalize(SimpleScore.ONE)
                .asConstraint(TEST_CONSTRAINT_NAME))).doesNotThrowAnyException();
    }

}