proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/swing/impl/SwingUtils.java
|
SwingUtils
|
configureNimbusToTangoColors
|
class SwingUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(SwingUtils.class);
private static final UIDefaults smallButtonUIDefaults;
static {
smallButtonUIDefaults = new UIDefaults();
smallButtonUIDefaults.put("Button.contentMargins", new Insets(5, 5, 5, 5));
}
public static void fixateLookAndFeel() {
configureNimbusToTangoColors();
configureLookAndFeel("Nimbus");
// increaseDefaultFont(1.5F);
}
protected static void configureNimbusToTangoColors() {<FILL_FUNCTION_BODY>}
protected static void configureLookAndFeel(String lookAndFeelName) {
Exception lookAndFeelException;
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (lookAndFeelName.equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
}
}
lookAndFeelException = null;
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
lookAndFeelException = e;
}
if (lookAndFeelException != null) {
LOGGER.warn("Could not switch to lookAndFeel ({}). Layout might be incorrect.", lookAndFeelName,
lookAndFeelException);
}
}
public static JButton makeSmallButton(JButton button) {
button.setMargin(new Insets(0, 0, 0, 0));
button.putClientProperty("Nimbus.Overrides", smallButtonUIDefaults);
return button;
}
private SwingUtils() {
}
}
|
UIManager.put("control", ALUMINIUM_1);
UIManager.put("info", BUTTER_1);
UIManager.put("nimbusAlertYellow", BUTTER_2);
UIManager.put("nimbusBase", SKY_BLUE_3);
UIManager.put("nimbusDisabledText", ALUMINIUM_4);
UIManager.put("nimbusFocus", SKY_BLUE_1);
UIManager.put("nimbusGreen", CHAMELEON_1);
UIManager.put("nimbusInfoBlue", SKY_BLUE_2);
UIManager.put("nimbusLightBackground", Color.WHITE);
UIManager.put("nimbusOrange", ORANGE_2);
UIManager.put("nimbusRed", SCARLET_2);
UIManager.put("nimbusSelectedText", Color.WHITE);
UIManager.put("nimbusSelectionBackground", SKY_BLUE_2);
UIManager.put("text", Color.BLACK);
UIManager.put("activeCaption", ALUMINIUM_3);
UIManager.put("background", ALUMINIUM_2);
UIManager.put("controlDkShadow", ALUMINIUM_4);
UIManager.put("controlHighlight", ALUMINIUM_1);
UIManager.put("controlLHighlight", ALUMINIUM_6);
UIManager.put("controlShadow", ALUMINIUM_2);
UIManager.put("controlText", Color.BLACK);
UIManager.put("desktop", SKY_BLUE_1);
UIManager.put("inactiveCaption", ALUMINIUM_3);
UIManager.put("infoText", Color.BLACK);
UIManager.put("menu", ALUMINIUM_1);
UIManager.put("menuText", Color.BLACK);
UIManager.put("nimbusBlueGrey", ALUMINIUM_1);
UIManager.put("nimbusBorder", ALUMINIUM_4);
UIManager.put("nimbusSelection", SKY_BLUE_2);
UIManager.put("scrollbar", ALUMINIUM_2);
UIManager.put("textBackground", SKY_BLUE_1);
UIManager.put("textForeground", Color.BLACK);
UIManager.put("textHighlight", SKY_BLUE_3);
UIManager.put("textHighlightText", Color.WHITE);
UIManager.put("textInactiveText", ALUMINIUM_4);
| 487
| 720
| 1,207
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-benchmark/src/main/java/org/optaplanner/swing/impl/TangoColorFactory.java
|
TangoColorFactory
|
nextColor
|
class TangoColorFactory {
public static final Color CHAMELEON_1 = new Color(138, 226, 52);
public static final Color CHAMELEON_2 = new Color(115, 210, 22);
public static final Color CHAMELEON_3 = new Color(78, 154, 6);
public static final Color BUTTER_1 = new Color(252, 233, 79);
public static final Color BUTTER_2 = new Color(237, 212, 0);
public static final Color BUTTER_3 = new Color(196, 160, 0);
public static final Color SKY_BLUE_1 = new Color(114, 159, 207);
public static final Color SKY_BLUE_2 = new Color(52, 101, 164);
public static final Color SKY_BLUE_3 = new Color(32, 74, 135);
public static final Color CHOCOLATE_1 = new Color(233, 185, 110);
public static final Color CHOCOLATE_2 = new Color(193, 125, 17);
public static final Color CHOCOLATE_3 = new Color(143, 89, 2);
public static final Color MAGENTA = new Color(255, 0, 255);
public static final Color PLUM_1 = new Color(173, 127, 168);
public static final Color PLUM_2 = new Color(117, 80, 123);
public static final Color PLUM_3 = new Color(92, 53, 102);
public static final Color SCARLET_1 = new Color(239, 41, 41);
public static final Color SCARLET_2 = new Color(204, 0, 0);
public static final Color SCARLET_3 = new Color(164, 0, 0);
public static final Color ORANGE_1 = new Color(252, 175, 62);
public static final Color ORANGE_2 = new Color(245, 121, 0);
public static final Color ORANGE_3 = new Color(206, 92, 0);
public static final Color ALUMINIUM_1 = new Color(238, 238, 236);
public static final Color ALUMINIUM_2 = new Color(211, 215, 207);
public static final Color ALUMINIUM_3 = new Color(186, 189, 182);
public static final Color ALUMINIUM_4 = new Color(136, 138, 133);
public static final Color ALUMINIUM_5 = new Color(85, 87, 83);
public static final Color ALUMINIUM_6 = new Color(46, 52, 54);
// Scarlet and orange are reserved for hard and soft constraints
public static final List<Color> SEQUENCE_1 = unmodifiableList(asList(TangoColorFactory.CHAMELEON_1,
TangoColorFactory.BUTTER_1, TangoColorFactory.SKY_BLUE_1, TangoColorFactory.CHOCOLATE_1,
TangoColorFactory.PLUM_1));
public static final List<Color> SEQUENCE_2 = unmodifiableList(asList(TangoColorFactory.CHAMELEON_2,
TangoColorFactory.BUTTER_2, TangoColorFactory.SKY_BLUE_2, TangoColorFactory.CHOCOLATE_2,
TangoColorFactory.PLUM_2));
public static final List<Color> SEQUENCE_3 = unmodifiableList(asList(TangoColorFactory.CHAMELEON_3,
TangoColorFactory.BUTTER_3, TangoColorFactory.SKY_BLUE_3, TangoColorFactory.CHOCOLATE_3,
TangoColorFactory.PLUM_3));
public static final Stroke THICK_STROKE = new BasicStroke(2.0f);
public static final Stroke NORMAL_STROKE = new BasicStroke();
public static final Stroke FAT_DASHED_STROKE = new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 7.0f, 3.0f }, 0.0f);
public static final Stroke DASHED_STROKE = new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f, 4.0f }, 0.0f);
public static final Stroke LIGHT_DASHED_STROKE = new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 3.0f, 7.0f }, 0.0f);
public static Color buildPercentageColor(Color floorColor, Color ceilColor, double shadePercentage) {
return new Color(
floorColor.getRed() + (int) (shadePercentage * (ceilColor.getRed() - floorColor.getRed())),
floorColor.getGreen() + (int) (shadePercentage * (ceilColor.getGreen() - floorColor.getGreen())),
floorColor.getBlue() + (int) (shadePercentage * (ceilColor.getBlue() - floorColor.getBlue())));
}
private Map<Object, Color> colorMap;
private int nextColorCount;
public TangoColorFactory() {
colorMap = new HashMap<>();
nextColorCount = 0;
}
public Color pickColor(Object object) {
return colorMap.computeIfAbsent(object, k -> nextColor());
}
private Color nextColor() {<FILL_FUNCTION_BODY>}
}
|
Color color;
int colorIndex = nextColorCount % SEQUENCE_1.size();
int shadeIndex = nextColorCount / SEQUENCE_1.size();
if (shadeIndex == 0) {
color = SEQUENCE_1.get(colorIndex);
} else if (shadeIndex == 1) {
color = SEQUENCE_2.get(colorIndex);
} else if (shadeIndex == 2) {
color = SEQUENCE_3.get(colorIndex);
} else {
shadeIndex -= 3;
Color floorColor;
Color ceilColor;
if (shadeIndex % 2 == 0) {
floorColor = SEQUENCE_2.get(colorIndex);
ceilColor = SEQUENCE_1.get(colorIndex);
} else {
floorColor = SEQUENCE_3.get(colorIndex);
ceilColor = SEQUENCE_2.get(colorIndex);
}
int base = (shadeIndex / 2) + 1;
int divisor = 2;
while (base >= divisor) {
divisor *= 2;
}
base = (base * 2) - divisor + 1;
double shadePercentage = base / (double) divisor;
color = buildPercentageColor(floorColor, ceilColor, shadePercentage);
}
nextColorCount++;
return color;
| 1,588
| 354
| 1,942
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/app/OptaPlannerExamplesApp.java
|
OptaPlannerExamplesApp
|
createDescriptionPanel
|
class OptaPlannerExamplesApp extends JFrame {
/**
* Supported system properties: {@link CommonApp#DATA_DIR_SYSTEM_PROPERTY}.
*
* @param args never null
*/
public static void main(String[] args) {
CommonApp.prepareSwingEnvironment();
OptaPlannerExamplesApp optaPlannerExamplesApp = new OptaPlannerExamplesApp();
optaPlannerExamplesApp.pack();
optaPlannerExamplesApp.setLocationRelativeTo(null);
optaPlannerExamplesApp.setVisible(true);
}
private static String determineOptaPlannerExamplesVersion() {
String optaPlannerExamplesVersion = OptaPlannerExamplesApp.class.getPackage().getImplementationVersion();
if (optaPlannerExamplesVersion == null) {
optaPlannerExamplesVersion = "";
}
return optaPlannerExamplesVersion;
}
private JTextArea descriptionTextArea;
public OptaPlannerExamplesApp() {
super("OptaPlanner examples " + determineOptaPlannerExamplesVersion());
setIconImage(SolverAndPersistenceFrame.OPTAPLANNER_ICON.getImage());
setContentPane(createContentPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel titleLabel = new JLabel("Which example do you want to see?", JLabel.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(20.0f));
contentPane.add(titleLabel, BorderLayout.NORTH);
JScrollPane examplesScrollPane = new JScrollPane(createExamplesPanel());
examplesScrollPane.getHorizontalScrollBar().setUnitIncrement(20);
examplesScrollPane.getVerticalScrollBar().setUnitIncrement(20);
examplesScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.add(examplesScrollPane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new BorderLayout(5, 5));
bottomPanel.add(createDescriptionPanel(), BorderLayout.CENTER);
bottomPanel.add(createExtraPanel(), BorderLayout.EAST);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
return contentPane;
}
private JPanel createExamplesPanel() {
JPanel panel = new JPanel(new GridLayout(0, 4, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Stream.of(new VehicleRoutingApp(),
new NurseRosteringApp(),
new TaskAssigningApp(),
new CloudBalancingApp(),
new ConferenceSchedulingApp(),
new PatientAdmissionScheduleApp(),
new MachineReassignmentApp(),
new CurriculumCourseApp(),
new ProjectJobSchedulingApp(),
new ExaminationApp(),
new MeetingSchedulingApp(),
new TravelingTournamentApp(),
new TennisApp(),
new FlightCrewSchedulingApp(),
new TspApp(), new NQueensApp())
.map(this::createExampleButton)
.forEach(panel::add);
return panel;
}
private JButton createExampleButton(final CommonApp commonApp) {
String iconResource = commonApp.getIconResource();
Icon icon = iconResource == null ? new EmptyIcon() : new ImageIcon(getClass().getResource(iconResource));
JButton button = new JButton(new AbstractAction(commonApp.getName(), icon) {
@Override
public void actionPerformed(ActionEvent e) {
commonApp.init(OptaPlannerExamplesApp.this, false);
}
});
button.setHorizontalAlignment(JButton.LEFT);
button.setHorizontalTextPosition(JButton.RIGHT);
button.setVerticalTextPosition(JButton.CENTER);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
descriptionTextArea.setText(commonApp.getDescription());
}
@Override
public void mouseExited(MouseEvent e) {
descriptionTextArea.setText("");
}
});
return button;
}
private JPanel createDescriptionPanel() {<FILL_FUNCTION_BODY>}
private JPanel createExtraPanel() {
JPanel extraPanel = new JPanel(new GridLayout(0, 1, 5, 5));
extraPanel.add(new JPanel());
Action homepageAction = new OpenBrowserAction("www.optaplanner.org", "https://www.optaplanner.org");
extraPanel.add(new JButton(homepageAction));
Action documentationAction = new OpenBrowserAction("Documentation",
"https://www.optaplanner.org/learn/documentation.html");
extraPanel.add(new JButton(documentationAction));
return extraPanel;
}
private static class EmptyIcon implements Icon {
@Override
public int getIconWidth() {
return 64;
}
@Override
public int getIconHeight() {
return 64;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
// Do nothing
}
}
}
|
JPanel descriptionPanel = new JPanel(new BorderLayout(2, 2));
descriptionPanel.add(new JLabel("Description"), BorderLayout.NORTH);
descriptionTextArea = new JTextArea(8, 65);
descriptionTextArea.setEditable(false);
descriptionTextArea.setLineWrap(true);
descriptionTextArea.setWrapStyleWord(true);
descriptionPanel.add(new JScrollPane(descriptionTextArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
return descriptionPanel;
| 1,434
| 167
| 1,601
|
<methods>public void <init>() throws java.awt.HeadlessException,public void <init>(java.awt.GraphicsConfiguration) ,public void <init>(java.lang.String) throws java.awt.HeadlessException,public void <init>(java.lang.String, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setIconImage(java.awt.Image) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/app/CloudBalancingHelloWorld.java
|
CloudBalancingHelloWorld
|
main
|
class CloudBalancingHelloWorld {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
public static String toDisplayString(CloudBalance cloudBalance) {
StringBuilder displayString = new StringBuilder();
for (CloudProcess process : cloudBalance.getProcessList()) {
CloudComputer computer = process.getComputer();
displayString.append(" ").append(process.getLabel()).append(" -> ")
.append(computer == null ? null : computer.getLabel()).append("\n");
}
return displayString.toString();
}
}
|
// Build the Solver
SolverFactory<CloudBalance> solverFactory = SolverFactory.create(new SolverConfig()
.withSolutionClass(CloudBalance.class)
.withEntityClasses(CloudProcess.class)
.withConstraintProviderClass(CloudBalancingConstraintProvider.class)
.withTerminationSpentLimit(Duration.ofMinutes(2)));
Solver<CloudBalance> solver = solverFactory.buildSolver();
// Load a problem with 400 computers and 1200 processes
CloudBalance unsolvedCloudBalance = new CloudBalancingGenerator().createCloudBalance(400, 1200);
// Solve the problem
CloudBalance solvedCloudBalance = solver.solve(unsolvedCloudBalance);
// Display the result
System.out.println("\nSolved cloudBalance with 400 computers and 1200 processes:\n"
+ toDisplayString(solvedCloudBalance));
| 152
| 249
| 401
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/benchmark/CloudBalancingBenchmarkHelloWorld.java
|
CloudBalancingBenchmarkHelloWorld
|
runAdvancedBenchmark
|
class CloudBalancingBenchmarkHelloWorld {
public static void main(String[] args) {
List<String> argList = Arrays.asList(args);
boolean advanced = argList.contains("--advanced");
if (!advanced) {
runBasicBenchmark();
} else {
boolean aggregator = argList.contains("--aggregator");
runAdvancedBenchmark(aggregator);
}
}
/**
* Basic (no benchmark XML): just benchmark the solver config
*/
public static void runBasicBenchmark() {
// Build the PlannerBenchmark
PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.createFromSolverConfigXmlResource(
"org/optaplanner/examples/cloudbalancing/cloudBalancingSolverConfig.xml");
CloudBalancingGenerator generator = new CloudBalancingGenerator();
PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark(
generator.createCloudBalance(200, 600),
generator.createCloudBalance(400, 1200));
// Benchmark the problem and show it
benchmark.benchmarkAndShowReportInBrowser();
}
/**
* Advanced (benchmark XML): benchmark multiple solver configurations
*/
public static void runAdvancedBenchmark(boolean aggregator) {<FILL_FUNCTION_BODY>}
}
|
// Build the PlannerBenchmark
PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/optional/benchmark/cloudBalancingBenchmarkConfig.xml");
PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark();
// Benchmark the problem and show it
benchmark.benchmarkAndShowReportInBrowser();
// Show aggregator to aggregate multiple reports
if (aggregator) {
BenchmarkAggregatorFrame.createAndDisplayFromXmlResource(
"org/optaplanner/examples/cloudbalancing/optional/benchmark/cloudBalancingBenchmarkConfig.xml");
}
| 357
| 180
| 537
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/partitioner/CloudBalancePartitioner.java
|
CloudBalancePartitioner
|
splitWorkingSolution
|
class CloudBalancePartitioner implements SolutionPartitioner<CloudBalance> {
private int partCount = 4;
private int minimumProcessListSize = 25;
@SuppressWarnings("unused")
public void setPartCount(int partCount) {
this.partCount = partCount;
}
@SuppressWarnings("unused")
public void setMinimumProcessListSize(int minimumProcessListSize) {
this.minimumProcessListSize = minimumProcessListSize;
}
@Override
public List<CloudBalance> splitWorkingSolution(ScoreDirector<CloudBalance> scoreDirector, Integer runnablePartThreadLimit) {<FILL_FUNCTION_BODY>}
}
|
CloudBalance originalSolution = scoreDirector.getWorkingSolution();
List<CloudComputer> originalComputerList = originalSolution.getComputerList();
List<CloudProcess> originalProcessList = originalSolution.getProcessList();
int partCount = this.partCount;
if (originalProcessList.size() / partCount < minimumProcessListSize) {
partCount = originalProcessList.size() / minimumProcessListSize;
}
List<CloudBalance> partList = new ArrayList<>(partCount);
for (int i = 0; i < partCount; i++) {
CloudBalance partSolution = new CloudBalance(originalSolution.getId(),
new ArrayList<>(originalComputerList.size() / partCount + 1),
new ArrayList<>(originalProcessList.size() / partCount + 1));
partList.add(partSolution);
}
int partIndex = 0;
Map<Long, Pair<Integer, CloudComputer>> idToPartIndexAndComputerMap = new HashMap<>(originalComputerList.size());
for (CloudComputer originalComputer : originalComputerList) {
CloudBalance part = partList.get(partIndex);
CloudComputer computer = new CloudComputer(
originalComputer.getId(),
originalComputer.getCpuPower(), originalComputer.getMemory(),
originalComputer.getNetworkBandwidth(), originalComputer.getCost());
part.getComputerList().add(computer);
idToPartIndexAndComputerMap.put(computer.getId(), Pair.of(partIndex, computer));
partIndex = (partIndex + 1) % partList.size();
}
partIndex = 0;
for (CloudProcess originalProcess : originalProcessList) {
CloudBalance part = partList.get(partIndex);
CloudProcess process = new CloudProcess(
originalProcess.getId(),
originalProcess.getRequiredCpuPower(), originalProcess.getRequiredMemory(),
originalProcess.getRequiredNetworkBandwidth());
part.getProcessList().add(process);
if (originalProcess.getComputer() != null) {
Pair<Integer, CloudComputer> partIndexAndComputer = idToPartIndexAndComputerMap.get(
originalProcess.getComputer().getId());
if (partIndexAndComputer == null) {
throw new IllegalStateException("The initialized process (" + originalProcess
+ ") has a computer (" + originalProcess.getComputer()
+ ") which doesn't exist in the originalSolution (" + originalSolution + ").");
}
if (partIndex != partIndexAndComputer.getKey().intValue()) {
throw new IllegalStateException("The initialized process (" + originalProcess
+ ") with partIndex (" + partIndex
+ ") has a computer (" + originalProcess.getComputer()
+ ") which belongs to another partIndex (" + partIndexAndComputer.getKey() + ").");
}
process.setComputer(partIndexAndComputer.getValue());
}
partIndex = (partIndex + 1) % partList.size();
}
return partList;
| 183
| 774
| 957
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/score/CloudBalancingEasyScoreCalculator.java
|
CloudBalancingEasyScoreCalculator
|
calculateScore
|
class CloudBalancingEasyScoreCalculator implements EasyScoreCalculator<CloudBalance, HardSoftScore> {
/**
* A very simple implementation. The double loop can easily be removed by using Maps as shown in
* {@link CloudBalancingMapBasedEasyScoreCalculator#calculateScore(CloudBalance)}.
*/
@Override
public HardSoftScore calculateScore(CloudBalance cloudBalance) {<FILL_FUNCTION_BODY>}
}
|
int hardScore = 0;
int softScore = 0;
for (CloudComputer computer : cloudBalance.getComputerList()) {
int cpuPowerUsage = 0;
int memoryUsage = 0;
int networkBandwidthUsage = 0;
boolean used = false;
// Calculate usage
for (CloudProcess process : cloudBalance.getProcessList()) {
if (computer.equals(process.getComputer())) {
cpuPowerUsage += process.getRequiredCpuPower();
memoryUsage += process.getRequiredMemory();
networkBandwidthUsage += process.getRequiredNetworkBandwidth();
used = true;
}
}
// Hard constraints
int cpuPowerAvailable = computer.getCpuPower() - cpuPowerUsage;
if (cpuPowerAvailable < 0) {
hardScore += cpuPowerAvailable;
}
int memoryAvailable = computer.getMemory() - memoryUsage;
if (memoryAvailable < 0) {
hardScore += memoryAvailable;
}
int networkBandwidthAvailable = computer.getNetworkBandwidth() - networkBandwidthUsage;
if (networkBandwidthAvailable < 0) {
hardScore += networkBandwidthAvailable;
}
// Soft constraints
if (used) {
softScore -= computer.getCost();
}
}
return HardSoftScore.of(hardScore, softScore);
| 114
| 352
| 466
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/solver/move/CloudComputerChangeMove.java
|
CloudComputerChangeMove
|
equals
|
class CloudComputerChangeMove extends AbstractMove<CloudBalance> {
private CloudProcess cloudProcess;
private CloudComputer toCloudComputer;
public CloudComputerChangeMove(CloudProcess cloudProcess, CloudComputer toCloudComputer) {
this.cloudProcess = cloudProcess;
this.toCloudComputer = toCloudComputer;
}
@Override
public boolean isMoveDoable(ScoreDirector<CloudBalance> scoreDirector) {
return !Objects.equals(cloudProcess.getComputer(), toCloudComputer);
}
@Override
public CloudComputerChangeMove createUndoMove(ScoreDirector<CloudBalance> scoreDirector) {
return new CloudComputerChangeMove(cloudProcess, cloudProcess.getComputer());
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<CloudBalance> scoreDirector) {
scoreDirector.beforeVariableChanged(cloudProcess, "computer");
cloudProcess.setComputer(toCloudComputer);
scoreDirector.afterVariableChanged(cloudProcess, "computer");
}
@Override
public CloudComputerChangeMove rebase(ScoreDirector<CloudBalance> destinationScoreDirector) {
return new CloudComputerChangeMove(destinationScoreDirector.lookUpWorkingObject(cloudProcess),
destinationScoreDirector.lookUpWorkingObject(toCloudComputer));
}
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + CloudProcess.class.getSimpleName() + ".computer)";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Collections.singletonList(cloudProcess);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toCloudComputer);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(cloudProcess, toCloudComputer);
}
@Override
public String toString() {
return cloudProcess + " {" + cloudProcess.getComputer() + " -> " + toCloudComputer + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CloudComputerChangeMove other = (CloudComputerChangeMove) o;
return Objects.equals(cloudProcess, other.cloudProcess) &&
Objects.equals(toCloudComputer, other.toCloudComputer);
| 581
| 102
| 683
|
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.cloudbalancing.domain.CloudBalance> doMove(ScoreDirector<org.optaplanner.examples.cloudbalancing.domain.CloudBalance>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.cloudbalancing.domain.CloudBalance>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/solver/move/CloudProcessSwapMove.java
|
CloudProcessSwapMove
|
equals
|
class CloudProcessSwapMove extends AbstractMove<CloudBalance> {
private CloudProcess leftCloudProcess;
private CloudProcess rightCloudProcess;
public CloudProcessSwapMove(CloudProcess leftCloudProcess, CloudProcess rightCloudProcess) {
this.leftCloudProcess = leftCloudProcess;
this.rightCloudProcess = rightCloudProcess;
}
@Override
public boolean isMoveDoable(ScoreDirector<CloudBalance> scoreDirector) {
return !Objects.equals(leftCloudProcess.getComputer(), rightCloudProcess.getComputer());
}
@Override
public CloudProcessSwapMove createUndoMove(ScoreDirector<CloudBalance> scoreDirector) {
return new CloudProcessSwapMove(rightCloudProcess, leftCloudProcess);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<CloudBalance> scoreDirector) {
CloudComputer oldLeftCloudComputer = leftCloudProcess.getComputer();
CloudComputer oldRightCloudComputer = rightCloudProcess.getComputer();
scoreDirector.beforeVariableChanged(leftCloudProcess, "computer");
leftCloudProcess.setComputer(oldRightCloudComputer);
scoreDirector.afterVariableChanged(leftCloudProcess, "computer");
scoreDirector.beforeVariableChanged(rightCloudProcess, "computer");
rightCloudProcess.setComputer(oldLeftCloudComputer);
scoreDirector.afterVariableChanged(rightCloudProcess, "computer");
}
@Override
public CloudProcessSwapMove rebase(ScoreDirector<CloudBalance> destinationScoreDirector) {
return new CloudProcessSwapMove(destinationScoreDirector.lookUpWorkingObject(leftCloudProcess),
destinationScoreDirector.lookUpWorkingObject(rightCloudProcess));
}
@Override
public String getSimpleMoveTypeDescription() {
return getClass().getSimpleName() + "(" + CloudProcess.class.getSimpleName() + ".computer)";
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Arrays.asList(leftCloudProcess, rightCloudProcess);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(leftCloudProcess.getComputer(), rightCloudProcess.getComputer());
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(leftCloudProcess, rightCloudProcess);
}
@Override
public String toString() {
return leftCloudProcess + " {" + leftCloudProcess.getComputer() + "} <-> "
+ rightCloudProcess + " {" + rightCloudProcess.getComputer() + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CloudProcessSwapMove other = (CloudProcessSwapMove) o;
return Objects.equals(leftCloudProcess, other.leftCloudProcess) &&
Objects.equals(rightCloudProcess, other.rightCloudProcess);
| 706
| 102
| 808
|
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.cloudbalancing.domain.CloudBalance> doMove(ScoreDirector<org.optaplanner.examples.cloudbalancing.domain.CloudBalance>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.cloudbalancing.domain.CloudBalance>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/solver/move/CloudProcessSwapMoveFactory.java
|
CloudProcessSwapMoveFactory
|
createMoveList
|
class CloudProcessSwapMoveFactory implements MoveListFactory<CloudBalance> {
@Override
public List<CloudProcessSwapMove> createMoveList(CloudBalance cloudBalance) {<FILL_FUNCTION_BODY>}
}
|
List<CloudProcess> cloudProcessList = cloudBalance.getProcessList();
List<CloudProcessSwapMove> moveList = new ArrayList<>();
for (ListIterator<CloudProcess> leftIt = cloudProcessList.listIterator(); leftIt.hasNext();) {
CloudProcess leftCloudProcess = leftIt.next();
for (ListIterator<CloudProcess> rightIt = cloudProcessList.listIterator(leftIt.nextIndex()); rightIt.hasNext();) {
CloudProcess rightCloudProcess = rightIt.next();
moveList.add(new CloudProcessSwapMove(leftCloudProcess, rightCloudProcess));
}
}
return moveList;
| 61
| 161
| 222
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/score/CloudBalancingConstraintProvider.java
|
CloudBalancingConstraintProvider
|
requiredCpuPowerTotal
|
class CloudBalancingConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
requiredCpuPowerTotal(constraintFactory),
requiredMemoryTotal(constraintFactory),
requiredNetworkBandwidthTotal(constraintFactory),
computerCost(constraintFactory)
};
}
// ************************************************************************
// Hard constraints
// ************************************************************************
Constraint requiredCpuPowerTotal(ConstraintFactory constraintFactory) {<FILL_FUNCTION_BODY>}
Constraint requiredMemoryTotal(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(CloudProcess.class)
.groupBy(CloudProcess::getComputer, sum(CloudProcess::getRequiredMemory))
.filter((computer, requiredMemory) -> requiredMemory > computer.getMemory())
.penalize(HardSoftScore.ONE_HARD,
(computer, requiredMemory) -> requiredMemory - computer.getMemory())
.asConstraint("requiredMemoryTotal");
}
Constraint requiredNetworkBandwidthTotal(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(CloudProcess.class)
.groupBy(CloudProcess::getComputer, sum(CloudProcess::getRequiredNetworkBandwidth))
.filter((computer, requiredNetworkBandwidth) -> requiredNetworkBandwidth > computer.getNetworkBandwidth())
.penalize(HardSoftScore.ONE_HARD,
(computer, requiredNetworkBandwidth) -> requiredNetworkBandwidth - computer.getNetworkBandwidth())
.asConstraint("requiredNetworkBandwidthTotal");
}
// ************************************************************************
// Soft constraints
// ************************************************************************
Constraint computerCost(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(CloudComputer.class)
.ifExists(CloudProcess.class, equal(Function.identity(), CloudProcess::getComputer))
.penalize(HardSoftScore.ONE_SOFT, CloudComputer::getCost)
.asConstraint("computerCost");
}
}
|
return constraintFactory.forEach(CloudProcess.class)
.groupBy(CloudProcess::getComputer, sum(CloudProcess::getRequiredCpuPower))
.filter((computer, requiredCpuPower) -> requiredCpuPower > computer.getCpuPower())
.penalize(HardSoftScore.ONE_HARD,
(computer, requiredCpuPower) -> requiredCpuPower - computer.getCpuPower())
.asConstraint("requiredCpuPowerTotal");
| 512
| 120
| 632
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/swingui/realtime/AddProcessProblemChange.java
|
AddProcessProblemChange
|
doChange
|
class AddProcessProblemChange implements ProblemChange<CloudBalance> {
private final LongFunction<CloudProcess> generator;
public AddProcessProblemChange(LongFunction<CloudProcess> generator) {
this.generator = generator;
}
@Override
public void doChange(CloudBalance cloudBalance, ProblemChangeDirector problemChangeDirector) {<FILL_FUNCTION_BODY>}
}
|
// Set a unique id on the new process
long nextProcessId = 0L;
for (CloudProcess otherProcess : cloudBalance.getProcessList()) {
if (nextProcessId <= otherProcess.getId()) {
nextProcessId = otherProcess.getId() + 1L;
}
}
CloudProcess process = generator.apply(nextProcessId);
// A SolutionCloner clones planning entity lists (such as processList), so no need to clone the processList here
// Add the planning entity itself
problemChangeDirector.addEntity(process, cloudBalance.getProcessList()::add);
| 103
| 150
| 253
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/swingui/realtime/DeleteComputerProblemChange.java
|
DeleteComputerProblemChange
|
doChange
|
class DeleteComputerProblemChange implements ProblemChange<CloudBalance> {
private final CloudComputer computer;
public DeleteComputerProblemChange(CloudComputer computer) {
this.computer = computer;
}
@Override
public void doChange(CloudBalance cloudBalance, ProblemChangeDirector problemChangeDirector) {<FILL_FUNCTION_BODY>}
}
|
problemChangeDirector.lookUpWorkingObject(computer)
.ifPresentOrElse(workingComputer -> {
// First remove the problem fact from all planning entities that use it
for (CloudProcess process : cloudBalance.getProcessList()) {
if (process.getComputer() == workingComputer) {
problemChangeDirector.changeVariable(process, "computer",
workingProcess -> workingProcess.setComputer(null));
}
}
// A SolutionCloner does not clone problem fact lists (such as computerList)
// Shallow clone the computerList so only workingSolution is affected, not bestSolution or guiSolution
ArrayList<CloudComputer> computerList = new ArrayList<>(cloudBalance.getComputerList());
cloudBalance.setComputerList(computerList);
// Remove the problem fact itself
problemChangeDirector.removeProblemFact(workingComputer, computerList::remove);
}, () -> {
// The computer has already been deleted (the UI asked to changed the same computer twice).
});
| 100
| 263
| 363
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/swingui/realtime/DeleteProcessProblemChange.java
|
DeleteProcessProblemChange
|
doChange
|
class DeleteProcessProblemChange implements ProblemChange<CloudBalance> {
private final CloudProcess process;
public DeleteProcessProblemChange(CloudProcess process) {
this.process = process;
}
@Override
public void doChange(CloudBalance cloudBalance, ProblemChangeDirector problemChangeDirector) {<FILL_FUNCTION_BODY>}
}
|
// A SolutionCloner clones planning entity lists (such as processList), so no need to clone the processList here
problemChangeDirector.lookUpWorkingObject(process)
.ifPresentOrElse(workingProcess -> {
// Remove the planning entity itself
problemChangeDirector.removeEntity(workingProcess, cloudBalance.getProcessList()::remove);
}, () -> {
// The process has already been deleted (the UI asked to changed the same process twice).
});
| 95
| 122
| 217
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/business/AlphaNumericStringComparator.java
|
AlphaNumericStringComparator
|
compare
|
class AlphaNumericStringComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {<FILL_FUNCTION_BODY>}
private boolean isDigit(char aChar) {
return aChar >= '0' && aChar <= '9';
}
}
|
char[] aChars = a.toCharArray();
char[] bChars = b.toCharArray();
int aIndex = 0;
int bIndex = 0;
while (true) {
if (aIndex >= aChars.length) {
if (bIndex >= bChars.length) {
return 0;
} else {
return -1;
}
} else if (bIndex >= bChars.length) {
return 1;
}
char aChar = aChars[aIndex];
char bChar = bChars[bIndex];
if (isDigit(aChar) && isDigit(bChar)) {
int aIndexTo = aIndex + 1;
while (aIndexTo < aChars.length && isDigit(aChars[aIndexTo])) {
aIndexTo++;
}
int bIndexTo = bIndex + 1;
while (bIndexTo < bChars.length && isDigit(bChars[bIndexTo])) {
bIndexTo++;
}
int aNumber = Integer.parseInt(new String(aChars, aIndex, aIndexTo - aIndex));
int bNumber = Integer.parseInt(new String(bChars, bIndex, bIndexTo - bIndex));
if (aNumber < bNumber) {
return -1;
} else if (aNumber > bNumber) {
return 1;
}
aIndex = aIndexTo;
bIndex = bIndexTo;
} else {
if (aChar < bChar) {
return -1;
} else if (aChar > bChar) {
return 1;
}
aIndex++;
bIndex++;
}
}
| 84
| 446
| 530
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/BreakImpl.java
|
BreakImpl
|
toString
|
class BreakImpl<Value_, Difference_ extends Comparable<Difference_>>
implements Break<Value_, Difference_> {
private Sequence<Value_, Difference_> previousSequence;
private Sequence<Value_, Difference_> nextSequence;
private Difference_ length;
BreakImpl(Sequence<Value_, Difference_> previousSequence, Sequence<Value_, Difference_> nextSequence,
Difference_ length) {
this.previousSequence = previousSequence;
this.nextSequence = nextSequence;
this.length = length;
}
@Override
public Sequence<Value_, Difference_> getPreviousSequence() {
return previousSequence;
}
@Override
public Sequence<Value_, Difference_> getNextSequence() {
return nextSequence;
}
@Override
public Difference_ getLength() {
return length;
}
void setPreviousSequence(Sequence<Value_, Difference_> previousSequence) {
this.previousSequence = previousSequence;
}
void setNextSequence(Sequence<Value_, Difference_> nextSequence) {
this.nextSequence = nextSequence;
}
void setLength(Difference_ length) {
this.length = length;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Break{" +
"previousSequence=" + previousSequence +
", nextSequence=" + nextSequence +
", length=" + length +
'}';
| 339
| 46
| 385
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/IntervalBreakImpl.java
|
IntervalBreakImpl
|
toString
|
class IntervalBreakImpl<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>>
implements IntervalBreak<Interval_, Point_, Difference_> {
private IntervalCluster<Interval_, Point_, Difference_> previousCluster;
private IntervalCluster<Interval_, Point_, Difference_> nextCluster;
private Difference_ length;
IntervalBreakImpl(IntervalCluster<Interval_, Point_, Difference_> previousCluster,
IntervalCluster<Interval_, Point_, Difference_> nextCluster, Difference_ length) {
this.previousCluster = previousCluster;
this.nextCluster = nextCluster;
this.length = length;
}
@Override
public IntervalCluster<Interval_, Point_, Difference_> getPreviousIntervalCluster() {
return previousCluster;
}
@Override
public IntervalCluster<Interval_, Point_, Difference_> getNextIntervalCluster() {
return nextCluster;
}
@Override
public Difference_ getLength() {
return length;
}
void setPreviousCluster(IntervalCluster<Interval_, Point_, Difference_> previousCluster) {
this.previousCluster = previousCluster;
}
void setNextCluster(IntervalCluster<Interval_, Point_, Difference_> nextCluster) {
this.nextCluster = nextCluster;
}
void setLength(Difference_ length) {
this.length = length;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "IntervalBreak{" +
"previousCluster=" + previousCluster +
", nextCluster=" + nextCluster +
", length=" + length +
'}';
| 384
| 47
| 431
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/IntervalSplitPoint.java
|
IntervalSplitPoint
|
removeIntervalStartingAtSplitPoint
|
class IntervalSplitPoint<Interval_, Point_ extends Comparable<Point_>>
implements Comparable<IntervalSplitPoint<Interval_, Point_>> {
final Point_ splitPoint;
Map<Interval_, Integer> startIntervalToCountMap;
Map<Interval_, Integer> endIntervalToCountMap;
TreeSet<Interval<Interval_, Point_>> intervalsStartingAtSplitPointSet;
TreeSet<Interval<Interval_, Point_>> intervalsEndingAtSplitPointSet;
public IntervalSplitPoint(Point_ splitPoint) {
this.splitPoint = splitPoint;
}
protected void createCollections() {
startIntervalToCountMap = new IdentityHashMap<>();
endIntervalToCountMap = new IdentityHashMap<>();
intervalsStartingAtSplitPointSet = new TreeSet<>(
Comparator.<Interval<Interval_, Point_>, Point_> comparing(Interval::getEnd)
.thenComparingInt(interval -> System.identityHashCode(interval.getValue())));
intervalsEndingAtSplitPointSet = new TreeSet<>(
Comparator.<Interval<Interval_, Point_>, Point_> comparing(Interval::getStart)
.thenComparingInt(interval -> System.identityHashCode(interval.getValue())));
}
public boolean addIntervalStartingAtSplitPoint(Interval<Interval_, Point_> interval) {
startIntervalToCountMap.merge(interval.getValue(), 1, Integer::sum);
return intervalsStartingAtSplitPointSet.add(interval);
}
public void removeIntervalStartingAtSplitPoint(Interval<Interval_, Point_> interval) {<FILL_FUNCTION_BODY>}
public boolean addIntervalEndingAtSplitPoint(Interval<Interval_, Point_> interval) {
endIntervalToCountMap.merge(interval.getValue(), 1, Integer::sum);
return intervalsEndingAtSplitPointSet.add(interval);
}
public void removeIntervalEndingAtSplitPoint(Interval<Interval_, Point_> interval) {
Integer newCount = endIntervalToCountMap.computeIfPresent(interval.getValue(), (key, count) -> {
if (count > 1) {
return count - 1;
}
return null;
});
if (null == newCount) {
intervalsEndingAtSplitPointSet.remove(interval);
}
}
public boolean containsIntervalStarting(Interval<Interval_, Point_> interval) {
return intervalsStartingAtSplitPointSet.contains(interval);
}
public boolean containsIntervalEnding(Interval<Interval_, Point_> interval) {
return intervalsEndingAtSplitPointSet.contains(interval);
}
public Iterator<Interval_> getValuesStartingFromSplitPointIterator() {
return intervalsStartingAtSplitPointSet.stream()
.flatMap(interval -> IntStream.range(0, startIntervalToCountMap.get(interval.getValue()))
.mapToObj(index -> interval.getValue()))
.iterator();
}
public boolean isEmpty() {
return intervalsStartingAtSplitPointSet.isEmpty() && intervalsEndingAtSplitPointSet.isEmpty();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
IntervalSplitPoint<?, ?> that = (IntervalSplitPoint<?, ?>) o;
return splitPoint.equals(that.splitPoint);
}
public boolean isBefore(IntervalSplitPoint<Interval_, Point_> other) {
return compareTo(other) < 0;
}
public boolean isAfter(IntervalSplitPoint<Interval_, Point_> other) {
return compareTo(other) > 0;
}
@Override
public int hashCode() {
return Objects.hash(splitPoint);
}
@Override
public int compareTo(IntervalSplitPoint<Interval_, Point_> other) {
return splitPoint.compareTo(other.splitPoint);
}
@Override
public String toString() {
return splitPoint.toString();
}
}
|
Integer newCount = startIntervalToCountMap.computeIfPresent(interval.getValue(), (key, count) -> {
if (count > 1) {
return count - 1;
}
return null;
});
if (null == newCount) {
intervalsStartingAtSplitPointSet.remove(interval);
}
| 1,021
| 86
| 1,107
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/IntervalTree.java
|
IntervalTree
|
contains
|
class IntervalTree<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> {
private final Function<Interval_, Point_> startMapping;
private final Function<Interval_, Point_> endMapping;
private final TreeSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet;
private final ConsecutiveIntervalInfoImpl<Interval_, Point_, Difference_> consecutiveIntervalData;
public IntervalTree(Function<Interval_, Point_> startMapping, Function<Interval_, Point_> endMapping,
BiFunction<Point_, Point_, Difference_> differenceFunction) {
this.startMapping = startMapping;
this.endMapping = endMapping;
this.splitPointSet = new TreeSet<>();
this.consecutiveIntervalData = new ConsecutiveIntervalInfoImpl<>(splitPointSet, differenceFunction);
}
public Interval<Interval_, Point_> getInterval(Interval_ intervalValue) {
return new Interval<>(intervalValue, startMapping, endMapping);
}
public boolean isEmpty() {
return splitPointSet.isEmpty();
}
public boolean contains(Interval_ o) {<FILL_FUNCTION_BODY>}
public Iterator<Interval_> iterator() {
return new IntervalTreeIterator<>(splitPointSet);
}
public boolean add(Interval<Interval_, Point_> interval) {
IntervalSplitPoint<Interval_, Point_> startSplitPoint = interval.getStartSplitPoint();
IntervalSplitPoint<Interval_, Point_> endSplitPoint = interval.getEndSplitPoint();
boolean isChanged;
IntervalSplitPoint<Interval_, Point_> flooredStartSplitPoint = splitPointSet.floor(startSplitPoint);
if (flooredStartSplitPoint == null || !flooredStartSplitPoint.equals(startSplitPoint)) {
splitPointSet.add(startSplitPoint);
startSplitPoint.createCollections();
isChanged = startSplitPoint.addIntervalStartingAtSplitPoint(interval);
} else {
isChanged = flooredStartSplitPoint.addIntervalStartingAtSplitPoint(interval);
}
IntervalSplitPoint<Interval_, Point_> ceilingEndSplitPoint = splitPointSet.ceiling(endSplitPoint);
if (ceilingEndSplitPoint == null || !ceilingEndSplitPoint.equals(endSplitPoint)) {
splitPointSet.add(endSplitPoint);
endSplitPoint.createCollections();
isChanged |= endSplitPoint.addIntervalEndingAtSplitPoint(interval);
} else {
isChanged |= ceilingEndSplitPoint.addIntervalEndingAtSplitPoint(interval);
}
if (isChanged) {
consecutiveIntervalData.addInterval(interval);
}
return true;
}
public boolean remove(Interval<Interval_, Point_> interval) {
IntervalSplitPoint<Interval_, Point_> startSplitPoint = interval.getStartSplitPoint();
IntervalSplitPoint<Interval_, Point_> endSplitPoint = interval.getEndSplitPoint();
IntervalSplitPoint<Interval_, Point_> flooredStartSplitPoint = splitPointSet.floor(startSplitPoint);
if (flooredStartSplitPoint == null || !flooredStartSplitPoint.containsIntervalStarting(interval)) {
return false;
}
flooredStartSplitPoint.removeIntervalStartingAtSplitPoint(interval);
if (flooredStartSplitPoint.isEmpty()) {
splitPointSet.remove(flooredStartSplitPoint);
}
IntervalSplitPoint<Interval_, Point_> ceilEndSplitPoint = splitPointSet.ceiling(endSplitPoint);
// Not null since the start point contained the interval
ceilEndSplitPoint.removeIntervalEndingAtSplitPoint(interval);
if (ceilEndSplitPoint.isEmpty()) {
splitPointSet.remove(ceilEndSplitPoint);
}
consecutiveIntervalData.removeInterval(interval);
return true;
}
public ConsecutiveIntervalInfoImpl<Interval_, Point_, Difference_> getConsecutiveIntervalData() {
return consecutiveIntervalData;
}
}
|
if (null == o || splitPointSet.isEmpty()) {
return false;
}
Interval<Interval_, Point_> interval = getInterval(o);
IntervalSplitPoint<Interval_, Point_> floorStartSplitPoint =
splitPointSet.floor(interval.getStartSplitPoint());
if (floorStartSplitPoint == null) {
return false;
}
return floorStartSplitPoint.containsIntervalStarting(interval);
| 998
| 110
| 1,108
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/IntervalTreeIterator.java
|
IntervalTreeIterator
|
next
|
class IntervalTreeIterator<Interval_, Point_ extends Comparable<Point_>> implements Iterator<Interval_> {
private final Iterator<IntervalSplitPoint<Interval_, Point_>> splitPointSetIterator;
private Iterator<Interval_> splitPointValueIterator;
IntervalTreeIterator(Iterable<IntervalSplitPoint<Interval_, Point_>> splitPointSet) {
this.splitPointSetIterator = splitPointSet.iterator();
if (splitPointSetIterator.hasNext()) {
splitPointValueIterator = splitPointSetIterator.next().getValuesStartingFromSplitPointIterator();
}
}
@Override
public boolean hasNext() {
return splitPointValueIterator != null && splitPointValueIterator.hasNext();
}
@Override
public Interval_ next() {<FILL_FUNCTION_BODY>}
}
|
Interval_ next = splitPointValueIterator.next();
while (!splitPointValueIterator.hasNext() && splitPointSetIterator.hasNext()) {
splitPointValueIterator = splitPointSetIterator.next().getValuesStartingFromSplitPointIterator();
}
if (!splitPointValueIterator.hasNext()) {
splitPointValueIterator = null;
}
return next;
| 208
| 98
| 306
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/experimental/impl/SequenceImpl.java
|
SequenceImpl
|
getItems
|
class SequenceImpl<Value_, Difference_ extends Comparable<Difference_>> implements Sequence<Value_, Difference_> {
private final ConsecutiveSetTree<Value_, ?, Difference_> sourceTree;
private Value_ firstItem;
private Value_ lastItem;
// Memorized calculations
private Difference_ length;
private NavigableSet<Value_> items;
SequenceImpl(ConsecutiveSetTree<Value_, ?, Difference_> sourceTree, Value_ item) {
this(sourceTree, item, item);
}
SequenceImpl(ConsecutiveSetTree<Value_, ?, Difference_> sourceTree, Value_ firstItem, Value_ lastItem) {
this.sourceTree = sourceTree;
this.firstItem = firstItem;
this.lastItem = lastItem;
length = null;
items = null;
}
@Override
public Value_ getFirstItem() {
return firstItem;
}
@Override
public Value_ getLastItem() {
return lastItem;
}
@Override
public Break<Value_, Difference_> getPreviousBreak() {
return sourceTree.getBreakBefore(firstItem);
}
@Override
public Break<Value_, Difference_> getNextBreak() {
return sourceTree.getBreakAfter(lastItem);
}
@Override
public boolean isFirst() {
return firstItem == sourceTree.getItemSet().first();
}
@Override
public boolean isLast() {
return lastItem == sourceTree.getItemSet().last();
}
@Override
public NavigableSet<Value_> getItems() {<FILL_FUNCTION_BODY>}
@Override
public int getCount() {
return getItems().size();
}
@Override
public Difference_ getLength() {
if (length == null) {
// memoize length for later calls
// (assignment returns the right hand side)
return length = sourceTree.getSequenceLength(this);
}
return length;
}
void setStart(Value_ item) {
firstItem = item;
invalidate();
}
void setEnd(Value_ item) {
lastItem = item;
invalidate();
}
// Called when start or end are removed; length
// need to be invalidated
void invalidate() {
length = null;
items = null;
}
SequenceImpl<Value_, Difference_> split(Value_ fromElement) {
NavigableSet<Value_> itemSet = getItems();
Value_ newSequenceStart = itemSet.higher(fromElement);
Value_ newSequenceEnd = lastItem;
setEnd(itemSet.lower(fromElement));
return new SequenceImpl<>(sourceTree, newSequenceStart, newSequenceEnd);
}
// This Sequence is ALWAYS before other Sequence
void merge(SequenceImpl<Value_, Difference_> other) {
lastItem = other.lastItem;
invalidate();
}
@Override
public String toString() {
return getItems().stream().map(Objects::toString).collect(Collectors.joining(", ", "Sequence [", "]"));
}
}
|
if (items == null) {
return items = sourceTree.getItemSet()
.subSet(firstItem, true, lastItem, true);
}
return items;
| 831
| 48
| 879
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractJsonSolutionFileIO.java
|
AbstractJsonSolutionFileIO
|
deduplicateMap
|
class AbstractJsonSolutionFileIO<Solution_> extends JacksonSolutionFileIO<Solution_> {
public AbstractJsonSolutionFileIO(Class<Solution_> clazz) {
super(clazz);
}
public AbstractJsonSolutionFileIO(Class<Solution_> clazz, ObjectMapper mapper) {
super(clazz, mapper);
}
protected <Entity_, Id_ extends Number, Value_> void deduplicateEntities(Solution_ solution,
Function<Solution_, Collection<Entity_>> entityCollectionFunction, Function<Entity_, Id_> entityIdFunction,
Function<Entity_, Map<Entity_, Value_>> entityMapGetter,
BiConsumer<Entity_, Map<Entity_, Value_>> entityMapSetter) {
var entityCollection = entityCollectionFunction.apply(solution);
var entitiesById = entityCollection.stream()
.collect(Collectors.toMap(entityIdFunction, Function.identity()));
for (Entity_ entity : entityCollection) {
var originalMap = entityMapGetter.apply(entity);
if (originalMap.isEmpty()) {
continue;
}
var newMap = new LinkedHashMap<Entity_, Value_>(originalMap.size());
originalMap
.forEach((otherEntity, value) -> newMap.put(entitiesById.get(entityIdFunction.apply(otherEntity)), value));
entityMapSetter.accept(entity, newMap);
}
}
protected <Key_, Value_, Index_> Map<Key_, Value_> deduplicateMap(Map<Key_, Value_> originalMap, Map<Index_, Key_> index,
Function<Key_, Index_> idFunction) {<FILL_FUNCTION_BODY>}
}
|
if (originalMap == null || originalMap.isEmpty()) {
return originalMap;
}
Map<Key_, Value_> newMap = new LinkedHashMap<>(originalMap.size());
originalMap.forEach((key, value) -> newMap.put(index.get(idFunction.apply(key)), value));
return newMap;
| 426
| 88
| 514
|
<methods>public void <init>(Class<Solution_>) ,public void <init>(Class<Solution_>, ObjectMapper) ,public java.lang.String getInputFileExtension() ,public java.lang.String getOutputFileExtension() ,public Solution_ read(java.io.File) ,public Solution_ read(java.io.InputStream) ,public void write(Solution_, java.io.File) <variables>private final non-sealed Class<Solution_> clazz,private final non-sealed ObjectMapper mapper
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractSolutionImporter.java
|
InputBuilder
|
getFlooredPossibleSolutionSize
|
class InputBuilder extends LoggingMain {
}
public static BigInteger factorial(int base) {
if (base > 100000) {
// Calculation takes too long
return null;
}
BigInteger value = BigInteger.ONE;
for (int i = 1; i <= base; i++) {
value = value.multiply(BigInteger.valueOf(i));
}
return value;
}
public static String getFlooredPossibleSolutionSize(BigInteger possibleSolutionSize) {<FILL_FUNCTION_BODY>
|
if (possibleSolutionSize == null) {
return null;
}
if (possibleSolutionSize.compareTo(BigInteger.valueOf(1000L)) < 0) {
return possibleSolutionSize.toString();
}
BigDecimal possibleSolutionSizeBigDecimal = new BigDecimal(possibleSolutionSize);
int decimalDigits = possibleSolutionSizeBigDecimal.scale() < 0
? possibleSolutionSizeBigDecimal.precision() - possibleSolutionSizeBigDecimal.scale()
: possibleSolutionSizeBigDecimal.precision();
return "10^" + decimalDigits;
| 148
| 158
| 306
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractTxtSolutionExporter.java
|
AbstractTxtSolutionExporter
|
writeSolution
|
class AbstractTxtSolutionExporter<Solution_> extends AbstractSolutionExporter<Solution_> {
protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = "txt";
@Override
public String getOutputFileSuffix() {
return DEFAULT_OUTPUT_FILE_SUFFIX;
}
public abstract TxtOutputBuilder<Solution_> createTxtOutputBuilder();
@Override
public void writeSolution(Solution_ solution, File outputFile) {<FILL_FUNCTION_BODY>}
public static abstract class TxtOutputBuilder<Solution_> extends OutputBuilder {
protected BufferedWriter bufferedWriter;
protected Solution_ solution;
public void setBufferedWriter(BufferedWriter bufferedWriter) {
this.bufferedWriter = bufferedWriter;
}
public void setSolution(Solution_ solution) {
this.solution = solution;
}
public abstract void writeSolution() throws IOException;
// ************************************************************************
// Helper methods
// ************************************************************************
}
}
|
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"))) {
TxtOutputBuilder<Solution_> txtOutputBuilder = createTxtOutputBuilder();
txtOutputBuilder.setBufferedWriter(writer);
txtOutputBuilder.setSolution(solution);
txtOutputBuilder.writeSolution();
logger.info("Exported: {}", outputFile);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
}
| 276
| 144
| 420
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getOutputFileSuffix() ,public abstract void writeSolution(Solution_, java.io.File) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractXmlSolutionExporter.java
|
AbstractXmlSolutionExporter
|
writeSolution
|
class AbstractXmlSolutionExporter<Solution_> extends AbstractSolutionExporter<Solution_> {
protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = "xml";
@Override
public String getOutputFileSuffix() {
return DEFAULT_OUTPUT_FILE_SUFFIX;
}
public abstract XmlOutputBuilder<Solution_> createXmlOutputBuilder();
@Override
public void writeSolution(Solution_ solution, File outputFile) {<FILL_FUNCTION_BODY>}
public static abstract class XmlOutputBuilder<Solution_> extends OutputBuilder {
protected Document document;
public void setDocument(Document document) {
this.document = document;
}
public abstract void setSolution(Solution_ solution);
public abstract void writeSolution() throws IOException, JDOMException;
// ************************************************************************
// Helper methods
// ************************************************************************
}
}
|
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile))) {
Document document = new Document();
XmlOutputBuilder<Solution_> xmlOutputBuilder = createXmlOutputBuilder();
xmlOutputBuilder.setDocument(document);
xmlOutputBuilder.setSolution(solution);
xmlOutputBuilder.writeSolution();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(document, out);
logger.info("Exported: {}", outputFile);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
} catch (JDOMException e) {
throw new IllegalArgumentException("Could not format the XML file (" + outputFile.getName() + ").", e);
}
| 244
| 210
| 454
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getOutputFileSuffix() ,public abstract void writeSolution(Solution_, java.io.File) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/jackson/JacksonUniqueIdGenerator.java
|
JacksonUniqueIdGenerator
|
key
|
class JacksonUniqueIdGenerator extends ObjectIdGenerator<String> {
private final Class<?> scope;
public JacksonUniqueIdGenerator() {
this.scope = Object.class;
}
@Override
public Class<?> getScope() {
return scope;
}
@Override
public boolean canUseFor(ObjectIdGenerator<?> gen) {
return (gen.getClass() == getClass());
}
@Override
public ObjectIdGenerator<String> forScope(Class<?> scope) {
return this;
}
@Override
public ObjectIdGenerator<String> newForSerialization(Object context) {
return this;
}
@Override
public IdKey key(Object key) {<FILL_FUNCTION_BODY>}
@Override
public String generateId(Object forPojo) {
return forPojo.getClass().getSimpleName() + "#" + ((AbstractPersistable) forPojo).getId();
}
}
|
if (key == null) {
return null;
}
return new IdKey(getClass(), null, key);
| 256
| 34
| 290
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/swingui/OpenBrowserAction.java
|
OpenBrowserAction
|
actionPerformed
|
class OpenBrowserAction extends AbstractAction {
private final URI uri;
public OpenBrowserAction(String title, String urlString) {
super(title);
try {
uri = new URI(urlString);
} catch (URISyntaxException e) {
throw new IllegalStateException("Failed creating URI for urlString (" + urlString + ").", e);
}
}
@Override
public void actionPerformed(ActionEvent event) {<FILL_FUNCTION_BODY>}
}
|
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
JOptionPane.showMessageDialog(null, "Cannot open a browser automatically."
+ "\nPlease open this url manually:\n" + uri.toString(),
"Cannot open browser", JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
desktop.browse(uri);
} catch (IOException e) {
throw new IllegalStateException("Failed showing uri (" + uri + ") in the default browser.", e);
}
| 128
| 159
| 287
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, javax.swing.Icon) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object[] getKeys() ,public synchronized java.beans.PropertyChangeListener[] getPropertyChangeListeners() ,public java.lang.Object getValue(java.lang.String) ,public boolean isEnabled() ,public void putValue(java.lang.String, java.lang.Object) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setEnabled(boolean) <variables>private static java.lang.Boolean RECONFIGURE_ON_NULL,private transient javax.swing.ArrayTable arrayTable,protected javax.swing.event.SwingPropertyChangeSupport changeSupport,protected boolean enabled
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/swingui/SolutionPanel.java
|
SolutionPanel
|
preparePlanningEntityColors
|
class SolutionPanel<Solution_> extends JPanel implements Scrollable {
protected static final String USAGE_EXPLANATION_PATH =
"/org/optaplanner/examples/common/swingui/exampleUsageExplanation.png";
// Size fits into screen resolution 1024*768
public static final Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE = new Dimension(800, 600);
protected static final Color[][] INDICTMENT_COLORS = {
{ TangoColorFactory.SCARLET_3, TangoColorFactory.SCARLET_1 },
{ TangoColorFactory.ORANGE_3, TangoColorFactory.ORANGE_1 },
{ TangoColorFactory.BUTTER_3, TangoColorFactory.BUTTER_1 },
{ TangoColorFactory.CHAMELEON_3, TangoColorFactory.CHAMELEON_1 },
{ TangoColorFactory.SKY_BLUE_3, TangoColorFactory.SKY_BLUE_1 },
{ TangoColorFactory.PLUM_3, TangoColorFactory.PLUM_1 }
};
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected SolverAndPersistenceFrame<Solution_> solverAndPersistenceFrame;
protected SolutionBusiness<Solution_, ?> solutionBusiness;
protected boolean useIndictmentColor = false;
protected TangoColorFactory normalColorFactory;
protected double[] indictmentMinimumLevelNumbers;
public SolverAndPersistenceFrame<Solution_> getSolverAndPersistenceFrame() {
return solverAndPersistenceFrame;
}
public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<Solution_> solverAndPersistenceFrame) {
this.solverAndPersistenceFrame = solverAndPersistenceFrame;
}
public SolutionBusiness<Solution_, ?> getSolutionBusiness() {
return solutionBusiness;
}
public void setSolutionBusiness(SolutionBusiness<Solution_, ?> solutionBusiness) {
this.solutionBusiness = solutionBusiness;
}
public boolean isUseIndictmentColor() {
return useIndictmentColor;
}
public void setUseIndictmentColor(boolean useIndictmentColor) {
this.useIndictmentColor = useIndictmentColor;
}
public String getUsageExplanationPath() {
return USAGE_EXPLANATION_PATH;
}
public boolean isWrapInScrollPane() {
return true;
}
public abstract void resetPanel(Solution_ solution);
public void updatePanel(Solution_ solution) {
resetPanel(solution);
}
public Solution_ getSolution() {
return solutionBusiness.getSolution();
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return PREFERRED_SCROLLABLE_VIEWPORT_SIZE;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
public boolean isIndictmentHeatMapEnabled() {
return false;
}
protected void preparePlanningEntityColors(List<?> planningEntityList) {<FILL_FUNCTION_BODY>}
public Color determinePlanningEntityColor(Object planningEntity, Object normalColorObject) {
if (useIndictmentColor) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment != null) {
Number[] levelNumbers = indictment.getScore().toLevelNumbers();
for (int i = 0; i < levelNumbers.length; i++) {
if (i > INDICTMENT_COLORS.length) {
return TangoColorFactory.ALUMINIUM_3;
}
double levelNumber = levelNumbers[i].doubleValue();
if (levelNumber < 0.0) {
return TangoColorFactory.buildPercentageColor(
INDICTMENT_COLORS[i][0], INDICTMENT_COLORS[i][1],
1.0 - (levelNumber / indictmentMinimumLevelNumbers[i]));
}
}
}
return Color.WHITE;
} else {
return normalColorFactory.pickColor(normalColorObject);
}
}
public String determinePlanningEntityTooltip(Object planningEntity) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment == null) {
return "<html>No indictment</html>";
}
StringBuilder s = new StringBuilder("<html>Indictment: ").append(indictment.getScore().toShortString());
for (ConstraintMatch<?> constraintMatch : indictment.getConstraintMatchSet()) {
s.append("<br/> ").append(constraintMatch.getConstraintName())
.append(" = ").append(constraintMatch.getScore().toShortString());
}
s.append("</html>");
return s.toString();
}
public void doProblemChange(ProblemChange<Solution_> problemChange) {
doProblemChange(problemChange, false);
}
public void doProblemChange(ProblemChange<Solution_> problemChange, boolean reset) {
solutionBusiness.doProblemChange(problemChange);
Solution_ solution = getSolution();
Score score = solutionBusiness.getScore();
if (reset) {
resetPanel(solution);
} else {
updatePanel(solution);
}
validate();
solverAndPersistenceFrame.refreshScoreField(score);
}
}
|
if (useIndictmentColor) {
indictmentMinimumLevelNumbers = null;
for (Object planningEntity : planningEntityList) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment != null) {
Number[] levelNumbers = indictment.getScore().toLevelNumbers();
if (indictmentMinimumLevelNumbers == null) {
indictmentMinimumLevelNumbers = new double[levelNumbers.length];
for (int i = 0; i < levelNumbers.length; i++) {
indictmentMinimumLevelNumbers[i] = levelNumbers[i].doubleValue();
}
} else {
for (int i = 0; i < levelNumbers.length; i++) {
double levelNumber = levelNumbers[i].doubleValue();
if (levelNumber < indictmentMinimumLevelNumbers[i]) {
indictmentMinimumLevelNumbers[i] = levelNumber;
}
}
}
}
}
} else {
normalColorFactory = new TangoColorFactory();
}
| 1,643
| 294
| 1,937
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/swingui/latitudelongitude/LatitudeLongitudeTranslator.java
|
LatitudeLongitudeTranslator
|
translateXToLongitude
|
class LatitudeLongitudeTranslator {
public static final double MARGIN_RATIO = 0.04;
private double minimumLatitude = Double.MAX_VALUE;
private double maximumLatitude = -Double.MAX_VALUE;
private double minimumLongitude = Double.MAX_VALUE;
private double maximumLongitude = -Double.MAX_VALUE;
private double latitudeLength = 0.0;
private double longitudeLength = 0.0;
private double innerWidth = 0.0;
private double innerHeight = 0.0;
private double innerWidthMargin = 0.0;
private double innerHeightMargin = 0.0;
private int imageWidth = -1;
private int imageHeight = -1;
public void addCoordinates(double latitude, double longitude) {
if (latitude < minimumLatitude) {
minimumLatitude = latitude;
}
if (latitude > maximumLatitude) {
maximumLatitude = latitude;
}
if (longitude < minimumLongitude) {
minimumLongitude = longitude;
}
if (longitude > maximumLongitude) {
maximumLongitude = longitude;
}
}
public void prepareFor(double width, double height) {
latitudeLength = maximumLatitude - minimumLatitude;
longitudeLength = maximumLongitude - minimumLongitude;
innerWidthMargin = width * MARGIN_RATIO;
innerHeightMargin = height * MARGIN_RATIO;
innerWidth = width - (2.0 * innerWidthMargin);
innerHeight = height - (2.0 * innerHeightMargin);
// Keep ratio visually correct
if (innerWidth > innerHeight * longitudeLength / latitudeLength) {
innerWidth = innerHeight * longitudeLength / latitudeLength;
} else {
innerHeight = innerWidth * latitudeLength / longitudeLength;
}
imageWidth = (int) Math.floor((2.0 * innerWidthMargin) + innerWidth);
imageHeight = (int) Math.floor((2.0 * innerHeightMargin) + innerHeight);
}
public int translateLongitudeToX(double longitude) {
return (int) Math.floor(((longitude - minimumLongitude) * innerWidth / longitudeLength) + innerWidthMargin);
}
public int translateLatitudeToY(double latitude) {
return (int) Math.floor(((maximumLatitude - latitude) * innerHeight / latitudeLength) + innerHeightMargin);
}
public double translateXToLongitude(int x) {<FILL_FUNCTION_BODY>}
public double translateYToLatitude(double y) {
return maximumLatitude - ((y - innerHeightMargin) * latitudeLength / innerHeight);
}
public int getImageWidth() {
return imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public void drawRoute(Graphics2D g, double lon1, double lat1, double lon2, double lat2, boolean straight, boolean dashed) {
int x1 = translateLongitudeToX(lon1);
int y1 = translateLatitudeToY(lat1);
int x2 = translateLongitudeToX(lon2);
int y2 = translateLatitudeToY(lat2);
if (dashed) {
g.setStroke(TangoColorFactory.FAT_DASHED_STROKE);
}
if (straight) {
g.drawLine(x1, y1, x2, y2);
} else {
double xDistPart = (x2 - x1) / 3.0;
double yDistPart = (y2 - y1) / 3.0;
double ctrlx1 = x1 + xDistPart + yDistPart;
double ctrly1 = y1 - xDistPart + yDistPart;
double ctrlx2 = x2 - xDistPart - yDistPart;
double ctrly2 = y2 + xDistPart - yDistPart;
g.draw(new CubicCurve2D.Double(x1, y1, ctrlx1, ctrly1, ctrlx2, ctrly2, x2, y2));
}
if (dashed) {
g.setStroke(TangoColorFactory.NORMAL_STROKE);
}
}
}
|
return minimumLongitude + ((x - innerWidthMargin) * longitudeLength / innerWidth);
| 1,102
| 26
| 1,128
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/swingui/timetable/TimeTablePanel.java
|
TimeTablePanel
|
addCell
|
class TimeTablePanel<XObject, YObject> extends JPanel implements Scrollable {
private final TimeTableLayout layout = new TimeTableLayout();
private final Map<Object, Integer> xMap = new HashMap<>();
private final Map<Object, Integer> yMap = new HashMap<>();
public TimeTablePanel() {
setLayout(layout);
}
public void reset() {
removeAll();
layout.reset();
xMap.clear();
yMap.clear();
}
// ************************************************************************
// Define methods
// ************************************************************************
public void defineColumnHeaderByKey(HeaderColumnKey xObject) {
int x = layout.addColumn();
xMap.put(xObject, x);
}
public void defineColumnHeader(XObject xObject) {
int x = layout.addColumn();
xMap.put(xObject, x);
}
public void defineColumnHeader(XObject xObject, int width) {
int x = layout.addColumn(width);
xMap.put(xObject, x);
}
public void defineRowHeaderByKey(HeaderRowKey yObject) {
int y = layout.addRow();
yMap.put(yObject, y);
}
public void defineRowHeader(YObject yObject) {
int y = layout.addRow();
yMap.put(yObject, y);
}
public void defineRowHeader(YObject yObject, int height) {
int y = layout.addRow(height);
yMap.put(yObject, y);
}
// ************************************************************************
// Add methods
// ************************************************************************
public void addCornerHeader(HeaderColumnKey xObject, HeaderRowKey yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addColumnHeader(XObject xObject, HeaderRowKey yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addColumnHeader(XObject xObject1, HeaderRowKey yObject1, XObject xObject2, HeaderRowKey yObject2,
JComponent component) {
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1, true));
}
public void addRowHeader(HeaderColumnKey xObject, YObject yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addRowHeader(HeaderColumnKey xObject1, YObject yObject1, HeaderColumnKey xObject2, YObject yObject2,
JComponent component) {
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1, true));
}
public void addCell(XObject xObject, YObject yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y));
}
public void addCell(XObject xObject1, YObject yObject1, XObject xObject2, YObject yObject2, JComponent component) {<FILL_FUNCTION_BODY>}
// ************************************************************************
// Scrollable methods
// ************************************************************************
@Override
public Dimension getPreferredScrollableViewportSize() {
return SolutionPanel.PREFERRED_SCROLLABLE_VIEWPORT_SIZE;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
public enum HeaderColumnKey {
HEADER_COLUMN_GROUP2,
HEADER_COLUMN_GROUP1,
HEADER_COLUMN,
HEADER_COLUMN_EXTRA_PROPERTY_1,
HEADER_COLUMN_EXTRA_PROPERTY_2,
HEADER_COLUMN_EXTRA_PROPERTY_3,
HEADER_COLUMN_EXTRA_PROPERTY_4,
HEADER_COLUMN_EXTRA_PROPERTY_5,
TRAILING_HEADER_COLUMN;
}
public enum HeaderRowKey {
HEADER_ROW_GROUP2,
HEADER_ROW_GROUP1,
HEADER_ROW,
TRAILING_HEADER_ROW;
}
}
|
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1));
| 1,539
| 98
| 1,637
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/common/util/PairImpl.java
|
PairImpl
|
equals
|
class PairImpl<A, B> implements Pair<A, B> {
private final A key;
private final B value;
public PairImpl(A key, B value) {
this.key = key;
this.value = value;
}
@Override
public A getKey() {
return key;
}
@Override
public B getValue() {
return value;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return "(" + key + ", " + value + ")";
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PairImpl<?, ?> that = (PairImpl<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
| 198
| 86
| 284
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/conferencescheduling/domain/Timeslot.java
|
Timeslot
|
setStartDateTime
|
class Timeslot extends AbstractPersistable {
private LocalDateTime startDateTime;
private LocalDateTime endDateTime;
private Set<TalkType> talkTypeSet;
private Set<String> tagSet;
// Cached
private int durationInMinutes;
public Timeslot() {
}
public Timeslot(long id) {
super(id);
}
public LocalDate getDate() {
return startDateTime.toLocalDate();
}
public int getDurationInMinutes() {
return durationInMinutes;
}
public boolean overlapsTime(Timeslot other) {
if (this == other) {
return true;
}
return startDateTime.compareTo(other.endDateTime) < 0
&& other.startDateTime.compareTo(endDateTime) < 0;
}
public int getOverlapInMinutes(Timeslot other) {
if (this == other) {
return durationInMinutes;
}
LocalDateTime startMaximum = (startDateTime.compareTo(other.startDateTime) < 0) ? other.startDateTime : startDateTime;
LocalDateTime endMinimum = (endDateTime.compareTo(other.endDateTime) < 0) ? endDateTime : other.endDateTime;
return (int) Duration.between(startMaximum, endMinimum).toMinutes();
}
public boolean startsAfter(Timeslot other) {
return other.endDateTime.compareTo(startDateTime) <= 0;
}
public boolean endsBefore(Timeslot other) {
return endDateTime.compareTo(other.startDateTime) <= 0;
}
public boolean isOnSameDayAs(Timeslot other) {
return startDateTime.toLocalDate().equals(other.getStartDateTime().toLocalDate());
}
public boolean pauseExists(Timeslot other, int pauseInMinutes) {
if (this.overlapsTime(other)) {
return false;
}
if (!this.isOnSameDayAs(other)) {
return true;
}
Duration pause = startsAfter(other) ? Duration.between(other.getEndDateTime(), getStartDateTime())
: Duration.between(getEndDateTime(), other.getStartDateTime());
return pause.toMinutes() >= pauseInMinutes;
}
@Override
public String toString() {
return startDateTime + "-" + endDateTime.toLocalTime();
}
// ************************************************************************
// Simple getters and setters
// ************************************************************************
public LocalDateTime getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(LocalDateTime startDateTime) {<FILL_FUNCTION_BODY>}
public LocalDateTime getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
durationInMinutes = (startDateTime == null || endDateTime == null) ? 0
: (int) Duration.between(startDateTime, endDateTime).toMinutes();
}
public Set<TalkType> getTalkTypeSet() {
return talkTypeSet;
}
public void setTalkTypeSet(Set<TalkType> talkTypeSet) {
this.talkTypeSet = talkTypeSet;
}
public Set<String> getTagSet() {
return tagSet;
}
public void setTagSet(Set<String> tagSet) {
this.tagSet = tagSet;
}
// ************************************************************************
// With methods
// ************************************************************************
public Timeslot withStartDateTime(LocalDateTime startDateTime) {
setStartDateTime(startDateTime);
return this;
}
public Timeslot withEndDateTime(LocalDateTime endDateTime) {
setEndDateTime(endDateTime);
return this;
}
public Timeslot withTalkTypeSet(Set<TalkType> talkTypeSet) {
this.talkTypeSet = talkTypeSet;
return this;
}
public Timeslot withTagSet(Set<String> tagSet) {
this.tagSet = tagSet;
return this;
}
}
|
this.startDateTime = startDateTime;
durationInMinutes = (startDateTime == null || endDateTime == null) ? 0
: (int) Duration.between(startDateTime, endDateTime).toMinutes();
| 1,048
| 55
| 1,103
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/conferencescheduling/persistence/ConnectionFollowRedirects.java
|
ConnectionFollowRedirects
|
redirectConnection
|
class ConnectionFollowRedirects {
private URLConnection connection;
private boolean isRedirect;
private int redirects = 0;
public ConnectionFollowRedirects(String url) throws IOException {
this.connection = new URL(url).openConnection();
}
public URLConnection getConnection() {
return connection;
}
public int getRedirects() {
return redirects;
}
public InputStream getInputStream() throws IOException {
InputStream in = null;
do {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).setInstanceFollowRedirects(false);
}
// We want to open the input stream before getting headers
// because getHeaderField() et al swallow IOExceptions.
in = connection.getInputStream();
followRedirects();
} while (isRedirect);
return in;
}
private void followRedirects() throws IOException {
isRedirect = false;
if (connection instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) connection;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 &&
stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
redirectConnection(http);
}
}
}
private void redirectConnection(HttpURLConnection http) throws IOException {<FILL_FUNCTION_BODY>}
}
|
URL base = http.getURL();
String location = http.getHeaderField("Location");
URL target = null;
if (location != null) {
target = new URL(base, location);
}
http.disconnect();
// Redirection should be allowed only for HTTP and HTTPS
// and should be limited to 5 redirections at most.
if (target == null || !(target.getProtocol().equals("http")
|| target.getProtocol().equals("https"))
|| redirects >= 5) {
throw new SecurityException("illegal URL redirect");
}
isRedirect = true;
connection = target.openConnection();
redirects++;
| 366
| 173
| 539
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/domain/CourseSchedule.java
|
CourseSchedule
|
calculateCourseConflictList
|
class CourseSchedule extends AbstractPersistable {
private String name;
private List<Teacher> teacherList;
private List<Curriculum> curriculumList;
private List<Course> courseList;
private List<Day> dayList;
private List<Timeslot> timeslotList;
private List<Period> periodList;
private List<Room> roomList;
private List<UnavailablePeriodPenalty> unavailablePeriodPenaltyList;
private List<Lecture> lectureList;
private HardSoftScore score;
public CourseSchedule() {
}
public CourseSchedule(long id) {
super(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ProblemFactCollectionProperty
public List<Teacher> getTeacherList() {
return teacherList;
}
public void setTeacherList(List<Teacher> teacherList) {
this.teacherList = teacherList;
}
@ProblemFactCollectionProperty
public List<Curriculum> getCurriculumList() {
return curriculumList;
}
public void setCurriculumList(List<Curriculum> curriculumList) {
this.curriculumList = curriculumList;
}
@ProblemFactCollectionProperty
public List<Course> getCourseList() {
return courseList;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
@ProblemFactCollectionProperty
public List<Day> getDayList() {
return dayList;
}
public void setDayList(List<Day> dayList) {
this.dayList = dayList;
}
@ProblemFactCollectionProperty
public List<Timeslot> getTimeslotList() {
return timeslotList;
}
public void setTimeslotList(List<Timeslot> timeslotList) {
this.timeslotList = timeslotList;
}
@ValueRangeProvider
@ProblemFactCollectionProperty
public List<Period> getPeriodList() {
return periodList;
}
public void setPeriodList(List<Period> periodList) {
this.periodList = periodList;
}
@ValueRangeProvider
@ProblemFactCollectionProperty
public List<Room> getRoomList() {
return roomList;
}
public void setRoomList(List<Room> roomList) {
this.roomList = roomList;
}
@ProblemFactCollectionProperty
public List<UnavailablePeriodPenalty> getUnavailablePeriodPenaltyList() {
return unavailablePeriodPenaltyList;
}
public void setUnavailablePeriodPenaltyList(List<UnavailablePeriodPenalty> unavailablePeriodPenaltyList) {
this.unavailablePeriodPenaltyList = unavailablePeriodPenaltyList;
}
@PlanningEntityCollectionProperty
public List<Lecture> getLectureList() {
return lectureList;
}
public void setLectureList(List<Lecture> lectureList) {
this.lectureList = lectureList;
}
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@ProblemFactCollectionProperty
private List<CourseConflict> calculateCourseConflictList() {<FILL_FUNCTION_BODY>}
}
|
List<CourseConflict> courseConflictList = new ArrayList<>();
for (Course leftCourse : courseList) {
for (Course rightCourse : courseList) {
if (leftCourse.getId() < rightCourse.getId()) {
int conflictCount = 0;
if (leftCourse.getTeacher().equals(rightCourse.getTeacher())) {
conflictCount++;
}
for (Curriculum curriculum : leftCourse.getCurriculumSet()) {
if (rightCourse.getCurriculumSet().contains(curriculum)) {
conflictCount++;
}
}
if (conflictCount > 0) {
courseConflictList.add(new CourseConflict(leftCourse, rightCourse, conflictCount));
}
}
}
}
return courseConflictList;
| 951
| 212
| 1,163
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/domain/Day.java
|
Day
|
getLabel
|
class Day extends AbstractPersistable implements Labeled {
private static final String[] WEEKDAYS = { "Mo", "Tu", "We", "Th", "Fr", "Sat", "Sun" };
private int dayIndex;
private List<Period> periodList;
public Day() {
}
public Day(int dayIndex, Period... periods) {
super(dayIndex);
this.dayIndex = dayIndex;
this.periodList = Arrays.stream(periods)
.collect(Collectors.toList());
}
public int getDayIndex() {
return dayIndex;
}
public void setDayIndex(int dayIndex) {
this.dayIndex = dayIndex;
}
public List<Period> getPeriodList() {
return periodList;
}
public void setPeriodList(List<Period> periodList) {
this.periodList = periodList;
}
@Override
public String getLabel() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return Integer.toString(dayIndex);
}
}
|
String weekday = WEEKDAYS[dayIndex % WEEKDAYS.length];
if (dayIndex > WEEKDAYS.length) {
return "Day " + dayIndex;
}
return weekday;
| 292
| 61
| 353
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/domain/Lecture.java
|
Lecture
|
getTimeslotIndex
|
class Lecture extends AbstractPersistable implements Labeled {
private Course course;
private int lectureIndexInCourse;
private boolean pinned;
// Planning variables: changes during planning, between score calculations.
private Period period;
private Room room;
public Lecture() {
}
public Lecture(long id, Course course, int lectureIndexInCourse, boolean pinned) {
super(id);
this.course = course;
this.lectureIndexInCourse = lectureIndexInCourse;
this.pinned = pinned;
}
public Lecture(long id, Course course, Period period, Room room) {
super(id);
this.course = course;
this.period = period;
this.room = room;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public int getLectureIndexInCourse() {
return lectureIndexInCourse;
}
public void setLectureIndexInCourse(int lectureIndexInCourse) {
this.lectureIndexInCourse = lectureIndexInCourse;
}
@PlanningPin
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
@PlanningVariable(strengthWeightFactoryClass = PeriodStrengthWeightFactory.class)
public Period getPeriod() {
return period;
}
public void setPeriod(Period period) {
this.period = period;
}
@PlanningVariable(strengthWeightFactoryClass = RoomStrengthWeightFactory.class)
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public Teacher getTeacher() {
return course.getTeacher();
}
@JsonIgnore
public int getStudentSize() {
return course.getStudentSize();
}
@JsonIgnore
public Set<Curriculum> getCurriculumSet() {
return course.getCurriculumSet();
}
@JsonIgnore
public Day getDay() {
if (period == null) {
return null;
}
return period.getDay();
}
@JsonIgnore
public int getTimeslotIndex() {<FILL_FUNCTION_BODY>}
@Override
public String getLabel() {
return course.getCode() + "-" + lectureIndexInCourse;
}
@Override
public String toString() {
return course + "-" + lectureIndexInCourse;
}
}
|
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getTimeslot().getTimeslotIndex();
| 738
| 38
| 776
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/domain/solver/CourseConflict.java
|
CourseConflict
|
equals
|
class CourseConflict implements Comparable<CourseConflict> {
private static final Comparator<Course> COURSE_COMPARATOR = Comparator.comparingLong(Course::getId);
private static final Comparator<CourseConflict> COMPARATOR = Comparator
.comparing(CourseConflict::getLeftCourse, COURSE_COMPARATOR)
.thenComparing(CourseConflict::getRightCourse, COURSE_COMPARATOR);
private final Course leftCourse;
private final Course rightCourse;
private final int conflictCount;
public CourseConflict(Course leftCourse, Course rightCourse, int conflictCount) {
this.leftCourse = leftCourse;
this.rightCourse = rightCourse;
this.conflictCount = conflictCount;
}
public Course getLeftCourse() {
return leftCourse;
}
public Course getRightCourse() {
return rightCourse;
}
public int getConflictCount() {
return conflictCount;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(leftCourse, rightCourse);
}
@Override
public int compareTo(CourseConflict other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return leftCourse + " & " + rightCourse;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CourseConflict other = (CourseConflict) o;
return Objects.equals(leftCourse, other.leftCourse) &&
Objects.equals(rightCourse, other.rightCourse);
| 398
| 99
| 497
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/domain/solver/PeriodStrengthWeightFactory.java
|
PeriodStrengthWeightFactory
|
createSorterWeight
|
class PeriodStrengthWeightFactory implements SelectionSorterWeightFactory<CourseSchedule, Period> {
@Override
public PeriodStrengthWeight createSorterWeight(CourseSchedule schedule, Period period) {<FILL_FUNCTION_BODY>}
public static class PeriodStrengthWeight implements Comparable<PeriodStrengthWeight> {
// The higher unavailablePeriodPenaltyCount, the weaker
private static final Comparator<PeriodStrengthWeight> BASE_COMPARATOR = reverseOrder(
comparingInt((PeriodStrengthWeight w) -> w.unavailablePeriodPenaltyCount));
private static final Comparator<Period> PERIOD_COMPARATOR = comparingInt((Period p) -> p.getDay().getDayIndex())
.thenComparingInt(p -> p.getTimeslot().getTimeslotIndex())
.thenComparingLong(Period::getId);
private static final Comparator<PeriodStrengthWeight> COMPARATOR = comparing(identity(), BASE_COMPARATOR)
.thenComparing(w -> w.period, PERIOD_COMPARATOR);
private final Period period;
private final int unavailablePeriodPenaltyCount;
public PeriodStrengthWeight(Period period, int unavailablePeriodPenaltyCount) {
this.period = period;
this.unavailablePeriodPenaltyCount = unavailablePeriodPenaltyCount;
}
@Override
public int compareTo(PeriodStrengthWeight other) {
return COMPARATOR.compare(this, other);
}
}
}
|
int unavailablePeriodPenaltyCount = 0;
for (UnavailablePeriodPenalty penalty : schedule.getUnavailablePeriodPenaltyList()) {
if (penalty.getPeriod().equals(period)) {
unavailablePeriodPenaltyCount++;
}
}
return new PeriodStrengthWeight(period, unavailablePeriodPenaltyCount);
| 381
| 92
| 473
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/persistence/CurriculumCourseExporter.java
|
CurriculumCourseExporter
|
main
|
class CurriculumCourseExporter extends AbstractTxtSolutionExporter<CourseSchedule> {
private static final String OUTPUT_FILE_SUFFIX = "sol";
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
@Override
public String getOutputFileSuffix() {
return OUTPUT_FILE_SUFFIX;
}
@Override
public TxtOutputBuilder<CourseSchedule> createTxtOutputBuilder() {
return new CurriculumCourseOutputBuilder();
}
public static class CurriculumCourseOutputBuilder extends TxtOutputBuilder<CourseSchedule> {
@Override
public void writeSolution() throws IOException {
for (Lecture lecture : solution.getLectureList()) {
bufferedWriter.write(lecture.getCourse().getCode()
+ " r" + lecture.getRoom().getCode()
+ " " + lecture.getPeriod().getDay().getDayIndex()
+ " " + lecture.getPeriod().getTimeslot().getTimeslotIndex() + "\r\n");
}
}
}
}
|
SolutionConverter<CourseSchedule> converter = SolutionConverter.createExportConverter(
CurriculumCourseApp.DATA_DIR_NAME, new CurriculumCourseExporter(), new CurriculumCourseSolutionFileIO());
converter.convertAll();
| 285
| 63
| 348
|
<methods>public non-sealed void <init>() ,public abstract TxtOutputBuilder<org.optaplanner.examples.curriculumcourse.domain.CourseSchedule> createTxtOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.curriculumcourse.domain.CourseSchedule, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/score/CurriculumCourseConstraintProvider.java
|
CurriculumCourseConstraintProvider
|
curriculumCompactness
|
class CurriculumCourseConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory factory) {
return new Constraint[] {
conflictingLecturesDifferentCourseInSamePeriod(factory),
conflictingLecturesSameCourseInSamePeriod(factory),
roomOccupancy(factory),
unavailablePeriodPenalty(factory),
roomCapacity(factory),
minimumWorkingDays(factory),
curriculumCompactness(factory),
roomStability(factory)
};
}
// ************************************************************************
// Hard constraints
// ************************************************************************
Constraint conflictingLecturesDifferentCourseInSamePeriod(ConstraintFactory factory) {
return factory.forEach(CourseConflict.class)
.join(Lecture.class,
equal(CourseConflict::getLeftCourse, Lecture::getCourse))
.join(Lecture.class,
equal((courseConflict, lecture1) -> courseConflict.getRightCourse(), Lecture::getCourse),
equal((courseConflict, lecture1) -> lecture1.getPeriod(), Lecture::getPeriod))
.filter(((courseConflict, lecture1, lecture2) -> lecture1 != lecture2))
.penalize(ONE_HARD,
(courseConflict, lecture1, lecture2) -> courseConflict.getConflictCount())
.asConstraint("conflictingLecturesDifferentCourseInSamePeriod");
}
Constraint conflictingLecturesSameCourseInSamePeriod(ConstraintFactory factory) {
return factory.forEachUniquePair(Lecture.class,
equal(Lecture::getPeriod),
equal(Lecture::getCourse))
.penalize(ONE_HARD,
(lecture1, lecture2) -> 1 + lecture1.getCurriculumSet().size())
.asConstraint("conflictingLecturesSameCourseInSamePeriod");
}
Constraint roomOccupancy(ConstraintFactory factory) {
return factory.forEachUniquePair(Lecture.class,
equal(Lecture::getRoom),
equal(Lecture::getPeriod))
.penalize(ONE_HARD)
.asConstraint("roomOccupancy");
}
Constraint unavailablePeriodPenalty(ConstraintFactory factory) {
return factory.forEach(UnavailablePeriodPenalty.class)
.join(Lecture.class,
equal(UnavailablePeriodPenalty::getCourse, Lecture::getCourse),
equal(UnavailablePeriodPenalty::getPeriod, Lecture::getPeriod))
.penalize(ofHard(10))
.asConstraint("unavailablePeriodPenalty");
}
// ************************************************************************
// Soft constraints
// ************************************************************************
Constraint roomCapacity(ConstraintFactory factory) {
return factory.forEach(Lecture.class)
.filter(lecture -> lecture.getStudentSize() > lecture.getRoom().getCapacity())
.penalize(ofSoft(1),
lecture -> lecture.getStudentSize() - lecture.getRoom().getCapacity())
.asConstraint("roomCapacity");
}
Constraint minimumWorkingDays(ConstraintFactory factory) {
return factory.forEach(Lecture.class)
.groupBy(Lecture::getCourse, countDistinct(Lecture::getDay))
.filter((course, dayCount) -> course.getMinWorkingDaySize() > dayCount)
.penalize(ofSoft(5),
(course, dayCount) -> course.getMinWorkingDaySize() - dayCount)
.asConstraint("minimumWorkingDays");
}
Constraint curriculumCompactness(ConstraintFactory factory) {<FILL_FUNCTION_BODY>}
Constraint roomStability(ConstraintFactory factory) {
return factory.forEach(Lecture.class)
.groupBy(Lecture::getCourse, countDistinct(Lecture::getRoom))
.filter((course, roomCount) -> roomCount > 1)
.penalize(HardSoftScore.ONE_SOFT,
(course, roomCount) -> roomCount - 1)
.asConstraint("roomStability");
}
}
|
return factory.forEach(Curriculum.class)
.join(Lecture.class,
filtering((curriculum, lecture) -> lecture.getCurriculumSet().contains(curriculum)))
.ifNotExists(Lecture.class,
equal((curriculum, lecture) -> lecture.getDay(), Lecture::getDay),
equal((curriculum, lecture) -> lecture.getTimeslotIndex(), lecture -> lecture.getTimeslotIndex() + 1),
filtering((curriculum, lectureA, lectureB) -> lectureB.getCurriculumSet().contains(curriculum)))
.ifNotExists(Lecture.class,
equal((curriculum, lecture) -> lecture.getDay(), Lecture::getDay),
equal((curriculum, lecture) -> lecture.getTimeslotIndex(), lecture -> lecture.getTimeslotIndex() - 1),
filtering((curriculum, lectureA, lectureB) -> lectureB.getCurriculumSet().contains(curriculum)))
.penalize(ofSoft(2))
.asConstraint("curriculumCompactness");
| 1,088
| 264
| 1,352
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/curriculumcourse/solver/move/DifferentCourseSwapMoveFilter.java
|
DifferentCourseSwapMoveFilter
|
accept
|
class DifferentCourseSwapMoveFilter implements SelectionFilter<CourseSchedule, SwapMove> {
@Override
public boolean accept(ScoreDirector<CourseSchedule> scoreDirector, SwapMove move) {<FILL_FUNCTION_BODY>}
}
|
Lecture leftLecture = (Lecture) move.getLeftEntity();
Lecture rightLecture = (Lecture) move.getRightEntity();
return !leftLecture.getCourse().equals(rightLecture.getCourse());
| 69
| 69
| 138
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/PeriodPenalty.java
|
PeriodPenalty
|
toString
|
class PeriodPenalty extends AbstractPersistable {
public PeriodPenalty() {
}
public PeriodPenalty(long id, Topic leftTopic, Topic rightTopic, PeriodPenaltyType periodPenaltyType) {
super(id);
this.leftTopic = leftTopic;
this.rightTopic = rightTopic;
this.periodPenaltyType = periodPenaltyType;
}
private PeriodPenaltyType periodPenaltyType;
private Topic leftTopic;
private Topic rightTopic;
public PeriodPenaltyType getPeriodPenaltyType() {
return periodPenaltyType;
}
public void setPeriodPenaltyType(PeriodPenaltyType periodPenaltyType) {
this.periodPenaltyType = periodPenaltyType;
}
public Topic getLeftTopic() {
return leftTopic;
}
public void setLeftTopic(Topic leftTopic) {
this.leftTopic = leftTopic;
}
public Topic getRightTopic() {
return rightTopic;
}
public void setRightTopic(Topic rightTopic) {
this.rightTopic = rightTopic;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return periodPenaltyType + "@" + leftTopic.getId() + "&" + rightTopic.getId();
| 351
| 33
| 384
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/Topic.java
|
Topic
|
toString
|
class Topic extends AbstractPersistable {
private int duration; // in minutes
private Set<Student> studentSet;
// Calculated during initialization, not modified during score calculation.
private boolean frontLoadLarge;
private Set<Topic> coincidenceTopicSet = null;
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public Set<Student> getStudentSet() {
return studentSet;
}
public void setStudentSet(Set<Student> studentSet) {
this.studentSet = studentSet;
}
@JsonIgnore
public int getStudentSize() {
return studentSet.size();
}
public boolean isFrontLoadLarge() {
return frontLoadLarge;
}
public void setFrontLoadLarge(boolean frontLoadLarge) {
this.frontLoadLarge = frontLoadLarge;
}
public Set<Topic> getCoincidenceTopicSet() {
return coincidenceTopicSet;
}
public void setCoincidenceTopicSet(Set<Topic> coincidenceTopicSet) {
this.coincidenceTopicSet = coincidenceTopicSet;
}
public boolean hasCoincidenceTopic() {
return coincidenceTopicSet != null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
// ************************************************************************
// With methods
// ************************************************************************
public Topic withId(long id) {
this.setId(id);
return this;
}
public Topic withDuration(int duration) {
this.setDuration(duration);
return this;
}
public Topic withStudents(Student... students) {
this.setStudentSet(Arrays.stream(students).collect(Collectors.toSet()));
return this;
}
public Topic withFrontLoadLarge(boolean frontLoadLarge) {
this.setFrontLoadLarge(frontLoadLarge);
return this;
}
public Topic withCoincidenceTopicSet(Set<Topic> coincidenceTopicSet) {
this.setCoincidenceTopicSet(coincidenceTopicSet);
return this;
}
}
|
return id == null ? "no id" : Long.toString(id);
| 600
| 21
| 621
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/solver/PeriodUpdatingVariableListener.java
|
PeriodUpdatingVariableListener
|
updatePeriod
|
class PeriodUpdatingVariableListener implements VariableListener<Examination, LeadingExam> {
@Override
public void beforeEntityAdded(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
// Do nothing
}
@Override
public void afterEntityAdded(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
updatePeriod(scoreDirector, leadingExam);
}
@Override
public void beforeVariableChanged(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
// Do nothing
}
@Override
public void afterVariableChanged(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
updatePeriod(scoreDirector, leadingExam);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
// Do nothing
}
@Override
public void afterEntityRemoved(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {
// Do nothing
}
protected void updatePeriod(ScoreDirector<Examination> scoreDirector, LeadingExam leadingExam) {<FILL_FUNCTION_BODY>}
}
|
Period period = leadingExam.getPeriod();
for (FollowingExam followingExam : leadingExam.getFollowingExamList()) {
scoreDirector.beforeVariableChanged(followingExam, "period");
followingExam.setPeriod(period);
scoreDirector.afterVariableChanged(followingExam, "period");
}
| 329
| 85
| 414
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/solver/TopicConflict.java
|
TopicConflict
|
toString
|
class TopicConflict extends AbstractPersistable implements Comparable<TopicConflict> {
private static final Comparator<Topic> TOPIC_COMPARATOR = Comparator.comparingLong(Topic::getId);
private static final Comparator<TopicConflict> COMPARATOR = Comparator
.comparing(TopicConflict::getLeftTopic, TOPIC_COMPARATOR)
.thenComparing(TopicConflict::getRightTopic, TOPIC_COMPARATOR);
private Topic leftTopic;
private Topic rightTopic;
private int studentSize;
public TopicConflict() {
}
public TopicConflict(long id, Topic leftTopic, Topic rightTopic, int studentSize) {
super(id);
this.leftTopic = leftTopic;
this.rightTopic = rightTopic;
this.studentSize = studentSize;
}
public Topic getLeftTopic() {
return leftTopic;
}
public void setLeftTopic(Topic leftTopic) {
this.leftTopic = leftTopic;
}
public Topic getRightTopic() {
return rightTopic;
}
public void setRightTopic(Topic rightTopic) {
this.rightTopic = rightTopic;
}
public int getStudentSize() {
return studentSize;
}
public void setStudentSize(int studentSize) {
this.studentSize = studentSize;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TopicConflict other = (TopicConflict) o;
return Objects.equals(leftTopic, other.leftTopic) &&
Objects.equals(rightTopic, other.rightTopic);
}
@Override
public int hashCode() {
return Objects.hash(leftTopic, rightTopic);
}
@Override
public int compareTo(TopicConflict other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return leftTopic + " & " + rightTopic + " = " + studentSize;
| 600
| 25
| 625
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/flightcrewscheduling/domain/Employee.java
|
Employee
|
getFlightDurationTotalInMinutes
|
class Employee extends AbstractPersistable {
private String name;
private Airport homeAirport;
private Set<Skill> skillSet;
private Set<LocalDate> unavailableDaySet;
@InverseRelationShadowVariable(sourceVariableName = "employee")
private SortedSet<FlightAssignment> flightAssignmentSet;
public Employee() {
}
public Employee(long id, String name, Airport homeAirport) {
super(id);
this.name = name;
this.homeAirport = homeAirport;
}
public boolean hasSkill(Skill skill) {
return skillSet.contains(skill);
}
public boolean isAvailable(LocalDate date) {
return !unavailableDaySet.contains(date);
}
public boolean isFirstAssignmentDepartingFromHome() {
if (flightAssignmentSet.isEmpty()) {
return true;
}
FlightAssignment firstAssignment = flightAssignmentSet.first();
// TODO allow taking a taxi, but penalize it with a soft score instead
return firstAssignment.getFlight().getDepartureAirport() == homeAirport;
}
public boolean isLastAssignmentArrivingAtHome() {
if (flightAssignmentSet.isEmpty()) {
return true;
}
FlightAssignment lastAssignment = flightAssignmentSet.last();
// TODO allow taking a taxi, but penalize it with a soft score instead
return lastAssignment.getFlight().getArrivalAirport() == homeAirport;
}
public long countInvalidConnections() {
// TODO Cache this to improve example performance.
// Especially useful for Constraint Streams, by which this is called multiple times per Employee.
long count = 0L;
FlightAssignment previousAssignment = null;
for (FlightAssignment assignment : flightAssignmentSet) {
if (previousAssignment != null
&& previousAssignment.getFlight().getArrivalAirport() != assignment.getFlight().getDepartureAirport()) {
count++;
}
previousAssignment = assignment;
}
return count;
}
public long getFlightDurationTotalInMinutes() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return name;
}
// ************************************************************************
// Simple getters and setters
// ************************************************************************
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Airport getHomeAirport() {
return homeAirport;
}
public void setHomeAirport(Airport homeAirport) {
this.homeAirport = homeAirport;
}
public Set<Skill> getSkillSet() {
return skillSet;
}
public void setSkillSet(Set<Skill> skillSet) {
this.skillSet = skillSet;
}
public Set<LocalDate> getUnavailableDaySet() {
return unavailableDaySet;
}
public void setUnavailableDaySet(Set<LocalDate> unavailableDaySet) {
this.unavailableDaySet = unavailableDaySet;
}
public SortedSet<FlightAssignment> getFlightAssignmentSet() {
return flightAssignmentSet;
}
public void setFlightAssignmentSet(SortedSet<FlightAssignment> flightAssignmentSet) {
this.flightAssignmentSet = flightAssignmentSet;
}
}
|
long total = 0L;
for (FlightAssignment flightAssignment : flightAssignmentSet) {
total += flightAssignment.getFlightDurationInMinutes();
}
return total;
| 919
| 53
| 972
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/flightcrewscheduling/score/FlightCrewSchedulingConstraintProvider.java
|
FlightCrewSchedulingConstraintProvider
|
transferBetweenTwoFlights
|
class FlightCrewSchedulingConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
requiredSkill(constraintFactory),
flightConflict(constraintFactory),
transferBetweenTwoFlights(constraintFactory),
employeeUnavailability(constraintFactory),
firstAssignmentNotDepartingFromHome(constraintFactory),
lastAssignmentNotArrivingAtHome(constraintFactory)
};
}
private Constraint requiredSkill(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(FlightAssignment.class)
.filter(flightAssignment -> {
Skill requiredSkill = flightAssignment.getRequiredSkill();
return !flightAssignment.getEmployee().hasSkill(requiredSkill);
})
.penalize(HardSoftLongScore.ofHard(100))
.asConstraint("Required skill");
}
private Constraint flightConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(FlightAssignment.class, equal(FlightAssignment::getEmployee),
overlapping(flightAssignment -> flightAssignment.getFlight().getDepartureUTCDateTime(),
flightAssignment -> flightAssignment.getFlight().getArrivalUTCDateTime()))
.penalize(HardSoftLongScore.ofHard(10))
.asConstraint("Flight conflict");
}
private Constraint transferBetweenTwoFlights(ConstraintFactory constraintFactory) {<FILL_FUNCTION_BODY>}
private Constraint employeeUnavailability(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(FlightAssignment.class)
.filter(flightAssignment -> {
LocalDate departureUTCDate = flightAssignment.getFlight().getDepartureUTCDate();
return !flightAssignment.getEmployee().isAvailable(departureUTCDate);
})
.penalize(HardSoftLongScore.ofHard(10))
.asConstraint("Employee unavailable");
}
private Constraint firstAssignmentNotDepartingFromHome(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Employee.class)
.filter(employee -> !employee.isFirstAssignmentDepartingFromHome())
.penalize(HardSoftLongScore.ofSoft(1_000_000))
.asConstraint("First assignment not departing from home");
}
private Constraint lastAssignmentNotArrivingAtHome(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Employee.class)
.filter(employee -> !employee.isLastAssignmentArrivingAtHome())
.penalize(HardSoftLongScore.ofSoft(1_000_000))
.asConstraint("Last assignment not arriving at home");
}
}
|
return constraintFactory.forEach(Employee.class)
.filter(employee -> employee.countInvalidConnections() > 0)
.penalizeLong(HardSoftLongScore.ofHard(1), Employee::countInvalidConnections)
.asConstraint("Transfer between two flights");
| 724
| 74
| 798
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/flightcrewscheduling/swingui/FlightCrewSchedulingWorldPanel.java
|
FlightCrewSchedulingWorldPanel
|
resetPanel
|
class FlightCrewSchedulingWorldPanel extends JPanel {
private static final int TEXT_SIZE = 12;
private static final int LOCATION_NAME_TEXT_SIZE = 8;
private final FlightCrewSchedulingPanel flightCrewSchedulingPanel;
private BufferedImage canvas = null;
private LatitudeLongitudeTranslator translator = null;
public FlightCrewSchedulingWorldPanel(FlightCrewSchedulingPanel flightCrewSchedulingPanel) {
this.flightCrewSchedulingPanel = flightCrewSchedulingPanel;
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// TODO Not thread-safe during solving
FlightCrewSolution solution = FlightCrewSchedulingWorldPanel.this.flightCrewSchedulingPanel.getSolution();
if (solution != null) {
resetPanel(solution);
}
}
});
}
public void resetPanel(FlightCrewSolution solution) {<FILL_FUNCTION_BODY>}
public void updatePanel(FlightCrewSolution solution) {
resetPanel(solution);
}
private Graphics2D createCanvas(double width, double height) {
int canvasWidth = (int) Math.ceil(width) + 1;
int canvasHeight = (int) Math.ceil(height) + 1;
canvas = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = canvas.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
return g;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (canvas != null) {
g.drawImage(canvas, 0, 0, this);
}
}
}
|
translator = new LatitudeLongitudeTranslator();
for (Airport airport : solution.getAirportList()) {
translator.addCoordinates(airport.getLatitude(), airport.getLongitude());
}
Dimension size = getSize();
double width = size.getWidth();
double height = size.getHeight();
translator.prepareFor(width, height);
Graphics2D g = createCanvas(width, height);
g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
g.setColor(TangoColorFactory.PLUM_2);
for (Airport airport : solution.getAirportList()) {
int x = translator.translateLongitudeToX(airport.getLongitude());
int y = translator.translateLatitudeToY(airport.getLatitude());
g.fillRect(x - 1, y - 1, 3, 3);
g.drawString(airport.getCode(), x + 3, y - 3);
}
g.setColor(TangoColorFactory.CHOCOLATE_1);
for (Flight flight : solution.getFlightList()) {
Airport departureAirport = flight.getDepartureAirport();
Airport arrivalAirport = flight.getArrivalAirport();
translator.drawRoute(g, departureAirport.getLongitude(), departureAirport.getLatitude(),
arrivalAirport.getLongitude(), arrivalAirport.getLatitude(),
true, false);
}
g.setFont(g.getFont().deriveFont((float) TEXT_SIZE));
// Legend
g.setColor(TangoColorFactory.PLUM_2);
g.fillRect(6, (int) height - 11, 3, 3);
g.drawString("Airport", 15, (int) height - 5);
repaint();
| 490
| 483
| 973
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/machinereassignment/domain/MrProcess.java
|
MrProcess
|
getUsageMultiplicand
|
class MrProcess extends AbstractPersistable {
private MrService service;
private int moveCost;
// Order is equal to resourceList so resource.getIndex() can be used
private List<MrProcessRequirement> processRequirementList;
public MrProcess() {
}
public MrProcess(int moveCost) {
this.moveCost = moveCost;
}
public MrProcess(MrService service) {
this.service = service;
}
public MrProcess(long id, MrService service, int moveCost) {
super(id);
this.service = service;
this.moveCost = moveCost;
}
public MrService getService() {
return service;
}
public int getMoveCost() {
return moveCost;
}
public List<MrProcessRequirement> getProcessRequirementList() {
return processRequirementList;
}
public void setProcessRequirementList(List<MrProcessRequirement> processRequirementList) {
this.processRequirementList = processRequirementList;
}
public MrProcessRequirement getProcessRequirement(MrResource resource) {
return processRequirementList.get(resource.getIndex());
}
public long getUsage(MrResource resource) {
return resource.getIndex() >= processRequirementList.size() ? 0L
: processRequirementList.get(resource.getIndex()).getUsage();
}
@JsonIgnore
public int getUsageMultiplicand() {<FILL_FUNCTION_BODY>}
}
|
int multiplicand = 1;
for (MrProcessRequirement processRequirement : processRequirementList) {
multiplicand *= processRequirement.getUsage();
}
return multiplicand;
| 393
| 51
| 444
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/machinereassignment/optional/score/MrMachineUsage.java
|
MrMachineUsage
|
equals
|
class MrMachineUsage implements Comparable<MrMachineUsage> {
private static final Comparator<MrMachineUsage> COMPARATOR = comparing(
(MrMachineUsage machineUsage) -> machineUsage.getClass().getName())
.thenComparing(machineUsage -> machineUsage.machineCapacity, comparingLong(MrMachineCapacity::getId))
.thenComparingLong(machineUsage -> machineUsage.usage);
private MrMachineCapacity machineCapacity;
private long usage;
public MrMachineUsage(MrMachineCapacity machineCapacity, long usage) {
this.machineCapacity = machineCapacity;
this.usage = usage;
}
public MrMachineCapacity getMachineCapacity() {
return machineCapacity;
}
public long getUsage() {
return usage;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(machineCapacity, usage);
}
public MrMachine getMachine() {
return machineCapacity.getMachine();
}
public MrResource getResource() {
return machineCapacity.getResource();
}
public boolean isTransientlyConsumed() {
return machineCapacity.getResource().isTransientlyConsumed();
}
public long getLoadCostWeight() {
return machineCapacity.getResource().getLoadCostWeight();
}
public long getMaximumAvailable() {
return machineCapacity.getMaximumCapacity() - usage;
}
public long getSafetyAvailable() {
return machineCapacity.getSafetyCapacity() - usage;
}
@Override
public String toString() {
return getMachine() + "-" + getResource() + "=" + usage;
}
@Override
public int compareTo(MrMachineUsage o) {
return COMPARATOR.compare(this, o);
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final MrMachineUsage other = (MrMachineUsage) o;
return Objects.equals(machineCapacity, other.machineCapacity) &&
usage == other.usage;
| 502
| 89
| 591
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/machinereassignment/optional/solver/selector/MrMachineProbabilityWeightFactory.java
|
MrMachineProbabilityWeightFactory
|
createProbabilityWeight
|
class MrMachineProbabilityWeightFactory
implements SelectionProbabilityWeightFactory<MachineReassignment, MrProcessAssignment> {
@Override
public double createProbabilityWeight(ScoreDirector<MachineReassignment> scoreDirector,
MrProcessAssignment processAssignment) {<FILL_FUNCTION_BODY>}
}
|
MachineReassignment machineReassignment = scoreDirector.getWorkingSolution();
MrMachine machine = processAssignment.getMachine();
// TODO reuse usage calculated by of the ScoreCalculator which is a delta
long[] usage = new long[machineReassignment.getResourceList().size()];
for (MrProcessAssignment someProcessAssignment : machineReassignment.getProcessAssignmentList()) {
if (someProcessAssignment.getMachine() == machine) {
MrProcess process = someProcessAssignment.getProcess();
for (MrResource resource : machineReassignment.getResourceList()) {
usage[resource.getIndex()] += process.getUsage(resource);
}
}
}
double sum = 0.0;
for (MrResource resource : machineReassignment.getResourceList()) {
double available = (machine.getMachineCapacity(resource).getSafetyCapacity() - usage[resource.getIndex()]);
sum += (available * available);
}
return sum + 1.0;
| 82
| 256
| 338
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/machinereassignment/swingui/MachineReassignmentPanel.java
|
MachineReassignmentPanel
|
updatePanel
|
class MachineReassignmentPanel extends SolutionPanel<MachineReassignment> {
public static final String LOGO_PATH = "/org/optaplanner/examples/machinereassignment/swingui/machineReassignmentLogo.png";
private JPanel machineListPanel;
private MrMachinePanel unassignedPanel;
private JLabel tooBigLabel = null;
private Map<MrMachine, MrMachinePanel> machineToPanelMap;
public MachineReassignmentPanel() {
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
createMachineListPanel();
JPanel headerPanel = new JPanel();
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(headerPanel).addComponent(machineListPanel));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(headerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(machineListPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE));
}
private void createMachineListPanel() {
machineListPanel = new JPanel(new GridLayout(0, 1));
unassignedPanel = new MrMachinePanel(this, Collections.emptyList(), null);
machineListPanel.add(unassignedPanel);
machineToPanelMap = new LinkedHashMap<>();
machineToPanelMap.put(null, unassignedPanel);
}
@Override
public void resetPanel(MachineReassignment machineReassignment) {
for (MrMachinePanel machinePanel : machineToPanelMap.values()) {
if (machinePanel.getMachine() != null) {
machineListPanel.remove(machinePanel);
}
}
machineToPanelMap.clear();
machineToPanelMap.put(null, unassignedPanel);
unassignedPanel.clearProcessAssignments();
updatePanel(machineReassignment);
}
@Override
public void updatePanel(MachineReassignment machineReassignment) {<FILL_FUNCTION_BODY>}
public void deleteMachine(final MrMachine machine) {
logger.info("Scheduling delete of machine ({}).", machine);
doProblemChange((machineReassignment, problemChangeDirector) -> problemChangeDirector.lookUpWorkingObject(machine)
.ifPresentOrElse(workingMachine -> {
// First remove the problem fact from all planning entities that use it
for (MrProcessAssignment processAssignment : machineReassignment.getProcessAssignmentList()) {
if (processAssignment.getOriginalMachine() == workingMachine) {
problemChangeDirector.changeProblemProperty(processAssignment,
workingProcessAssignment -> workingProcessAssignment.setOriginalMachine(null));
}
if (processAssignment.getMachine() == workingMachine) {
problemChangeDirector.changeVariable(processAssignment, "machine",
workingProcessAssignment -> workingProcessAssignment.setMachine(null));
}
}
// A SolutionCloner does not clone problem fact lists (such as machineList)
// Shallow clone the machineList so only workingSolution is affected, not bestSolution or guiSolution
ArrayList<MrMachine> machineList = new ArrayList<>(machineReassignment.getMachineList());
machineReassignment.setMachineList(machineList);
// Remove it the problem fact itself
problemChangeDirector.removeProblemFact(workingMachine, machineList::remove);
}, () -> logger.info("Skipping problem change due to machine ({}) already deleted.", machine)));
}
}
|
List<MrResource> resourceList = machineReassignment.getResourceList();
unassignedPanel.setResourceList(resourceList);
if (machineReassignment.getMachineList().size() > 1000) {
if (tooBigLabel == null) {
tooBigLabel = new JLabel("The dataset is too big to show.");
machineListPanel.add(tooBigLabel);
}
} else {
if (tooBigLabel != null) {
machineListPanel.remove(tooBigLabel);
tooBigLabel = null;
}
Set<MrMachine> deadMachineSet = new LinkedHashSet<>(machineToPanelMap.keySet());
deadMachineSet.remove(null);
for (MrMachine machine : machineReassignment.getMachineList()) {
deadMachineSet.remove(machine);
MrMachinePanel machinePanel = machineToPanelMap.get(machine);
if (machinePanel == null) {
machinePanel = new MrMachinePanel(this, resourceList, machine);
machineListPanel.add(machinePanel);
machineToPanelMap.put(machine, machinePanel);
}
machinePanel.clearProcessAssignments();
}
unassignedPanel.clearProcessAssignments();
for (MrProcessAssignment processAssignment : machineReassignment.getProcessAssignmentList()) {
MrMachine machine = processAssignment.getMachine();
MrMachinePanel machinePanel = machineToPanelMap.get(machine);
machinePanel.addProcessAssignment(processAssignment);
}
for (MrMachine deadMachine : deadMachineSet) {
MrMachinePanel deadMachinePanel = machineToPanelMap.remove(deadMachine);
machineListPanel.remove(deadMachinePanel);
}
for (MrMachinePanel machinePanel : machineToPanelMap.values()) {
machinePanel.update();
}
}
| 915
| 454
| 1,369
|
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.machinereassignment.domain.MachineReassignment>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.machinereassignment.domain.MachineReassignment>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.machinereassignment.domain.MachineReassignment getSolution() ,public SolutionBusiness<org.optaplanner.examples.machinereassignment.domain.MachineReassignment,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.machinereassignment.domain.MachineReassignment> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.machinereassignment.domain.MachineReassignment) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.machinereassignment.domain.MachineReassignment,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.machinereassignment.domain.MachineReassignment>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.machinereassignment.domain.MachineReassignment) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.machinereassignment.domain.MachineReassignment,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.machinereassignment.domain.MachineReassignment> solverAndPersistenceFrame,protected boolean useIndictmentColor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/meetingscheduling/domain/Day.java
|
Day
|
equals
|
class Day extends AbstractPersistable
implements Comparable<Day>, Labeled {
private int dayOfYear;
public Day() {
}
public Day(long id, int dayOfYear) {
super(id);
this.dayOfYear = dayOfYear;
}
private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("E", Locale.ENGLISH);
public int getDayOfYear() {
return dayOfYear;
}
public void setDayOfYear(int dayOfYear) {
this.dayOfYear = dayOfYear;
}
public String getDateString() {
return DAY_FORMATTER.format(toDate());
}
public LocalDate toDate() {
return LocalDate.ofYearDay(LocalDate.now().getYear(), dayOfYear);
}
@Override
public String getLabel() {
return getDateString();
}
@Override
public String toString() {
return getDateString();
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return dayOfYear;
}
@Override
public int compareTo(Day o) {
return Integer.compare(this.dayOfYear, o.dayOfYear);
}
}
|
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
Day day = (Day) other;
return dayOfYear == day.dayOfYear;
| 357
| 64
| 421
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/meetingscheduling/domain/TimeGrain.java
|
TimeGrain
|
hashCode
|
class TimeGrain extends AbstractPersistable
implements Comparable<TimeGrain>, Labeled {
private static final Comparator<TimeGrain> COMPARATOR = Comparator.comparing(TimeGrain::getDay)
.thenComparingInt(TimeGrain::getStartingMinuteOfDay);
/**
* Time granularity is 15 minutes (which is often recommended when dealing with humans for practical purposes).
*/
public static final int GRAIN_LENGTH_IN_MINUTES = 15;
private int grainIndex;
private Day day;
private int startingMinuteOfDay;
public TimeGrain() {
}
public TimeGrain(long id, int grainIndex, Day day, int startingMinuteOfDay) {
super(id);
this.grainIndex = grainIndex;
this.day = day;
this.startingMinuteOfDay = startingMinuteOfDay;
}
public int getGrainIndex() {
return grainIndex;
}
public void setGrainIndex(int grainIndex) {
this.grainIndex = grainIndex;
}
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
public int getStartingMinuteOfDay() {
return startingMinuteOfDay;
}
public void setStartingMinuteOfDay(int startingMinuteOfDay) {
this.startingMinuteOfDay = startingMinuteOfDay;
}
public LocalDate getDate() {
return day.toDate();
}
public LocalTime getTime() {
return LocalTime.of(startingMinuteOfDay / 60, startingMinuteOfDay % 60);
}
public LocalDateTime getDateTime() {
return LocalDateTime.of(getDate(), getTime());
}
public String getTimeString() {
int hourOfDay = startingMinuteOfDay / 60;
int minuteOfHour = startingMinuteOfDay % 60;
return (hourOfDay < 10 ? "0" : "") + hourOfDay
+ ":" + (minuteOfHour < 10 ? "0" : "") + minuteOfHour;
}
public String getDateTimeString() {
return day.getDateString() + " " + getTimeString();
}
@Override
public String getLabel() {
return getTimeString();
}
@Override
public String toString() {
return grainIndex + "(" + getDateTimeString() + ")";
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
TimeGrain timeGrain = (TimeGrain) other;
if (startingMinuteOfDay != timeGrain.startingMinuteOfDay)
return false;
return Objects.equals(day, timeGrain.day);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public int compareTo(TimeGrain other) {
return COMPARATOR.compare(this, other);
}
}
|
int result = day != null ? day.hashCode() : 0;
result = 31 * result + startingMinuteOfDay;
return result;
| 842
| 42
| 884
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/meetingscheduling/swingui/MeetingSchedulingPanel.java
|
MeetingAssignmentAction
|
actionPerformed
|
class MeetingAssignmentAction extends AbstractAction {
private final MeetingAssignment meetingAssignment;
public MeetingAssignmentAction(MeetingAssignment meetingAssignment) {
super(meetingAssignment.getLabel());
putValue(SHORT_DESCRIPTION, "<html>Topic: " + meetingAssignment.getMeeting().getTopic() + "<br/>"
+ "Date and time: "
+ Objects.requireNonNullElse(meetingAssignment.getStartingDateTimeString(), "unassigned") + "<br/>"
+ "Duration: " + meetingAssignment.getMeeting().getDurationString() + "<br/>"
+ "Room: " + Objects.requireNonNullElse(meetingAssignment.getRoom(), "unassigned")
+ "</html>");
this.meetingAssignment = meetingAssignment;
}
@Override
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
}
|
JPanel listFieldsPanel = new JPanel(new GridLayout(3, 2));
listFieldsPanel.add(new JLabel("Starting time grain:"));
MeetingSchedule meetingSchedule = getSolution();
List<TimeGrain> timeGrainList = meetingSchedule.getTimeGrainList();
// Add 1 to array size to add null, which makes the entity unassigned
JComboBox timeGrainListField = new JComboBox(
timeGrainList.toArray(new Object[timeGrainList.size() + 1]));
LabeledComboBoxRenderer.applyToComboBox(timeGrainListField);
timeGrainListField.setSelectedItem(meetingAssignment.getStartingTimeGrain());
listFieldsPanel.add(timeGrainListField);
listFieldsPanel.add(new JLabel("Room:"));
List<Room> roomList = meetingSchedule.getRoomList();
// Add 1 to array size to add null, which makes the entity unassigned
JComboBox roomListField = new JComboBox(
roomList.toArray(new Object[roomList.size() + 1]));
LabeledComboBoxRenderer.applyToComboBox(roomListField);
roomListField.setSelectedItem(meetingAssignment.getRoom());
listFieldsPanel.add(roomListField);
listFieldsPanel.add(new JLabel("Pinned:"));
JCheckBox pinnedField = new JCheckBox("cannot move during solving");
pinnedField.setSelected(meetingAssignment.isPinned());
listFieldsPanel.add(pinnedField);
int result = JOptionPane.showConfirmDialog(MeetingSchedulingPanel.this.getRootPane(), listFieldsPanel,
"Select time grain and room", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
TimeGrain toStartingTimeGrain = (TimeGrain) timeGrainListField.getSelectedItem();
if (meetingAssignment.getStartingTimeGrain() != toStartingTimeGrain) {
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(
meetingAssignment, "startingTimeGrain",
ma -> ma.setStartingTimeGrain(toStartingTimeGrain)));
}
Room toRoom = (Room) roomListField.getSelectedItem();
if (meetingAssignment.getRoom() != toRoom) {
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(
meetingAssignment, "room",
ma -> ma.setRoom(toRoom)));
}
boolean toPinned = pinnedField.isSelected();
if (meetingAssignment.isPinned() != toPinned) {
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector
.changeProblemProperty(meetingAssignment, ma -> ma.setPinned(toPinned)));
}
solverAndPersistenceFrame.resetScreen();
}
| 254
| 781
| 1,035
|
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule getSolution() ,public SolutionBusiness<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.meetingscheduling.domain.MeetingSchedule> solverAndPersistenceFrame,protected boolean useIndictmentColor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/app/NQueensHelloWorld.java
|
NQueensHelloWorld
|
toDisplayString
|
class NQueensHelloWorld {
public static void main(String[] args) {
// Build the Solver
SolverFactory<NQueens> solverFactory = SolverFactory.createFromXmlResource(
"org/optaplanner/examples/nqueens/nqueensSolverConfig.xml");
Solver<NQueens> solver = solverFactory.buildSolver();
// Load a problem with 8 queens
NQueens unsolved8Queens = new NQueensGenerator(true).createNQueens(8);
// Solve the problem
NQueens solved8Queens = solver.solve(unsolved8Queens);
// Display the result
System.out.println("\nSolved 8 queens:\n" + toDisplayString(solved8Queens));
}
public static String toDisplayString(NQueens nQueens) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder displayString = new StringBuilder();
int n = nQueens.getN();
List<Queen> queenList = nQueens.getQueenList();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
Queen queen = queenList.get(column);
if (queen.getColumn().getIndex() != column) {
throw new IllegalStateException("The queenList is not in the expected order.");
}
displayString.append(" ");
if (queen.getRow() != null && queen.getRow().getIndex() == row) {
displayString.append("Q");
} else {
displayString.append("_");
}
}
displayString.append("\n");
}
return displayString.toString();
| 238
| 213
| 451
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/domain/Queen.java
|
Queen
|
getRowIndex
|
class Queen extends AbstractPersistable {
private Column column;
// Planning variables: changes during planning, between score calculations.
private Row row;
public Queen() {
}
public Queen(long id) {
super(id);
}
public Queen(long id, Row row, Column column) {
this(id);
this.row = row;
this.column = column;
}
public Column getColumn() {
return column;
}
public void setColumn(Column column) {
this.column = column;
}
@PlanningVariable(strengthWeightFactoryClass = RowStrengthWeightFactory.class)
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public int getColumnIndex() {
return column.getIndex();
}
@JsonIgnore
public int getRowIndex() {<FILL_FUNCTION_BODY>}
@JsonIgnore
public int getAscendingDiagonalIndex() {
return (getColumnIndex() + getRowIndex());
}
@JsonIgnore
public int getDescendingDiagonalIndex() {
return (getColumnIndex() - getRowIndex());
}
@Override
public String toString() {
return "Queen-" + column.getIndex();
}
}
|
if (row == null) {
return Integer.MIN_VALUE;
}
return row.getIndex();
| 383
| 32
| 415
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/domain/solver/QueenDifficultyWeightFactory.java
|
QueenDifficultyWeightFactory
|
calculateDistanceFromMiddle
|
class QueenDifficultyWeightFactory implements SelectionSorterWeightFactory<NQueens, Queen> {
private static int calculateDistanceFromMiddle(int n, int columnIndex) {<FILL_FUNCTION_BODY>}
@Override
public QueenDifficultyWeight createSorterWeight(NQueens nQueens, Queen queen) {
int distanceFromMiddle = calculateDistanceFromMiddle(nQueens.getN(), queen.getColumnIndex());
return new QueenDifficultyWeight(queen, distanceFromMiddle);
}
public static class QueenDifficultyWeight implements Comparable<QueenDifficultyWeight> {
// The more difficult queens have a lower distance to the middle
private static final Comparator<QueenDifficultyWeight> COMPARATOR = Comparator
.comparingInt((QueenDifficultyWeight weight) -> -weight.distanceFromMiddle) // Decreasing.
.thenComparingInt(weight -> weight.queen.getColumnIndex()); // Tie-breaker.
private final Queen queen;
private final int distanceFromMiddle;
public QueenDifficultyWeight(Queen queen, int distanceFromMiddle) {
this.queen = queen;
this.distanceFromMiddle = distanceFromMiddle;
}
@Override
public int compareTo(QueenDifficultyWeight other) {
return COMPARATOR.compare(this, other);
}
}
}
|
int middle = n / 2;
int distanceFromMiddle = Math.abs(columnIndex - middle);
if ((n % 2 == 0) && (columnIndex < middle)) {
distanceFromMiddle--;
}
return distanceFromMiddle;
| 359
| 68
| 427
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/NQueensSolutionCloner.java
|
NQueensSolutionCloner
|
cloneSolution
|
class NQueensSolutionCloner implements SolutionCloner<NQueens> {
@Override
public NQueens cloneSolution(NQueens original) {<FILL_FUNCTION_BODY>}
}
|
NQueens clone = new NQueens(original.getId());
clone.setN(original.getN());
clone.setColumnList(original.getColumnList());
clone.setRowList(original.getRowList());
List<Queen> queenList = original.getQueenList();
List<Queen> clonedQueenList = new ArrayList<Queen>(queenList.size());
for (Queen originalQueen : queenList) {
Queen cloneQueen = new Queen(originalQueen.getId());
cloneQueen.setColumn(originalQueen.getColumn());
cloneQueen.setRow(originalQueen.getRow());
clonedQueenList.add(cloneQueen);
}
clone.setQueenList(clonedQueenList);
clone.setScore(original.getScore());
return clone;
| 56
| 213
| 269
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/score/NQueensBasicIncrementalScoreCalculator.java
|
NQueensBasicIncrementalScoreCalculator
|
resetWorkingSolution
|
class NQueensBasicIncrementalScoreCalculator implements IncrementalScoreCalculator<NQueens, SimpleScore> {
private List<Queen> insertedQueenList;
private int score;
@Override
public void resetWorkingSolution(NQueens nQueens) {<FILL_FUNCTION_BODY>}
@Override
public void beforeEntityAdded(Object entity) {
// Do nothing
}
@Override
public void afterEntityAdded(Object entity) {
insert((Queen) entity);
}
@Override
public void beforeVariableChanged(Object entity, String variableName) {
retract((Queen) entity);
}
@Override
public void afterVariableChanged(Object entity, String variableName) {
insert((Queen) entity);
}
@Override
public void beforeEntityRemoved(Object entity) {
retract((Queen) entity);
}
@Override
public void afterEntityRemoved(Object entity) {
// Do nothing
}
private void insert(Queen queen) {
Row row = queen.getRow();
if (row != null) {
for (Queen otherQueen : insertedQueenList) {
if (queen.getRowIndex() == otherQueen.getRowIndex()) {
score--;
}
if (queen.getAscendingDiagonalIndex() == otherQueen.getAscendingDiagonalIndex()) {
score--;
}
if (queen.getDescendingDiagonalIndex() == otherQueen.getDescendingDiagonalIndex()) {
score--;
}
}
insertedQueenList.add(queen);
}
}
private void retract(Queen queen) {
Row row = queen.getRow();
if (row != null) {
insertedQueenList.remove(queen);
for (Queen otherQueen : insertedQueenList) {
if (queen.getRowIndex() == otherQueen.getRowIndex()) {
score++;
}
if (queen.getAscendingDiagonalIndex() == otherQueen.getAscendingDiagonalIndex()) {
score++;
}
if (queen.getDescendingDiagonalIndex() == otherQueen.getDescendingDiagonalIndex()) {
score++;
}
}
}
}
@Override
public SimpleScore calculateScore() {
return SimpleScore.of(score);
}
}
|
insertedQueenList = new ArrayList<>(nQueens.getN());
score = 0;
for (Queen queen : nQueens.getQueenList()) {
insert(queen);
}
| 633
| 55
| 688
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/score/NQueensEasyScoreCalculator.java
|
NQueensEasyScoreCalculator
|
calculateScore
|
class NQueensEasyScoreCalculator implements EasyScoreCalculator<NQueens, SimpleScore> {
@Override
public SimpleScore calculateScore(NQueens nQueens) {<FILL_FUNCTION_BODY>}
}
|
int n = nQueens.getN();
List<Queen> queenList = nQueens.getQueenList();
int score = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Queen leftQueen = queenList.get(i);
Queen rightQueen = queenList.get(j);
if (leftQueen.getRow() != null && rightQueen.getRow() != null) {
if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) {
score--;
}
if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) {
score--;
}
if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) {
score--;
}
}
}
}
return SimpleScore.of(score);
| 60
| 256
| 316
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/score/NQueensMapBasedEasyScoreCalculator.java
|
NQueensMapBasedEasyScoreCalculator
|
calculateScore
|
class NQueensMapBasedEasyScoreCalculator implements EasyScoreCalculator<NQueens, SimpleScore> {
@Override
public SimpleScore calculateScore(NQueens nQueens) {<FILL_FUNCTION_BODY>}
}
|
int n = nQueens.getN();
List<Queen> queenList = nQueens.getQueenList();
Map<Integer, Integer> rowIndexCountMap = new HashMap<>(n);
Map<Integer, Integer> ascendingDiagonalIndexCountMap = new HashMap<>(n);
Map<Integer, Integer> descendingDiagonalIndexCountMap = new HashMap<>(n);
int score = 0;
for (Queen queen : queenList) {
if (queen.getRow() != null) {
int rowIndex = queen.getRowIndex();
Integer rowIndexCount = rowIndexCountMap.get(rowIndex);
if (rowIndexCount != null) {
score -= rowIndexCount;
rowIndexCount++;
} else {
rowIndexCount = 1;
}
rowIndexCountMap.put(rowIndex, rowIndexCount);
int ascendingDiagonalIndex = queen.getAscendingDiagonalIndex();
Integer ascendingDiagonalIndexCount = ascendingDiagonalIndexCountMap.get(ascendingDiagonalIndex);
if (ascendingDiagonalIndexCount != null) {
score -= ascendingDiagonalIndexCount;
ascendingDiagonalIndexCount++;
} else {
ascendingDiagonalIndexCount = 1;
}
ascendingDiagonalIndexCountMap.put(ascendingDiagonalIndex, ascendingDiagonalIndexCount);
int descendingDiagonalIndex = queen.getDescendingDiagonalIndex();
Integer descendingDiagonalIndexCount = descendingDiagonalIndexCountMap.get(descendingDiagonalIndex);
if (descendingDiagonalIndexCount != null) {
score -= descendingDiagonalIndexCount;
descendingDiagonalIndexCount++;
} else {
descendingDiagonalIndexCount = 1;
}
descendingDiagonalIndexCountMap.put(descendingDiagonalIndex, descendingDiagonalIndexCount);
}
}
return SimpleScore.of(score);
| 62
| 493
| 555
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/solver/move/RowChangeMove.java
|
RowChangeMove
|
equals
|
class RowChangeMove extends AbstractMove<NQueens> {
private Queen queen;
private Row toRow;
public RowChangeMove(Queen queen, Row toRow) {
this.queen = queen;
this.toRow = toRow;
}
@Override
public boolean isMoveDoable(ScoreDirector<NQueens> scoreDirector) {
return !Objects.equals(queen.getRow(), toRow);
}
@Override
public RowChangeMove createUndoMove(ScoreDirector<NQueens> scoreDirector) {
return new RowChangeMove(queen, queen.getRow());
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<NQueens> scoreDirector) {
scoreDirector.beforeVariableChanged(queen, "row"); // before changes are made
queen.setRow(toRow);
scoreDirector.afterVariableChanged(queen, "row"); // after changes are made
}
@Override
public RowChangeMove rebase(ScoreDirector<NQueens> destinationScoreDirector) {
return new RowChangeMove(destinationScoreDirector.lookUpWorkingObject(queen),
destinationScoreDirector.lookUpWorkingObject(toRow));
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Collections.singletonList(queen);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Collections.singletonList(toRow);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(queen, toRow);
}
@Override
public String toString() {
return queen + " {" + queen.getRow() + " -> " + toRow + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RowChangeMove other = (RowChangeMove) o;
return Objects.equals(queen, other.queen) &&
Objects.equals(toRow, other.toRow);
| 493
| 94
| 587
|
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.nqueens.domain.NQueens> doMove(ScoreDirector<org.optaplanner.examples.nqueens.domain.NQueens>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.nqueens.domain.NQueens>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/optional/solver/solution/CheatingNQueensPhaseCommand.java
|
CheatingNQueensPhaseCommand
|
changeWorkingSolution
|
class CheatingNQueensPhaseCommand implements CustomPhaseCommand<NQueens> {
@Override
public void changeWorkingSolution(ScoreDirector<NQueens> scoreDirector) {<FILL_FUNCTION_BODY>}
}
|
NQueens nQueens = scoreDirector.getWorkingSolution();
int n = nQueens.getN();
List<Queen> queenList = nQueens.getQueenList();
List<Row> rowList = nQueens.getRowList();
if (n % 2 != 0) {
Queen a = queenList.get(n - 1);
scoreDirector.beforeVariableChanged(a, "row");
a.setRow(rowList.get(n - 1));
scoreDirector.afterVariableChanged(a, "row");
n--;
}
int halfN = n / 2;
if (n % 6 != 2) {
for (int i = 0; i < halfN; i++) {
Queen a = queenList.get(i);
scoreDirector.beforeVariableChanged(a, "row");
a.setRow(rowList.get((2 * i) + 1));
scoreDirector.afterVariableChanged(a, "row");
Queen b = queenList.get(halfN + i);
scoreDirector.beforeVariableChanged(b, "row");
b.setRow(rowList.get(2 * i));
scoreDirector.afterVariableChanged(b, "row");
}
} else {
for (int i = 0; i < halfN; i++) {
Queen a = queenList.get(i);
scoreDirector.beforeVariableChanged(a, "row");
a.setRow(rowList.get((halfN + (2 * i) - 1) % n));
scoreDirector.afterVariableChanged(a, "row");
Queen b = queenList.get(n - i - 1);
scoreDirector.beforeVariableChanged(b, "row");
b.setRow(rowList.get(n - 1 - ((halfN + (2 * i) - 1) % n)));
scoreDirector.afterVariableChanged(b, "row");
}
}
scoreDirector.triggerVariableListeners();
| 64
| 512
| 576
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nqueens/swingui/NQueensPanel.java
|
NQueensPanel
|
resetPanel
|
class NQueensPanel extends SolutionPanel<NQueens> {
public static final String LOGO_PATH = "/org/optaplanner/examples/nqueens/swingui/nqueensLogo.png";
private static final String QUEEN_IMAGE_PATH = "/org/optaplanner/examples/nqueens/swingui/queenImage.png";
private ImageIcon queenImageIcon;
public NQueensPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBackground(Color.BLACK);
queenImageIcon = new ImageIcon(getClass().getResource(QUEEN_IMAGE_PATH));
}
@Override
public void resetPanel(NQueens nQueens) {<FILL_FUNCTION_BODY>}
private class QueenAction extends AbstractAction {
private Queen queen;
public QueenAction(Queen queen) {
super(null, queenImageIcon);
this.queen = queen;
}
@Override
public void actionPerformed(ActionEvent e) {
JPanel messagePanel = new JPanel(new BorderLayout());
messagePanel.add(new JLabel("Move to row: "), BorderLayout.WEST);
List<Row> rowList = getSolution().getRowList();
// Add 1 to array size to add null, which makes the entity unassigned
JComboBox rowListField = new JComboBox(
rowList.toArray(new Object[rowList.size() + 1]));
LabeledComboBoxRenderer.applyToComboBox(rowListField);
rowListField.setSelectedItem(queen.getRow());
messagePanel.add(rowListField, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(NQueensPanel.this.getRootPane(), messagePanel,
"Queen in column " + queen.getColumn().getIndex(),
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
Row toRow = (Row) rowListField.getSelectedItem();
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(queen, "row",
q -> q.setRow(toRow)));
solverAndPersistenceFrame.resetScreen();
}
}
}
}
|
removeAll();
repaint(); // When GridLayout doesn't fill up all the space
int n = nQueens.getN();
if (n > 100) {
JLabel tooBigToShowLabel = new JLabel("The dataset is too big to show.");
tooBigToShowLabel.setForeground(Color.WHITE);
add(tooBigToShowLabel);
return;
}
List<Queen> queenList = nQueens.getQueenList();
setLayout(new GridLayout(n, n));
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
Queen queen = queenList.get(column);
if (queen.getColumn().getIndex() != column) {
throw new IllegalStateException("The queenList is not in the expected order.");
}
String toolTip = "<html>Row " + row + "<br/>Column " + column + "</html>";
if (queen.getRow() != null && queen.getRow().getIndex() == row) {
JButton button = new JButton(new QueenAction(queen));
button.setMinimumSize(new Dimension(20, 20));
button.setPreferredSize(new Dimension(20, 20));
button.setToolTipText(toolTip);
add(button);
} else {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(TangoColorFactory.ALUMINIUM_6),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
Color background = (((row + column) % 2) == 0) ? Color.WHITE : TangoColorFactory.ALUMINIUM_3;
panel.setBackground(background);
panel.setToolTipText(toolTip);
add(panel);
}
}
}
| 599
| 500
| 1,099
|
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.nqueens.domain.NQueens>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.nqueens.domain.NQueens>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.nqueens.domain.NQueens getSolution() ,public SolutionBusiness<org.optaplanner.examples.nqueens.domain.NQueens,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.nqueens.domain.NQueens> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.nqueens.domain.NQueens) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.nqueens.domain.NQueens,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.nqueens.domain.NQueens>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.nqueens.domain.NQueens) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.nqueens.domain.NQueens,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.nqueens.domain.NQueens> solverAndPersistenceFrame,protected boolean useIndictmentColor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/Employee.java
|
Employee
|
toString
|
class Employee extends AbstractPersistable implements Labeled, Comparable<Employee> {
private String code;
private String name;
private Contract contract;
public Employee() {
}
public Employee(long id, String code, String name, Contract contract) {
super(id);
this.code = code;
this.name = name;
this.contract = contract;
}
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftDateKeyDeserializer.class)
private Map<ShiftDate, DayOffRequest> dayOffRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftDateKeyDeserializer.class)
private Map<ShiftDate, DayOnRequest> dayOnRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftKeyDeserializer.class)
private Map<Shift, ShiftOffRequest> shiftOffRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftKeyDeserializer.class)
private Map<Shift, ShiftOnRequest> shiftOnRequestMap;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
@JsonIgnore
public int getWeekendLength() {
return getContract().getWeekendLength();
}
public Map<ShiftDate, DayOffRequest> getDayOffRequestMap() {
return dayOffRequestMap;
}
public void setDayOffRequestMap(Map<ShiftDate, DayOffRequest> dayOffRequestMap) {
this.dayOffRequestMap = dayOffRequestMap;
}
public Map<ShiftDate, DayOnRequest> getDayOnRequestMap() {
return dayOnRequestMap;
}
public void setDayOnRequestMap(Map<ShiftDate, DayOnRequest> dayOnRequestMap) {
this.dayOnRequestMap = dayOnRequestMap;
}
public Map<Shift, ShiftOffRequest> getShiftOffRequestMap() {
return shiftOffRequestMap;
}
public void setShiftOffRequestMap(Map<Shift, ShiftOffRequest> shiftOffRequestMap) {
this.shiftOffRequestMap = shiftOffRequestMap;
}
public Map<Shift, ShiftOnRequest> getShiftOnRequestMap() {
return shiftOnRequestMap;
}
public void setShiftOnRequestMap(Map<Shift, ShiftOnRequest> shiftOnRequestMap) {
this.shiftOnRequestMap = shiftOnRequestMap;
}
@Override
public String getLabel() {
return "Employee " + name;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int compareTo(Employee employee) {
return name.compareTo(employee.name);
}
}
|
if (name == null) {
return super.toString();
}
return name;
| 852
| 27
| 879
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/ShiftAssignment.java
|
ShiftAssignment
|
isWeekend
|
class ShiftAssignment extends AbstractPersistable implements Comparable<ShiftAssignment> {
private static final Comparator<Shift> COMPARATOR = Comparator.comparing(Shift::getShiftDate)
.thenComparing(a -> a.getShiftType().getStartTimeString())
.thenComparing(a -> a.getShiftType().getEndTimeString());
private Shift shift;
private int indexInShift;
public ShiftAssignment() {
}
public ShiftAssignment(long id, Shift shift, int indexInShift) {
super(id);
this.shift = shift;
this.indexInShift = indexInShift;
}
// Planning variables: changes during planning, between score calculations.
@PlanningVariable(strengthComparatorClass = EmployeeStrengthComparator.class)
private Employee employee;
public Shift getShift() {
return shift;
}
public void setShift(Shift shift) {
this.shift = shift;
}
public int getIndexInShift() {
return indexInShift;
}
public void setIndexInShift(int indexInShift) {
this.indexInShift = indexInShift;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public ShiftDate getShiftDate() {
return shift.getShiftDate();
}
@JsonIgnore
public ShiftType getShiftType() {
return shift.getShiftType();
}
@JsonIgnore
public int getShiftDateDayIndex() {
return shift.getShiftDate().getDayIndex();
}
@JsonIgnore
public DayOfWeek getShiftDateDayOfWeek() {
return shift.getShiftDate().getDayOfWeek();
}
@JsonIgnore
public Contract getContract() {
if (employee == null) {
return null;
}
return employee.getContract();
}
@JsonIgnore
public boolean isWeekend() {<FILL_FUNCTION_BODY>}
@JsonIgnore
public int getWeekendSundayIndex() {
return shift.getShiftDate().getWeekendSundayIndex();
}
@Override
public String toString() {
return shift.toString();
}
@Override
public int compareTo(ShiftAssignment o) {
return COMPARATOR.compare(shift, o.shift);
}
}
|
if (employee == null) {
return false;
}
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shift.getShiftDate().getDayOfWeek();
return weekendDefinition.isWeekend(dayOfWeek);
| 674
| 73
| 747
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/ShiftDate.java
|
ShiftDate
|
getWeekendSundayIndex
|
class ShiftDate extends AbstractPersistable implements Labeled, Comparable<ShiftDate> {
private static final DateTimeFormatter LABEL_FORMATTER = DateTimeFormatter.ofPattern("E d MMM");
private int dayIndex; // TODO check if still needed/faster now that we use LocalDate instead of java.util.Date
private LocalDate date;
private List<Shift> shiftList;
public ShiftDate() {
}
public ShiftDate(long id) {
super(id);
}
public ShiftDate(long id, int dayIndex, LocalDate date) {
this(id);
this.dayIndex = dayIndex;
this.date = date;
}
public int getDayIndex() {
return dayIndex;
}
public void setDayIndex(int dayIndex) {
this.dayIndex = dayIndex;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
@JsonIgnore
public DayOfWeek getDayOfWeek() {
return date.getDayOfWeek();
}
public List<Shift> getShiftList() {
return shiftList;
}
public void setShiftList(List<Shift> shiftList) {
this.shiftList = shiftList;
}
@JsonIgnore
public int getWeekendSundayIndex() {<FILL_FUNCTION_BODY>}
@Override
public String getLabel() {
return date.format(LABEL_FORMATTER);
}
@Override
public String toString() {
return date.format(DateTimeFormatter.ISO_DATE);
}
@Override
public int compareTo(ShiftDate o) {
return this.getDate().compareTo(o.getDate());
}
}
|
switch (date.getDayOfWeek()) {
case MONDAY:
return dayIndex - 1;
case TUESDAY:
return dayIndex - 2;
case WEDNESDAY:
return dayIndex - 3;
case THURSDAY:
return dayIndex + 3;
case FRIDAY:
return dayIndex + 2;
case SATURDAY:
return dayIndex + 1;
case SUNDAY:
return dayIndex;
default:
throw new IllegalArgumentException("The dayOfWeek (" + date.getDayOfWeek() + ") is not valid.");
}
| 477
| 162
| 639
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/contract/MinMaxContractLine.java
|
MinMaxContractLine
|
getViolationAmount
|
class MinMaxContractLine extends ContractLine {
private boolean minimumEnabled;
private int minimumValue;
private int minimumWeight;
private boolean maximumEnabled;
private int maximumValue;
private int maximumWeight;
public MinMaxContractLine() {
}
public MinMaxContractLine(long id, Contract contract, ContractLineType contractLineType, boolean minimumEnabled,
boolean maximumEnabled) {
super(id, contract, contractLineType);
this.minimumEnabled = minimumEnabled;
this.maximumEnabled = maximumEnabled;
}
public boolean isViolated(int count) {
return getViolationAmount(count) != 0;
}
public int getViolationAmount(int count) {<FILL_FUNCTION_BODY>}
public boolean isMinimumEnabled() {
return minimumEnabled;
}
public void setMinimumEnabled(boolean minimumEnabled) {
this.minimumEnabled = minimumEnabled;
}
public int getMinimumValue() {
return minimumValue;
}
public void setMinimumValue(int minimumValue) {
this.minimumValue = minimumValue;
}
public int getMinimumWeight() {
return minimumWeight;
}
public void setMinimumWeight(int minimumWeight) {
this.minimumWeight = minimumWeight;
}
public boolean isMaximumEnabled() {
return maximumEnabled;
}
public void setMaximumEnabled(boolean maximumEnabled) {
this.maximumEnabled = maximumEnabled;
}
public int getMaximumValue() {
return maximumValue;
}
public void setMaximumValue(int maximumValue) {
this.maximumValue = maximumValue;
}
public int getMaximumWeight() {
return maximumWeight;
}
public void setMaximumWeight(int maximumWeight) {
this.maximumWeight = maximumWeight;
}
@Override
@JsonIgnore
public boolean isEnabled() {
return minimumEnabled || maximumEnabled;
}
}
|
if (minimumEnabled && count < minimumValue) {
return (minimumValue - count) * minimumWeight;
} else if (maximumEnabled && count > maximumValue) {
return (count - maximumValue) * maximumWeight;
} else {
return 0;
}
| 519
| 72
| 591
|
<methods>public org.optaplanner.examples.nurserostering.domain.contract.Contract getContract() ,public org.optaplanner.examples.nurserostering.domain.contract.ContractLineType getContractLineType() ,public abstract boolean isEnabled() ,public void setContract(org.optaplanner.examples.nurserostering.domain.contract.Contract) ,public void setContractLineType(org.optaplanner.examples.nurserostering.domain.contract.ContractLineType) ,public java.lang.String toString() <variables>private org.optaplanner.examples.nurserostering.domain.contract.Contract contract,private org.optaplanner.examples.nurserostering.domain.contract.ContractLineType contractLineType
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/pattern/FreeBefore2DaysWithAWorkDayPattern.java
|
FreeBefore2DaysWithAWorkDayPattern
|
toString
|
class FreeBefore2DaysWithAWorkDayPattern extends Pattern {
private DayOfWeek freeDayOfWeek;
public FreeBefore2DaysWithAWorkDayPattern() {
}
public FreeBefore2DaysWithAWorkDayPattern(long id, String code) {
super(id, code);
}
public FreeBefore2DaysWithAWorkDayPattern(long id, String code, DayOfWeek freeDayOfWeek) {
this(id, code);
this.freeDayOfWeek = freeDayOfWeek;
}
public DayOfWeek getFreeDayOfWeek() {
return freeDayOfWeek;
}
public void setFreeDayOfWeek(DayOfWeek freeDayOfWeek) {
this.freeDayOfWeek = freeDayOfWeek;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Free on " + freeDayOfWeek + " followed by a work day within 2 days";
| 225
| 27
| 252
|
<methods>public java.lang.String getCode() ,public int getWeight() ,public void setCode(java.lang.String) ,public void setWeight(int) ,public java.lang.String toString() <variables>protected java.lang.String code,protected int weight
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/pattern/ShiftType2DaysPattern.java
|
ShiftType2DaysPattern
|
toString
|
class ShiftType2DaysPattern extends Pattern {
private ShiftType dayIndex0ShiftType;
private ShiftType dayIndex1ShiftType;
public ShiftType2DaysPattern() {
}
public ShiftType2DaysPattern(long id, String code) {
super(id, code);
}
public ShiftType getDayIndex0ShiftType() {
return dayIndex0ShiftType;
}
public void setDayIndex0ShiftType(ShiftType dayIndex0ShiftType) {
this.dayIndex0ShiftType = dayIndex0ShiftType;
}
public ShiftType getDayIndex1ShiftType() {
return dayIndex1ShiftType;
}
public void setDayIndex1ShiftType(ShiftType dayIndex1ShiftType) {
this.dayIndex1ShiftType = dayIndex1ShiftType;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Work pattern: " + dayIndex0ShiftType + ", " + dayIndex1ShiftType;
| 246
| 27
| 273
|
<methods>public java.lang.String getCode() ,public int getWeight() ,public void setCode(java.lang.String) ,public void setWeight(int) ,public java.lang.String toString() <variables>protected java.lang.String code,protected int weight
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/pattern/ShiftType3DaysPattern.java
|
ShiftType3DaysPattern
|
toString
|
class ShiftType3DaysPattern extends Pattern {
private ShiftType dayIndex0ShiftType;
private ShiftType dayIndex1ShiftType;
private ShiftType dayIndex2ShiftType;
public ShiftType3DaysPattern() {
}
public ShiftType3DaysPattern(long id, String code) {
super(id, code);
}
public ShiftType getDayIndex0ShiftType() {
return dayIndex0ShiftType;
}
public void setDayIndex0ShiftType(ShiftType dayIndex0ShiftType) {
this.dayIndex0ShiftType = dayIndex0ShiftType;
}
public ShiftType getDayIndex1ShiftType() {
return dayIndex1ShiftType;
}
public void setDayIndex1ShiftType(ShiftType dayIndex1ShiftType) {
this.dayIndex1ShiftType = dayIndex1ShiftType;
}
public ShiftType getDayIndex2ShiftType() {
return dayIndex2ShiftType;
}
public void setDayIndex2ShiftType(ShiftType dayIndex2ShiftType) {
this.dayIndex2ShiftType = dayIndex2ShiftType;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Work pattern: " + dayIndex0ShiftType + ", " + dayIndex1ShiftType + ", " + dayIndex2ShiftType;
| 325
| 36
| 361
|
<methods>public java.lang.String getCode() ,public int getWeight() ,public void setCode(java.lang.String) ,public void setWeight(int) ,public java.lang.String toString() <variables>protected java.lang.String code,protected int weight
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/domain/solver/ShiftAssignmentDifficultyComparator.java
|
ShiftAssignmentDifficultyComparator
|
compare
|
class ShiftAssignmentDifficultyComparator implements Comparator<ShiftAssignment> {
private static final Comparator<Shift> COMPARATOR = comparing(Shift::getShiftDate,
Collections.reverseOrder(comparing(ShiftDate::getDate)))
.thenComparing(Shift::getShiftType, comparingLong(ShiftType::getId).reversed())
.thenComparingInt(Shift::getRequiredEmployeeSize);
@Override
public int compare(ShiftAssignment a, ShiftAssignment b) {<FILL_FUNCTION_BODY>}
}
|
Shift aShift = a.getShift();
Shift bShift = b.getShift();
return COMPARATOR.compare(aShift, bShift);
| 143
| 42
| 185
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/optional/score/EmployeeConsecutiveAssignmentStart.java
|
EmployeeConsecutiveAssignmentStart
|
toString
|
class EmployeeConsecutiveAssignmentStart implements Comparable<EmployeeConsecutiveAssignmentStart> {
public static boolean isWeekendAndNotFirstDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
return weekendDefinition.isWeekend(dayOfWeek) && weekendDefinition.getFirstDayOfWeekend() != dayOfWeek;
}
public static int getDistanceToFirstDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
DayOfWeek firstDayOfWeekend = weekendDefinition.getFirstDayOfWeekend();
int distance = dayOfWeek.getValue() - firstDayOfWeekend.getValue();
if (distance < 0) {
distance += 7;
}
return distance;
}
private static final Comparator<EmployeeConsecutiveAssignmentStart> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveAssignmentStart::getEmployee)
.thenComparing(EmployeeConsecutiveAssignmentStart::getShiftDate);
private Employee employee;
private ShiftDate shiftDate;
public EmployeeConsecutiveAssignmentStart(Employee employee, ShiftDate shiftDate) {
this.employee = employee;
this.shiftDate = shiftDate;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveAssignmentStart other = (EmployeeConsecutiveAssignmentStart) o;
return Objects.equals(employee, other.employee) &&
Objects.equals(shiftDate, other.shiftDate);
}
@Override
public int hashCode() {
return Objects.hash(employee, shiftDate);
}
@Override
public int compareTo(EmployeeConsecutiveAssignmentStart other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public Contract getContract() {
return employee.getContract();
}
public int getShiftDateDayIndex() {
return shiftDate.getDayIndex();
}
public boolean isWeekendAndNotFirstDayOfWeekend() {
return isWeekendAndNotFirstDayOfWeekend(employee, shiftDate);
}
public int getDistanceToFirstDayOfWeekend() {
return getDistanceToFirstDayOfWeekend(employee, shiftDate);
}
}
|
return employee + " " + shiftDate + " - ...";
| 822
| 19
| 841
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/optional/score/EmployeeConsecutiveWeekendAssignmentEnd.java
|
EmployeeConsecutiveWeekendAssignmentEnd
|
equals
|
class EmployeeConsecutiveWeekendAssignmentEnd implements Comparable<EmployeeConsecutiveWeekendAssignmentEnd> {
private static final Comparator<EmployeeConsecutiveWeekendAssignmentEnd> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveWeekendAssignmentEnd::getEmployee)
.thenComparingInt(EmployeeConsecutiveWeekendAssignmentEnd::getSundayIndex);
private Employee employee;
private int sundayIndex;
public EmployeeConsecutiveWeekendAssignmentEnd(Employee employee, int sundayIndex) {
this.employee = employee;
this.sundayIndex = sundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getSundayIndex() {
return sundayIndex;
}
public void setSundayIndex(int sundayIndex) {
this.sundayIndex = sundayIndex;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(employee, sundayIndex);
}
@Override
public int compareTo(EmployeeConsecutiveWeekendAssignmentEnd other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " weekend ... - " + sundayIndex;
}
public Contract getContract() {
return employee.getContract();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveWeekendAssignmentEnd other = (EmployeeConsecutiveWeekendAssignmentEnd) o;
return Objects.equals(employee, other.employee) &&
sundayIndex == other.sundayIndex;
| 424
| 106
| 530
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/optional/score/EmployeeConsecutiveWeekendAssignmentStart.java
|
EmployeeConsecutiveWeekendAssignmentStart
|
equals
|
class EmployeeConsecutiveWeekendAssignmentStart implements Comparable<EmployeeConsecutiveWeekendAssignmentStart> {
private static final Comparator<EmployeeConsecutiveWeekendAssignmentStart> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveWeekendAssignmentStart::getEmployee)
.thenComparingInt(EmployeeConsecutiveWeekendAssignmentStart::getSundayIndex);
private Employee employee;
private int sundayIndex;
public EmployeeConsecutiveWeekendAssignmentStart(Employee employee, int sundayIndex) {
this.employee = employee;
this.sundayIndex = sundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getSundayIndex() {
return sundayIndex;
}
public void setSundayIndex(int sundayIndex) {
this.sundayIndex = sundayIndex;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(employee, sundayIndex);
}
@Override
public int compareTo(EmployeeConsecutiveWeekendAssignmentStart other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " weekend " + sundayIndex + " - ...";
}
public Contract getContract() {
return employee.getContract();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveWeekendAssignmentStart other = (EmployeeConsecutiveWeekendAssignmentStart) o;
return Objects.equals(employee, other.employee) &&
sundayIndex == other.sundayIndex;
| 427
| 106
| 533
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/optional/score/EmployeeFreeSequence.java
|
EmployeeFreeSequence
|
equals
|
class EmployeeFreeSequence implements Comparable<EmployeeFreeSequence> {
private static final Comparator<EmployeeFreeSequence> COMPARATOR = Comparator.comparing(EmployeeFreeSequence::getEmployee)
.thenComparingInt(EmployeeFreeSequence::getFirstDayIndex)
.thenComparingInt(EmployeeFreeSequence::getLastDayIndex);
private Employee employee;
private int firstDayIndex;
private int lastDayIndex;
public EmployeeFreeSequence(Employee employee, int firstDayIndex, int lastDayIndex) {
this.employee = employee;
this.firstDayIndex = firstDayIndex;
this.lastDayIndex = lastDayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getFirstDayIndex() {
return firstDayIndex;
}
public void setFirstDayIndex(int firstDayIndex) {
this.firstDayIndex = firstDayIndex;
}
public int getLastDayIndex() {
return lastDayIndex;
}
public void setLastDayIndex(int lastDayIndex) {
this.lastDayIndex = lastDayIndex;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(employee, firstDayIndex, lastDayIndex);
}
@Override
public int compareTo(EmployeeFreeSequence other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " is free between " + firstDayIndex + " - " + lastDayIndex;
}
public int getDayLength() {
return lastDayIndex - firstDayIndex + 1;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeFreeSequence other = (EmployeeFreeSequence) o;
return Objects.equals(employee, other.employee) &&
firstDayIndex == other.firstDayIndex &&
lastDayIndex == other.lastDayIndex;
| 497
| 106
| 603
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/optional/score/EmployeeWeekendSequence.java
|
EmployeeWeekendSequence
|
equals
|
class EmployeeWeekendSequence implements Comparable<EmployeeWeekendSequence> {
private static final Comparator<EmployeeWeekendSequence> COMPARATOR = Comparator
.comparing(EmployeeWeekendSequence::getEmployee)
.thenComparingInt(EmployeeWeekendSequence::getFirstSundayIndex)
.thenComparingInt(EmployeeWeekendSequence::getLastSundayIndex);
private Employee employee;
private int firstSundayIndex;
private int lastSundayIndex;
public EmployeeWeekendSequence(Employee employee, int firstSundayIndex, int lastSundayIndex) {
this.employee = employee;
this.firstSundayIndex = firstSundayIndex;
this.lastSundayIndex = lastSundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getFirstSundayIndex() {
return firstSundayIndex;
}
public void setFirstSundayIndex(int firstSundayIndex) {
this.firstSundayIndex = firstSundayIndex;
}
public int getLastSundayIndex() {
return lastSundayIndex;
}
public void setLastSundayIndex(int lastSundayIndex) {
this.lastSundayIndex = lastSundayIndex;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(employee, firstSundayIndex, lastSundayIndex);
}
@Override
public int compareTo(EmployeeWeekendSequence other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " is working the weekend of " + firstSundayIndex + " - " + lastSundayIndex;
}
public int getWeekendLength() {
return ((lastSundayIndex - firstSundayIndex) / 7) + 1;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeWeekendSequence other = (EmployeeWeekendSequence) o;
return Objects.equals(employee, other.employee) &&
firstSundayIndex == other.firstSundayIndex &&
lastSundayIndex == other.lastSundayIndex;
| 516
| 108
| 624
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/persistence/NurseRosteringExporter.java
|
NurseRosteringOutputBuilder
|
writeSolution
|
class NurseRosteringOutputBuilder extends XmlOutputBuilder<NurseRoster> {
private NurseRoster nurseRoster;
@Override
public void setSolution(NurseRoster solution) {
nurseRoster = solution;
}
@Override
public void writeSolution() throws IOException {<FILL_FUNCTION_BODY>}
}
|
Element solutionElement = new Element("Solution");
document.setRootElement(solutionElement);
Element schedulingPeriodIDElement = new Element("SchedulingPeriodID");
schedulingPeriodIDElement.setText(nurseRoster.getCode());
solutionElement.addContent(schedulingPeriodIDElement);
Element competitorElement = new Element("Competitor");
competitorElement.setText("Geoffrey De Smet with OptaPlanner");
solutionElement.addContent(competitorElement);
Element softConstraintsPenaltyElement = new Element("SoftConstraintsPenalty");
softConstraintsPenaltyElement.setText(Integer.toString(nurseRoster.getScore().softScore()));
solutionElement.addContent(softConstraintsPenaltyElement);
for (ShiftAssignment shiftAssignment : nurseRoster.getShiftAssignmentList()) {
Shift shift = shiftAssignment.getShift();
if (shift != null) {
Element assignmentElement = new Element("Assignment");
solutionElement.addContent(assignmentElement);
Element dateElement = new Element("Date");
dateElement.setText(shift.getShiftDate().getDate().format(DateTimeFormatter.ISO_DATE));
assignmentElement.addContent(dateElement);
Element employeeElement = new Element("Employee");
employeeElement.setText(shiftAssignment.getEmployee().getCode());
assignmentElement.addContent(employeeElement);
Element shiftTypeElement = new Element("ShiftType");
shiftTypeElement.setText(shift.getShiftType().getCode());
assignmentElement.addContent(shiftTypeElement);
}
}
| 95
| 400
| 495
|
<methods>public non-sealed void <init>() ,public abstract XmlOutputBuilder<org.optaplanner.examples.nurserostering.domain.NurseRoster> createXmlOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.nurserostering.domain.NurseRoster, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/nurserostering/solver/move/EmployeeMultipleChangeMove.java
|
EmployeeMultipleChangeMove
|
doMoveOnGenuineVariables
|
class EmployeeMultipleChangeMove extends AbstractMove<NurseRoster> {
private Employee fromEmployee;
private List<ShiftAssignment> shiftAssignmentList;
private Employee toEmployee;
public EmployeeMultipleChangeMove(Employee fromEmployee, List<ShiftAssignment> shiftAssignmentList, Employee toEmployee) {
this.fromEmployee = fromEmployee;
this.shiftAssignmentList = shiftAssignmentList;
this.toEmployee = toEmployee;
}
@Override
public boolean isMoveDoable(ScoreDirector<NurseRoster> scoreDirector) {
return !Objects.equals(fromEmployee, toEmployee);
}
@Override
public EmployeeMultipleChangeMove createUndoMove(ScoreDirector<NurseRoster> scoreDirector) {
return new EmployeeMultipleChangeMove(toEmployee, shiftAssignmentList, fromEmployee);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<NurseRoster> scoreDirector) {<FILL_FUNCTION_BODY>}
@Override
public EmployeeMultipleChangeMove rebase(ScoreDirector<NurseRoster> destinationScoreDirector) {
return new EmployeeMultipleChangeMove(destinationScoreDirector.lookUpWorkingObject(fromEmployee),
rebaseList(shiftAssignmentList, destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(toEmployee));
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Collections.singletonList(shiftAssignmentList);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(fromEmployee, toEmployee);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeMultipleChangeMove other = (EmployeeMultipleChangeMove) o;
return Objects.equals(fromEmployee, other.fromEmployee) &&
Objects.equals(shiftAssignmentList, other.shiftAssignmentList) &&
Objects.equals(toEmployee, other.toEmployee);
}
@Override
public int hashCode() {
return Objects.hash(fromEmployee, shiftAssignmentList, toEmployee);
}
@Override
public String toString() {
return shiftAssignmentList + " {? -> " + toEmployee + "}";
}
}
|
for (ShiftAssignment shiftAssignment : shiftAssignmentList) {
if (!shiftAssignment.getEmployee().equals(fromEmployee)) {
throw new IllegalStateException("The shiftAssignment (" + shiftAssignment + ") should have the same employee ("
+ shiftAssignment.getEmployee() + ") as the fromEmployee (" + fromEmployee + ").");
}
NurseRosteringMoveHelper.moveEmployee(scoreDirector, shiftAssignment, toEmployee);
}
| 695
| 130
| 825
|
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.nurserostering.domain.NurseRoster> doMove(ScoreDirector<org.optaplanner.examples.nurserostering.domain.NurseRoster>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.nurserostering.domain.NurseRoster>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/pas/domain/Department.java
|
Department
|
countDisallowedPatientAge
|
class Department extends AbstractPersistable implements Labeled {
private String name;
private Integer minimumAge = null;
private Integer maximumAge = null;
private List<Room> roomList;
public Department() {
}
public Department(long id, String name) {
super(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getMinimumAge() {
return minimumAge;
}
public void setMinimumAge(Integer minimumAge) {
this.minimumAge = minimumAge;
}
public Integer getMaximumAge() {
return maximumAge;
}
public void setMaximumAge(Integer maximumAge) {
this.maximumAge = maximumAge;
}
public List<Room> getRoomList() {
return roomList;
}
public void setRoomList(List<Room> roomList) {
this.roomList = roomList;
}
public int countHardDisallowedAdmissionPart(AdmissionPart admissionPart) {
return countDisallowedPatientAge(admissionPart.getPatient());
}
public int countDisallowedPatientAge(Patient patient) {<FILL_FUNCTION_BODY>}
@Override
public String getLabel() {
String label = name;
if (minimumAge != null) {
label += "(≥" + minimumAge + ")";
}
if (maximumAge != null) {
label += "(≤" + maximumAge + ")";
}
return label;
}
@Override
public String toString() {
return name;
}
}
|
int count = 0;
if (minimumAge != null && patient.getAge() < minimumAge) {
count += 100;
}
if (maximumAge != null && patient.getAge() > maximumAge) {
count += 100;
}
return count;
| 485
| 84
| 569
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/pas/domain/solver/BedStrengthComparator.java
|
BedStrengthComparator
|
compare
|
class BedStrengthComparator implements Comparator<Bed> {
private static final Comparator<Integer> NULLSAFE_INTEGER_COMPARATOR = nullsFirst(Integer::compareTo);
private static final Comparator<Department> DEPARTMENT_COMPARATOR = comparing(
(Department department) -> department.getMinimumAge() == null) // null minimumAge is stronger
.thenComparing(department -> department.getMaximumAge() == null) // null maximumAge is stronger
.thenComparing(Department::getMinimumAge, Collections.reverseOrder(NULLSAFE_INTEGER_COMPARATOR)) // Descending, low minimumAge is stronger
.thenComparing(Department::getMaximumAge, NULLSAFE_INTEGER_COMPARATOR); // High maximumAge is stronger
private static final Comparator<Room> ROOM_COMPARATOR = comparingInt((Room room) -> room.getRoomEquipmentList().size())
.thenComparingInt(room -> room.getRoomSpecialismList().size())
.thenComparingInt(room -> -room.getCapacity()); // Descending (smaller rooms are stronger)
private static final Comparator<Bed> COMPARATOR = comparing((Bed bed) -> bed.getRoom().getDepartment(),
DEPARTMENT_COMPARATOR)
.thenComparing(Bed::getRoom, ROOM_COMPARATOR)
.thenComparingLong(Bed::getId);
@Override
public int compare(Bed a, Bed b) {<FILL_FUNCTION_BODY>}
}
|
if (a == null) {
if (b == null) {
return 0;
}
return -1;
} else if (b == null) {
return 1;
}
return COMPARATOR.compare(a, b);
| 409
| 70
| 479
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/pas/optional/solver/move/BedDesignationSwapMove.java
|
BedDesignationSwapMove
|
toString
|
class BedDesignationSwapMove extends AbstractMove<PatientAdmissionSchedule> {
private BedDesignation leftBedDesignation;
private BedDesignation rightBedDesignation;
public BedDesignationSwapMove(BedDesignation leftBedDesignation, BedDesignation rightBedDesignation) {
this.leftBedDesignation = leftBedDesignation;
this.rightBedDesignation = rightBedDesignation;
}
@Override
public boolean isMoveDoable(ScoreDirector<PatientAdmissionSchedule> scoreDirector) {
return !Objects.equals(leftBedDesignation.getBed(), rightBedDesignation.getBed());
}
@Override
public BedDesignationSwapMove createUndoMove(ScoreDirector<PatientAdmissionSchedule> scoreDirector) {
return new BedDesignationSwapMove(rightBedDesignation, leftBedDesignation);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<PatientAdmissionSchedule> scoreDirector) {
Bed oldLeftBed = leftBedDesignation.getBed();
Bed oldRightBed = rightBedDesignation.getBed();
PatientAdmissionMoveHelper.moveBed(scoreDirector, leftBedDesignation, oldRightBed);
PatientAdmissionMoveHelper.moveBed(scoreDirector, rightBedDesignation, oldLeftBed);
}
@Override
public BedDesignationSwapMove rebase(ScoreDirector<PatientAdmissionSchedule> destinationScoreDirector) {
return new BedDesignationSwapMove(destinationScoreDirector.lookUpWorkingObject(leftBedDesignation),
destinationScoreDirector.lookUpWorkingObject(rightBedDesignation));
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Arrays.asList(leftBedDesignation, rightBedDesignation);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(leftBedDesignation.getBed(), rightBedDesignation.getBed());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final BedDesignationSwapMove other = (BedDesignationSwapMove) o;
return Objects.equals(leftBedDesignation, other.leftBedDesignation) &&
Objects.equals(rightBedDesignation, other.rightBedDesignation);
}
@Override
public int hashCode() {
return Objects.hash(leftBedDesignation, rightBedDesignation);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return leftBedDesignation + " {" + leftBedDesignation.getBed() + "} <-> "
+ rightBedDesignation + " {" + rightBedDesignation.getBed() + "}";
| 737
| 58
| 795
|
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule> doMove(ScoreDirector<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/pas/persistence/PatientAdmissionScheduleExporter.java
|
PatientAdmissionScheduleOutputBuilder
|
writeSolution
|
class PatientAdmissionScheduleOutputBuilder extends TxtOutputBuilder<PatientAdmissionSchedule> {
private static final Comparator<BedDesignation> COMPARATOR = comparing(BedDesignation::getAdmissionPart,
comparingLong(AdmissionPart::getId))
.thenComparing(BedDesignation::getBed, comparingLong(Bed::getId))
.thenComparingLong(BedDesignation::getId);
@Override
public void writeSolution() throws IOException {<FILL_FUNCTION_BODY>}
}
|
solution.getBedDesignationList().sort(COMPARATOR);
for (Patient patient : solution.getPatientList()) {
bufferedWriter.write(Long.toString(patient.getId()));
for (BedDesignation bedDesignation : solution.getBedDesignationList()) {
if (bedDesignation.getPatient().equals(patient)) {
for (int i = 0; i < bedDesignation.getAdmissionPart().getNightCount(); i++) {
bufferedWriter.write(" " + bedDesignation.getBed().getId());
}
}
}
bufferedWriter.write("\n");
}
| 136
| 162
| 298
|
<methods>public non-sealed void <init>() ,public abstract TxtOutputBuilder<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule> createTxtOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.pas.domain.PatientAdmissionSchedule, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/pas/swingui/PatientAdmissionSchedulePanel.java
|
PatientOrRoomIcon
|
paintIcon
|
class PatientOrRoomIcon implements Icon {
private static final int EQUIPMENT_ICON_WIDTH = 8;
private final ImageIcon genderIcon;
private final List<Color> equipmentColorList;
private PatientOrRoomIcon(Patient patient) {
genderIcon = determinePatientGenderIcon(patient.getGender());
List<RequiredPatientEquipment> equipmentList = patient.getRequiredPatientEquipmentList();
equipmentColorList = new ArrayList<>(equipmentList.size());
for (RequiredPatientEquipment equipment : equipmentList) {
equipmentColorList.add(equipmentTangoColorFactory.pickColor(equipment.getEquipment()));
}
}
private PatientOrRoomIcon(Room room) {
genderIcon = determineRoomGenderIcon(room.getGenderLimitation());
List<RoomEquipment> equipmentList = room.getRoomEquipmentList();
equipmentColorList = new ArrayList<>(equipmentList.size());
for (RoomEquipment equipment : equipmentList) {
equipmentColorList.add(equipmentTangoColorFactory.pickColor(equipment.getEquipment()));
}
}
@Override
public int getIconWidth() {
return genderIcon.getIconWidth() + equipmentColorList.size() * EQUIPMENT_ICON_WIDTH;
}
@Override
public int getIconHeight() {
return genderIcon.getIconHeight();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {<FILL_FUNCTION_BODY>}
}
|
genderIcon.paintIcon(c, g, x, y);
int innerX = x + genderIcon.getIconWidth();
int equipmentIconHeight = genderIcon.getIconHeight();
for (int i = 0; i < equipmentColorList.size(); i++) {
g.setColor(equipmentColorList.get(i));
g.fillRect(innerX + 1, y + 1, EQUIPMENT_ICON_WIDTH - 2, equipmentIconHeight - 2);
g.setColor(TangoColorFactory.ALUMINIUM_5);
g.drawRect(innerX + 1, y + 1, EQUIPMENT_ICON_WIDTH - 2, equipmentIconHeight - 2);
innerX += EQUIPMENT_ICON_WIDTH;
}
| 408
| 199
| 607
|
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.pas.domain.PatientAdmissionSchedule getSolution() ,public SolutionBusiness<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.pas.domain.PatientAdmissionSchedule) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.pas.domain.PatientAdmissionSchedule) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.pas.domain.PatientAdmissionSchedule> solverAndPersistenceFrame,protected boolean useIndictmentColor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/domain/Allocation.java
|
Allocation
|
getEndDate
|
class Allocation extends AbstractPersistable implements Labeled {
private Job job;
private Allocation sourceAllocation;
private Allocation sinkAllocation;
private List<Allocation> predecessorAllocationList;
private List<Allocation> successorAllocationList;
// Planning variables: changes during planning, between score calculations.
private ExecutionMode executionMode;
private Integer delay; // In days
// Shadow variables
private Integer predecessorsDoneDate;
public Allocation() {
}
public Allocation(long id, Job job) {
super(id);
this.job = job;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public Allocation getSourceAllocation() {
return sourceAllocation;
}
public void setSourceAllocation(Allocation sourceAllocation) {
this.sourceAllocation = sourceAllocation;
}
public Allocation getSinkAllocation() {
return sinkAllocation;
}
public void setSinkAllocation(Allocation sinkAllocation) {
this.sinkAllocation = sinkAllocation;
}
public List<Allocation> getPredecessorAllocationList() {
return predecessorAllocationList;
}
public void setPredecessorAllocationList(List<Allocation> predecessorAllocationList) {
this.predecessorAllocationList = predecessorAllocationList;
}
public List<Allocation> getSuccessorAllocationList() {
return successorAllocationList;
}
public void setSuccessorAllocationList(List<Allocation> successorAllocationList) {
this.successorAllocationList = successorAllocationList;
}
@PlanningVariable(strengthWeightFactoryClass = ExecutionModeStrengthWeightFactory.class)
public ExecutionMode getExecutionMode() {
return executionMode;
}
public void setExecutionMode(ExecutionMode executionMode) {
this.executionMode = executionMode;
}
@PlanningVariable(strengthComparatorClass = DelayStrengthComparator.class)
public Integer getDelay() {
return delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
}
@ShadowVariable(
variableListenerClass = PredecessorsDoneDateUpdatingVariableListener.class, sourceVariableName = "executionMode")
@ShadowVariable(variableListenerClass = PredecessorsDoneDateUpdatingVariableListener.class, sourceVariableName = "delay")
public Integer getPredecessorsDoneDate() {
return predecessorsDoneDate;
}
public void setPredecessorsDoneDate(Integer predecessorsDoneDate) {
this.predecessorsDoneDate = predecessorsDoneDate;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public Integer getStartDate() {
if (predecessorsDoneDate == null) {
return null;
}
return predecessorsDoneDate + (delay == null ? 0 : delay);
}
@JsonIgnore
public Integer getEndDate() {<FILL_FUNCTION_BODY>}
@JsonIgnore
public Project getProject() {
return job.getProject();
}
@JsonIgnore
public int getProjectCriticalPathEndDate() {
return job.getProject().getCriticalPathEndDate();
}
@JsonIgnore
public JobType getJobType() {
return job.getJobType();
}
@Override
public String getLabel() {
return "Job " + job.getId();
}
// ************************************************************************
// Ranges
// ************************************************************************
@ValueRangeProvider
@JsonIgnore
public List<ExecutionMode> getExecutionModeRange() {
return job.getExecutionModeList();
}
@ValueRangeProvider
@JsonIgnore
public CountableValueRange<Integer> getDelayRange() {
return ValueRangeFactory.createIntValueRange(0, 500);
}
}
|
if (predecessorsDoneDate == null) {
return null;
}
return predecessorsDoneDate + (delay == null ? 0 : delay)
+ (executionMode == null ? 0 : executionMode.getDuration());
| 1,047
| 60
| 1,107
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/domain/solver/NotSourceOrSinkAllocationFilter.java
|
NotSourceOrSinkAllocationFilter
|
accept
|
class NotSourceOrSinkAllocationFilter implements PinningFilter<Schedule, Allocation> {
@Override
public boolean accept(Schedule schedule, Allocation allocation) {<FILL_FUNCTION_BODY>}
}
|
JobType jobType = allocation.getJob().getJobType();
return jobType == JobType.SOURCE || jobType == JobType.SINK;
| 57
| 41
| 98
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/domain/solver/PredecessorsDoneDateUpdatingVariableListener.java
|
PredecessorsDoneDateUpdatingVariableListener
|
updatePredecessorsDoneDate
|
class PredecessorsDoneDateUpdatingVariableListener implements VariableListener<Schedule, Allocation> {
@Override
public void beforeEntityAdded(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterEntityAdded(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
updateAllocation(scoreDirector, allocation);
}
@Override
public void beforeVariableChanged(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterVariableChanged(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
updateAllocation(scoreDirector, allocation);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterEntityRemoved(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
protected void updateAllocation(ScoreDirector<Schedule> scoreDirector, Allocation originalAllocation) {
Queue<Allocation> uncheckedSuccessorQueue = new ArrayDeque<>();
uncheckedSuccessorQueue.addAll(originalAllocation.getSuccessorAllocationList());
while (!uncheckedSuccessorQueue.isEmpty()) {
Allocation allocation = uncheckedSuccessorQueue.remove();
boolean updated = updatePredecessorsDoneDate(scoreDirector, allocation);
if (updated) {
uncheckedSuccessorQueue.addAll(allocation.getSuccessorAllocationList());
}
}
}
/**
* @param scoreDirector never null
* @param allocation never null
* @return true if the startDate changed
*/
protected boolean updatePredecessorsDoneDate(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {<FILL_FUNCTION_BODY>}
}
|
// For the source the doneDate must be 0.
Integer doneDate = 0;
for (Allocation predecessorAllocation : allocation.getPredecessorAllocationList()) {
int endDate = predecessorAllocation.getEndDate();
doneDate = Math.max(doneDate, endDate);
}
if (Objects.equals(doneDate, allocation.getPredecessorsDoneDate())) {
return false;
}
scoreDirector.beforeVariableChanged(allocation, "predecessorsDoneDate");
allocation.setPredecessorsDoneDate(doneDate);
scoreDirector.afterVariableChanged(allocation, "predecessorsDoneDate");
return true;
| 492
| 168
| 660
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/optional/score/ProjectJobSchedulingIncrementalScoreCalculator.java
|
ProjectJobSchedulingIncrementalScoreCalculator
|
retract
|
class ProjectJobSchedulingIncrementalScoreCalculator
implements IncrementalScoreCalculator<Schedule, HardMediumSoftScore> {
private Map<Resource, ResourceCapacityTracker> resourceCapacityTrackerMap;
private Map<Project, Integer> projectEndDateMap;
private int maximumProjectEndDate;
private int hardScore;
private int mediumScore;
private int softScore;
@Override
public void resetWorkingSolution(Schedule schedule) {
List<Resource> resourceList = schedule.getResourceList();
resourceCapacityTrackerMap = new HashMap<>(resourceList.size());
for (Resource resource : resourceList) {
resourceCapacityTrackerMap.put(resource, resource.isRenewable()
? new RenewableResourceCapacityTracker(resource)
: new NonrenewableResourceCapacityTracker(resource));
}
List<Project> projectList = schedule.getProjectList();
projectEndDateMap = new HashMap<>(projectList.size());
maximumProjectEndDate = 0;
hardScore = 0;
mediumScore = 0;
softScore = 0;
int minimumReleaseDate = Integer.MAX_VALUE;
for (Project p : projectList) {
minimumReleaseDate = Math.min(p.getReleaseDate(), minimumReleaseDate);
}
softScore += minimumReleaseDate;
for (Allocation allocation : schedule.getAllocationList()) {
insert(allocation);
}
}
@Override
public void beforeEntityAdded(Object entity) {
// Do nothing
}
@Override
public void afterEntityAdded(Object entity) {
insert((Allocation) entity);
}
@Override
public void beforeVariableChanged(Object entity, String variableName) {
retract((Allocation) entity);
}
@Override
public void afterVariableChanged(Object entity, String variableName) {
insert((Allocation) entity);
}
@Override
public void beforeEntityRemoved(Object entity) {
retract((Allocation) entity);
}
@Override
public void afterEntityRemoved(Object entity) {
// Do nothing
}
private void insert(Allocation allocation) {
// Job precedence is built-in
// Resource capacity
ExecutionMode executionMode = allocation.getExecutionMode();
if (executionMode != null && allocation.getJob().getJobType() == JobType.STANDARD) {
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
ResourceCapacityTracker tracker = resourceCapacityTrackerMap.get(
resourceRequirement.getResource());
hardScore -= tracker.getHardScore();
tracker.insert(resourceRequirement, allocation);
hardScore += tracker.getHardScore();
}
}
// Total project delay and total make span
if (allocation.getJob().getJobType() == JobType.SINK) {
Integer endDate = allocation.getEndDate();
if (endDate != null) {
Project project = allocation.getProject();
projectEndDateMap.put(project, endDate);
// Total project delay
mediumScore -= endDate - project.getCriticalPathEndDate();
// Total make span
if (endDate > maximumProjectEndDate) {
softScore -= endDate - maximumProjectEndDate;
maximumProjectEndDate = endDate;
}
}
}
}
private void retract(Allocation allocation) {<FILL_FUNCTION_BODY>}
private void updateMaximumProjectEndDate() {
int maximum = 0;
for (Integer endDate : projectEndDateMap.values()) {
if (endDate > maximum) {
maximum = endDate;
}
}
maximumProjectEndDate = maximum;
}
@Override
public HardMediumSoftScore calculateScore() {
return HardMediumSoftScore.of(hardScore, mediumScore, softScore);
}
}
|
// Job precedence is built-in
// Resource capacity
ExecutionMode executionMode = allocation.getExecutionMode();
if (executionMode != null && allocation.getJob().getJobType() == JobType.STANDARD) {
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
ResourceCapacityTracker tracker = resourceCapacityTrackerMap.get(
resourceRequirement.getResource());
hardScore -= tracker.getHardScore();
tracker.retract(resourceRequirement, allocation);
hardScore += tracker.getHardScore();
}
}
// Total project delay and total make span
if (allocation.getJob().getJobType() == JobType.SINK) {
Integer endDate = allocation.getEndDate();
if (endDate != null) {
Project project = allocation.getProject();
projectEndDateMap.remove(project);
// Total project delay
mediumScore += endDate - project.getCriticalPathEndDate();
// Total make span
if (endDate == maximumProjectEndDate) {
updateMaximumProjectEndDate();
softScore += endDate - maximumProjectEndDate;
}
}
}
| 1,004
| 304
| 1,308
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/optional/score/common/RenewableResourceCapacityTracker.java
|
RenewableResourceCapacityTracker
|
insert
|
class RenewableResourceCapacityTracker extends ResourceCapacityTracker {
protected int capacityEveryDay;
protected Map<Integer, Integer> usedPerDay;
protected int hardScore;
public RenewableResourceCapacityTracker(Resource resource) {
super(resource);
if (!resource.isRenewable()) {
throw new IllegalArgumentException("The resource (" + resource + ") is expected to be renewable.");
}
capacityEveryDay = resource.getCapacity();
usedPerDay = new HashMap<>();
hardScore = 0;
}
@Override
public void insert(ResourceRequirement resourceRequirement, Allocation allocation) {<FILL_FUNCTION_BODY>}
@Override
public void retract(ResourceRequirement resourceRequirement, Allocation allocation) {
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
int requirement = resourceRequirement.getRequirement();
for (int i = startDate; i < endDate; i++) {
Integer used = usedPerDay.get(i);
if (used == null) {
used = 0;
}
if (used > capacityEveryDay) {
hardScore += (used - capacityEveryDay);
}
used -= requirement;
if (used > capacityEveryDay) {
hardScore -= (used - capacityEveryDay);
}
usedPerDay.put(i, used);
}
}
@Override
public int getHardScore() {
return hardScore;
}
}
|
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
int requirement = resourceRequirement.getRequirement();
for (int i = startDate; i < endDate; i++) {
Integer used = usedPerDay.get(i);
if (used == null) {
used = 0;
}
if (used > capacityEveryDay) {
hardScore += (used - capacityEveryDay);
}
used += requirement;
if (used > capacityEveryDay) {
hardScore -= (used - capacityEveryDay);
}
usedPerDay.put(i, used);
}
| 390
| 164
| 554
|
<methods>public void <init>(org.optaplanner.examples.projectjobscheduling.domain.resource.Resource) ,public abstract int getHardScore() ,public abstract void insert(org.optaplanner.examples.projectjobscheduling.domain.ResourceRequirement, org.optaplanner.examples.projectjobscheduling.domain.Allocation) ,public abstract void retract(org.optaplanner.examples.projectjobscheduling.domain.ResourceRequirement, org.optaplanner.examples.projectjobscheduling.domain.Allocation) <variables>protected org.optaplanner.examples.projectjobscheduling.domain.resource.Resource resource
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/optional/score/common/RenewableResourceUsedDay.java
|
RenewableResourceUsedDay
|
equals
|
class RenewableResourceUsedDay {
private final Resource resource;
private final int usedDay;
public RenewableResourceUsedDay(Resource resource, int usedDay) {
this.resource = resource;
this.usedDay = usedDay;
}
public Resource getResource() {
return resource;
}
public int getUsedDay() {
return usedDay;
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(resource, usedDay);
}
@Override
public String toString() {
return resource + " on " + usedDay;
}
public int getResourceCapacity() {
return resource.getCapacity();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RenewableResourceUsedDay other = (RenewableResourceUsedDay) o;
return usedDay == other.usedDay &&
Objects.equals(resource, other.resource);
| 212
| 93
| 305
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/projectjobscheduling/swingui/ProjectJobSchedulingPanel.java
|
ProjectJobSchedulingPanel
|
createChart
|
class ProjectJobSchedulingPanel extends SolutionPanel<Schedule> {
public static final String LOGO_PATH =
"/org/optaplanner/examples/projectjobscheduling/swingui/projectJobSchedulingLogo.png";
public ProjectJobSchedulingPanel() {
setLayout(new BorderLayout());
}
@Override
public void resetPanel(Schedule schedule) {
removeAll();
ChartPanel chartPanel = new ChartPanel(createChart(schedule));
add(chartPanel, BorderLayout.CENTER);
}
private JFreeChart createChart(Schedule schedule) {<FILL_FUNCTION_BODY>}
}
|
YIntervalSeriesCollection seriesCollection = new YIntervalSeriesCollection();
Map<Project, YIntervalSeries> projectSeriesMap = new LinkedHashMap<>(
schedule.getProjectList().size());
YIntervalRenderer renderer = new YIntervalRenderer();
int maximumEndDate = 0;
int seriesIndex = 0;
TangoColorFactory tangoColorFactory = new TangoColorFactory();
for (Project project : schedule.getProjectList()) {
YIntervalSeries projectSeries = new YIntervalSeries(project.getLabel());
seriesCollection.addSeries(projectSeries);
projectSeriesMap.put(project, projectSeries);
renderer.setSeriesShape(seriesIndex, new Rectangle());
renderer.setSeriesStroke(seriesIndex, new BasicStroke(3.0f));
renderer.setSeriesPaint(seriesIndex, tangoColorFactory.pickColor(project));
seriesIndex++;
}
for (Allocation allocation : schedule.getAllocationList()) {
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
YIntervalSeries projectSeries = projectSeriesMap.get(allocation.getProject());
projectSeries.add(allocation.getId(), (startDate + endDate) / 2.0,
startDate, endDate);
maximumEndDate = Math.max(maximumEndDate, endDate);
}
NumberAxis domainAxis = new NumberAxis("Job");
domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
domainAxis.setRange(-0.5, schedule.getAllocationList().size() - 0.5);
domainAxis.setInverted(true);
NumberAxis rangeAxis = new NumberAxis("Day (start to end date)");
rangeAxis.setRange(-0.5, maximumEndDate + 0.5);
XYPlot plot = new XYPlot(seriesCollection, domainAxis, rangeAxis, renderer);
plot.setOrientation(PlotOrientation.HORIZONTAL);
plot.setDomainGridlinePaint(TangoColorFactory.ALUMINIUM_5);
plot.setRangeGridlinePaint(TangoColorFactory.ALUMINIUM_5);
return new JFreeChart("Project Job Scheduling", JFreeChart.DEFAULT_TITLE_FONT,
plot, true);
| 168
| 575
| 743
|
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.projectjobscheduling.domain.Schedule>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.projectjobscheduling.domain.Schedule>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.projectjobscheduling.domain.Schedule getSolution() ,public SolutionBusiness<org.optaplanner.examples.projectjobscheduling.domain.Schedule,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.projectjobscheduling.domain.Schedule> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.projectjobscheduling.domain.Schedule) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.projectjobscheduling.domain.Schedule,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.projectjobscheduling.domain.Schedule>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.projectjobscheduling.domain.Schedule) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.projectjobscheduling.domain.Schedule,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.projectjobscheduling.domain.Schedule> solverAndPersistenceFrame,protected boolean useIndictmentColor
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/domain/Employee.java
|
Employee
|
getAffinity
|
class Employee extends AbstractPersistable implements Labeled {
private String fullName;
private Set<Skill> skillSet;
private Map<Customer, Affinity> affinityMap;
@PlanningListVariable
private List<Task> tasks;
// TODO pinning: https://issues.redhat.com/browse/PLANNER-2633.
public Employee() {
}
public Employee(long id, String fullName) {
super(id);
this.fullName = fullName;
skillSet = new LinkedHashSet<>();
affinityMap = new LinkedHashMap<>();
tasks = new ArrayList<>();
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Set<Skill> getSkillSet() {
return skillSet;
}
public void setSkillSet(Set<Skill> skillSet) {
this.skillSet = skillSet;
}
public Map<Customer, Affinity> getAffinityMap() {
return affinityMap;
}
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = CustomerKeyDeserializer.class)
public void setAffinityMap(Map<Customer, Affinity> affinityMap) {
this.affinityMap = affinityMap;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
// ************************************************************************
// Complex methods
// ************************************************************************
/**
* @param customer never null
* @return never null
*/
@JsonIgnore
public Affinity getAffinity(Customer customer) {<FILL_FUNCTION_BODY>}
@JsonIgnore
public Integer getEndTime() {
return tasks.isEmpty() ? 0 : tasks.get(tasks.size() - 1).getEndTime();
}
@Override
public String getLabel() {
return fullName;
}
@JsonIgnore
public String getToolText() {
StringBuilder toolText = new StringBuilder();
toolText.append("<html><center><b>").append(fullName).append("</b><br/><br/>");
toolText.append("Skills:<br/>");
for (Skill skill : skillSet) {
toolText.append(skill.getLabel()).append("<br/>");
}
toolText.append("</center></html>");
return toolText.toString();
}
@Override
public String toString() {
return fullName;
}
}
|
Affinity affinity = affinityMap.get(customer);
if (affinity == null) {
affinity = Affinity.NONE;
}
return affinity;
| 721
| 48
| 769
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/domain/Task.java
|
Task
|
getMissingSkillCount
|
class Task extends AbstractPersistable implements Labeled {
private TaskType taskType;
private int indexInTaskType;
private Customer customer;
private int readyTime;
private Priority priority;
// Shadow variables
@InverseRelationShadowVariable(sourceVariableName = "tasks")
private Employee employee;
@ShadowVariable(variableListenerClass = StartTimeUpdatingVariableListener.class,
sourceEntityClass = Employee.class, sourceVariableName = "tasks")
private Integer startTime; // In minutes
public Task() {
}
public Task(long id, TaskType taskType, int indexInTaskType, Customer customer, int readyTime, Priority priority) {
super(id);
this.taskType = taskType;
this.indexInTaskType = indexInTaskType;
this.customer = customer;
this.readyTime = readyTime;
this.priority = priority;
}
public TaskType getTaskType() {
return taskType;
}
public void setTaskType(TaskType taskType) {
this.taskType = taskType;
}
public int getIndexInTaskType() {
return indexInTaskType;
}
public void setIndexInTaskType(int indexInTaskType) {
this.indexInTaskType = indexInTaskType;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getReadyTime() {
return readyTime;
}
public void setReadyTime(int readyTime) {
this.readyTime = readyTime;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Integer getStartTime() {
return startTime;
}
public void setStartTime(Integer startTime) {
this.startTime = startTime;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public int getMissingSkillCount() {<FILL_FUNCTION_BODY>}
/**
* In minutes
*
* @return at least 1 minute
*/
@JsonIgnore
public int getDuration() {
Affinity affinity = getAffinity();
return taskType.getBaseDuration() * affinity.getDurationMultiplier();
}
@JsonIgnore
public Affinity getAffinity() {
return (employee == null) ? Affinity.NONE : employee.getAffinity(customer);
}
@JsonIgnore
public Integer getEndTime() {
if (startTime == null) {
return null;
}
return startTime + getDuration();
}
@JsonIgnore
public String getCode() {
return taskType + "-" + indexInTaskType;
}
@JsonIgnore
public String getTitle() {
return taskType.getTitle();
}
@Override
public String getLabel() {
return getCode() + ": " + taskType.getTitle();
}
@JsonIgnore
public String getToolText() {
StringBuilder toolText = new StringBuilder();
toolText.append("<html><center><b>").append(getLabel()).append("</b><br/>")
.append(priority.getLabel()).append("<br/><br/>");
toolText.append("Required skills:<br/>");
for (Skill skill : taskType.getRequiredSkillList()) {
toolText.append(skill.getLabel()).append("<br/>");
}
toolText.append("<br/>Customer:<br/>").append(customer.getName()).append("<br/>(")
.append(getAffinity().getLabel()).append(")<br/>");
toolText.append("</center></html>");
return toolText.toString();
}
@Override
public String toString() {
return getCode();
}
}
|
if (employee == null) {
return 0;
}
int count = 0;
for (Skill skill : taskType.getRequiredSkillList()) {
if (!employee.getSkillSet().contains(skill)) {
count++;
}
}
return count;
| 1,103
| 81
| 1,184
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/domain/solver/StartTimeUpdatingVariableListener.java
|
StartTimeUpdatingVariableListener
|
afterEntityRemoved
|
class StartTimeUpdatingVariableListener implements ListVariableListener<TaskAssigningSolution, Employee, Task> {
@Override
public void beforeEntityAdded(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support adding employees.");
}
@Override
public void afterEntityAdded(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support adding employees.");
}
@Override
public void beforeEntityRemoved(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support removing employees.");
}
@Override
public void afterEntityRemoved(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {<FILL_FUNCTION_BODY>}
@Override
public void afterListVariableElementUnassigned(ScoreDirector<TaskAssigningSolution> scoreDirector, Task task) {
scoreDirector.beforeVariableChanged(task, "startTime");
task.setStartTime(null);
scoreDirector.afterVariableChanged(task, "startTime");
}
@Override
public void beforeListVariableChanged(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int startIndex,
int endIndex) {
// Do nothing
}
@Override
public void afterListVariableChanged(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int startIndex,
int endIndex) {
updateStartTime(scoreDirector, employee, startIndex);
}
protected void updateStartTime(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int index) {
List<Task> tasks = employee.getTasks();
Integer previousEndTime = index == 0 ? Integer.valueOf(0) : tasks.get(index - 1).getEndTime();
for (int i = index; i < tasks.size(); i++) {
Task t = tasks.get(i);
Integer startTime = calculateStartTime(t, previousEndTime);
if (!Objects.equals(t.getStartTime(), startTime)) {
scoreDirector.beforeVariableChanged(t, "startTime");
t.setStartTime(startTime);
scoreDirector.afterVariableChanged(t, "startTime");
}
previousEndTime = t.getEndTime();
}
}
private Integer calculateStartTime(Task task, Integer previousEndTime) {
if (previousEndTime == null) {
return null;
}
return Math.max(task.getReadyTime(), previousEndTime);
}
}
|
throw new UnsupportedOperationException("This example does not support removing employees.");
| 693
| 20
| 713
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/persistence/TaskAssigningSolutionFileIO.java
|
TaskAssigningSolutionFileIO
|
read
|
class TaskAssigningSolutionFileIO extends AbstractJsonSolutionFileIO<TaskAssigningSolution> {
public TaskAssigningSolutionFileIO() {
super(TaskAssigningSolution.class);
}
@Override
public TaskAssigningSolution read(File inputSolutionFile) {<FILL_FUNCTION_BODY>}
}
|
TaskAssigningSolution taskAssigningSolution = super.read(inputSolutionFile);
var customersById = taskAssigningSolution.getCustomerList().stream()
.collect(Collectors.toMap(Customer::getId, Function.identity()));
/*
* Replace the duplicate customer instances in the affinityMap by references to instances from
* the customerList.
*/
for (Employee employee : taskAssigningSolution.getEmployeeList()) {
var newTravelDistanceMap = deduplicateMap(employee.getAffinityMap(),
customersById, Customer::getId);
employee.setAffinityMap(newTravelDistanceMap);
}
return taskAssigningSolution;
| 94
| 181
| 275
|
<methods>public void <init>(Class<org.optaplanner.examples.taskassigning.domain.TaskAssigningSolution>) ,public void <init>(Class<org.optaplanner.examples.taskassigning.domain.TaskAssigningSolution>, ObjectMapper) <variables>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/score/TaskAssigningConstraintProvider.java
|
TaskAssigningConstraintProvider
|
defineConstraints
|
class TaskAssigningConstraintProvider implements ConstraintProvider {
private static final int BENDABLE_SCORE_HARD_LEVELS_SIZE = 1;
private static final int BENDABLE_SCORE_SOFT_LEVELS_SIZE = 4;
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {<FILL_FUNCTION_BODY>}
private UniConstraintStream<Task> getTaskWithPriority(ConstraintFactory constraintFactory, Priority priority) {
return constraintFactory.forEach(Task.class)
.filter(task -> task.getEmployee() != null && task.getPriority() == priority);
}
private Constraint noMissingSkills(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Task.class)
.filter(task -> task.getMissingSkillCount() > 0)
.penalize(BendableScore.ofHard(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 0, 1),
Task::getMissingSkillCount)
.asConstraint("No missing skills");
}
private Constraint criticalPriorityBasedTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.CRITICAL)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 0, 1),
Task::getEndTime)
.asConstraint("Critical priority task end time");
}
private Constraint minimizeMakespan(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Employee.class)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 1, 1),
employee -> employee.getEndTime() * employee.getEndTime())
.asConstraint("Minimize makespan, latest ending employee first");
}
private Constraint majorPriorityTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.MAJOR)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 2, 1),
Task::getEndTime)
.asConstraint("Major priority task end time");
}
private Constraint minorPriorityTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.MINOR)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 3, 1),
Task::getEndTime)
.asConstraint("Minor priority task end time");
}
}
|
return new Constraint[] {
noMissingSkills(constraintFactory),
minimizeMakespan(constraintFactory),
/*
* TODO potential for performance improvements through API enhancements,
* see https://issues.redhat.com/browse/PLANNER-1604.
*/
criticalPriorityBasedTaskEndTime(constraintFactory),
majorPriorityTaskEndTime(constraintFactory),
minorPriorityTaskEndTime(constraintFactory)
};
| 762
| 112
| 874
|
<no_super_class>
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/swingui/TaskOverviewPanel.java
|
TaskOrEmployeeIcon
|
paintIcon
|
class TaskOrEmployeeIcon implements Icon {
private static final int SKILL_ICON_WIDTH = 8;
private static final int SKILL_ICON_HEIGHT = 16;
private final ImageIcon priorityIcon;
private final List<Color> skillColorList;
private final ImageIcon affinityIcon;
private TaskOrEmployeeIcon(Task task) {
priorityIcon = priorityIcons[task.getPriority().ordinal()];
skillColorList = task.getTaskType().getRequiredSkillList().stream()
.map(skillColorFactory::pickColor)
.collect(Collectors.toList());
affinityIcon = affinityIcons[task.getAffinity().ordinal()];
}
private TaskOrEmployeeIcon(Employee employee) {
priorityIcon = null;
skillColorList = employee.getSkillSet().stream()
.sorted(Comparator.comparing(Skill::getName))
.map(skillColorFactory::pickColor)
.collect(Collectors.toList());
affinityIcon = null;
}
@Override
public int getIconWidth() {
int width = 0;
if (priorityIcon != null) {
width += priorityIcon.getIconWidth();
}
width += skillColorList.size() * SKILL_ICON_WIDTH;
if (affinityIcon != null) {
width += affinityIcon.getIconWidth();
}
return width;
}
@Override
public int getIconHeight() {
int height = SKILL_ICON_HEIGHT;
if (priorityIcon != null && priorityIcon.getIconHeight() > height) {
height = priorityIcon.getIconHeight();
}
if (affinityIcon != null && affinityIcon.getIconHeight() > height) {
height = affinityIcon.getIconHeight();
}
return height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {<FILL_FUNCTION_BODY>}
}
|
int innerX = x;
if (priorityIcon != null) {
priorityIcon.paintIcon(c, g, innerX, y);
innerX += priorityIcon.getIconWidth();
}
for (Color skillColor : skillColorList) {
g.setColor(skillColor);
g.fillRect(innerX + 1, y + 1, SKILL_ICON_WIDTH - 2, SKILL_ICON_HEIGHT - 2);
g.setColor(TangoColorFactory.ALUMINIUM_5);
g.drawRect(innerX + 1, y + 1, SKILL_ICON_WIDTH - 2, SKILL_ICON_HEIGHT - 2);
innerX += SKILL_ICON_WIDTH;
}
if (affinityIcon != null) {
affinityIcon.paintIcon(c, g, innerX, y);
innerX += affinityIcon.getIconWidth();
}
| 529
| 244
| 773
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tennis/domain/TeamAssignment.java
|
TeamAssignment
|
toString
|
class TeamAssignment extends AbstractPersistable {
private Day day;
private int indexInDay;
private boolean pinned;
// planning variable
private Team team;
public TeamAssignment() {
}
public TeamAssignment(long id, Day day, int indexInDay) {
super(id);
this.day = day;
this.indexInDay = indexInDay;
}
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
public int getIndexInDay() {
return indexInDay;
}
public void setIndexInDay(int indexInDay) {
this.indexInDay = indexInDay;
}
@PlanningPin
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
@PlanningVariable
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Day-" + day.getDateIndex() + "(" + indexInDay + ")";
| 324
| 26
| 350
|
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
|
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tennis/optional/benchmark/TennisBenchmarkApp.java
|
TennisBenchmarkApp
|
benchmark
|
class TennisBenchmarkApp extends LoggingMain {
public static void main(String[] args) {
new TennisBenchmarkApp().benchmark();
}
private final PlannerBenchmarkFactory benchmarkFactory;
public TennisBenchmarkApp() {
benchmarkFactory = PlannerBenchmarkFactory.createFromSolverConfigXmlResource(
TennisApp.SOLVER_CONFIG, new File("local/data/tennis"));
}
public void benchmark() {<FILL_FUNCTION_BODY>}
}
|
TennisSolution problem = new TennisGenerator().createTennisSolution();
PlannerBenchmark plannerBenchmark = benchmarkFactory.buildPlannerBenchmark(problem);
plannerBenchmark.benchmark();
| 136
| 58
| 194
|
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.