diff options
| author | EVE <EVE@EVE-PC> | 2017-03-13 16:42:21 -0400 |
|---|---|---|
| committer | EVE <EVE@EVE-PC> | 2017-03-13 16:42:21 -0400 |
| commit | 27bf571d6413c3cc6a5d664b5bddd38d21d7b1cd (patch) | |
| tree | 847fb52acb091c1c613d37b8477094d5762c6988 /BJC-Utils2/src/main/java/bjc | |
| parent | aa807a96cae2c47259fb38f710640883060339e9 (diff) | |
Formatting
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc')
110 files changed, 1980 insertions, 2155 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java index bc3e56e..22fb276 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java @@ -16,9 +16,9 @@ public class CLICommander { /* * The streams used for input and normal/error output */ - private InputStream input; - private OutputStream output; - private OutputStream error; + private InputStream input; + private OutputStream output; + private OutputStream error; /* * The command mode to start execution in @@ -29,11 +29,11 @@ public class CLICommander { * Create a new CLI interface powered by streams. * * @param input - * The stream to get user input from. + * The stream to get user input from. * @param output - * The stream to send normal output to. + * The stream to send normal output to. * @param error - * The stream to send error output to. + * The stream to send error output to. */ public CLICommander(InputStream input, OutputStream output, OutputStream error) { if (input == null) { @@ -76,8 +76,8 @@ public class CLICommander { // Process commands until we're told to stop while (currentMode != null) { /* - * Print out the command prompt, using a custom prompt if one - * is specified + * Print out the command prompt, using a custom prompt + * if one is specified */ if (currentMode.isCustomPromptEnabled()) { normalOutput.print(currentMode.getCustomPrompt()); @@ -99,7 +99,7 @@ public class CLICommander { } // Process command - currentMode = currentMode. process(commandTokens[0], commandArgs); + currentMode = currentMode.process(commandTokens[0], commandArgs); } else { errorOutput.print("Error: Unrecognized command " + currentLine); } @@ -112,7 +112,7 @@ public class CLICommander { * Set the initial command mode to use * * @param initialMode - * The initial command mode to use + * The initial command mode to use */ public void setInitialCommandMode(ICommandMode initialMode) { if (initialMode == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java index aa0a308..7d2f807 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -14,7 +14,7 @@ class DelegatingCommand implements ICommand { * Create a new command that delegates to another command * * @param delegate - * The command to delegate to + * The command to delegate to */ public DelegatingCommand(ICommand delegate) { this.delegate = delegate; diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java index d6a72c9..b0ceb3b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java @@ -8,7 +8,7 @@ package bjc.utils.cli; */ public class GenericCommand implements ICommand { // The behavior for invoking the command - private ICommandHandler handler; + private ICommandHandler handler; // The help for the command private ICommandHelp help; @@ -17,11 +17,11 @@ public class GenericCommand implements ICommand { * Create a new generic command * * @param handler - * The handler to use for the command + * The handler to use for the command * @param description - * The description of the command. May be null + * The description of the command. May be null * @param help - * The detailed help message for the command. May be null + * The detailed help message for the command. May be null */ public GenericCommand(ICommandHandler handler, String description, String help) { if (handler == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java index b3847c0..62d0008 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -10,9 +10,9 @@ import bjc.utils.funcdata.IMap; /** * A general command mode, with a customizable set of commands * - * There is a small set of commands which is handled by default. The first - * is 'list', which lists all the commands the user can input. The second - * is 'alias', which allows the user to bind a new name to a command + * There is a small set of commands which is handled by default. The first is + * 'list', which lists all the commands the user can input. The second is + * 'alias', which allows the user to bind a new name to a command * * @author ben * @@ -44,9 +44,9 @@ public class GenericCommandMode implements ICommandMode { * Create a new generic command mode * * @param normalOutput - * The function to use for normal output + * The function to use for normal output * @param errorOutput - * The function to use for error output + * The function to use for error output */ public GenericCommandMode(Consumer<String> normalOutput, Consumer<String> errorOutput) { if (normalOutput == null) { @@ -58,10 +58,11 @@ public class GenericCommandMode implements ICommandMode { this.normalOutput = normalOutput; this.errorOutput = errorOutput; - // Initialize handler maps so that they sort in alphabetical order + // Initialize handler maps so that they sort in alphabetical + // order commandHandlers = new FunctionalMap<>(new TreeMap<>()); defaultHandlers = new FunctionalMap<>(new TreeMap<>()); - helpTopics = new FunctionalMap<>(new TreeMap<>()); + helpTopics = new FunctionalMap<>(new TreeMap<>()); setupDefaultCommands(); } @@ -70,27 +71,25 @@ public class GenericCommandMode implements ICommandMode { * Add an alias to an existing command * * @param commandName - * The name of the command to add an alias for + * The name of the command to add an alias for * @param aliasName - * The new alias for the command + * The new alias for the command * * @throws IllegalArgumentException - * if the specified command doesn't have a bound handler, - * or if the alias name already has a bound value + * if the specified command doesn't have a bound + * handler, or if the alias name already has a bound + * value */ public void addCommandAlias(String commandName, String aliasName) { if (commandName == null) { throw new NullPointerException("Command name must not be null"); } else if (aliasName == null) { throw new NullPointerException("Alias name must not be null"); - } else if (!commandHandlers.containsKey(commandName) - && !defaultHandlers.containsKey(commandName)) { - throw new IllegalArgumentException("Cannot alias non-existant command '" - + commandName + "'"); - } else if (commandHandlers.containsKey(aliasName) - || defaultHandlers.containsKey(aliasName)) { - throw new IllegalArgumentException("Cannot bind alias '" - + aliasName + "' to a command with a bound handler"); + } else if (!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) { + throw new IllegalArgumentException("Cannot alias non-existant command '" + commandName + "'"); + } else if (commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) { + throw new IllegalArgumentException( + "Cannot bind alias '" + aliasName + "' to a command with a bound handler"); } else { ICommand aliasedCommand; @@ -108,13 +107,13 @@ public class GenericCommandMode implements ICommandMode { * Add a command to this command mode * * @param command - * The name of the command to add + * The name of the command to add * @param handler - * The handler to use for the specified command + * The handler to use for the specified command * * @throws IllegalArgumentException - * if the specified command already has a handler - * registered + * if the specified command already has a handler + * registered */ public void addCommandHandler(String command, ICommand handler) { if (command == null) { @@ -122,8 +121,7 @@ public class GenericCommandMode implements ICommandMode { } else if (handler == null) { throw new NullPointerException("Handler must not be null"); } else if (canHandle(command)) { - throw new IllegalArgumentException("Command " + - command + " already has a handler registered"); + throw new IllegalArgumentException("Command " + command + " already has a handler registered"); } else { commandHandlers.put(command, handler); } @@ -133,9 +131,9 @@ public class GenericCommandMode implements ICommandMode { * Add a help topic to this command mode that isn't tied to a command * * @param topicName - * The name of the topic + * The name of the topic * @param topic - * The contents of the topic + * The contents of the topic */ public void addHelpTopic(String topicName, ICommandHelp topic) { helpTopics.put(topicName, topic); @@ -147,9 +145,9 @@ public class GenericCommandMode implements ICommandMode { private GenericCommand buildAliasCommand() { String aliasShortHelp = "alias\tAlias one command to another"; - String aliasLongHelp = "Gives a command another name it can be invoked by." - +" Invoke with two arguments: the name of the command to alias" - + "followed by the name of the alias to give that command."; + String aliasLongHelp = "Gives a command another name it can be invoked by." + + " Invoke with two arguments: the name of the command to alias" + + "followed by the name of the alias to give that command."; return new GenericCommand((args) -> { doAliasCommands(args); @@ -160,8 +158,7 @@ public class GenericCommandMode implements ICommandMode { private GenericCommand buildClearCommands() { String clearShortHelp = "clear\tClear the screen"; - String clearLongHelp = "Clears the screen of all the text on it," - + " and prints a new prompt."; + String clearLongHelp = "Clears the screen of all the text on it," + " and prints a new prompt."; return new GenericCommand((args) -> { errorOutput.accept("ERROR: This console doesn't support screen clearing"); @@ -172,8 +169,8 @@ public class GenericCommandMode implements ICommandMode { private GenericCommand buildExitCommand() { String exitShortHelp = "exit\tExit the console"; - String exitLongHelp = "First prompts the user to make sure they want to" - + " exit, then quits if they say they do"; + String exitLongHelp = "First prompts the user to make sure they want to" + + " exit, then quits if they say they do"; return new GenericCommand((args) -> { errorOutput.accept("ERROR: This console doesn't support auto-exiting"); @@ -184,11 +181,10 @@ public class GenericCommandMode implements ICommandMode { private GenericCommand buildHelpCommand() { String helpShortHelp = "help\tConsult the help system"; - String helpLongHelp = "Consults the internal help system." - + " Invoked in two different ways. Invoking with no arguments" - + " causes all the topics you can ask for details on to be list," - + " while invoking with the name of a topic will print the entry" - + " for that topic"; + String helpLongHelp = "Consults the internal help system." + + " Invoked in two different ways. Invoking with no arguments" + + " causes all the topics you can ask for details on to be list," + + " while invoking with the name of a topic will print the entry" + " for that topic"; return new GenericCommand((args) -> { if (args == null || args.length == 0) { @@ -205,8 +201,8 @@ public class GenericCommandMode implements ICommandMode { private GenericCommand buildListCommand() { String listShortHelp = "list\tList available commands"; - String listLongHelp = "Lists all of the commands available in this mode," - + " as well as commands available in any mode"; + String listLongHelp = "Lists all of the commands available in this mode," + + " as well as commands available in any mode"; return new GenericCommand((args) -> { doListCommands(); @@ -235,8 +231,7 @@ public class GenericCommandMode implements ICommandMode { if (!canHandle(commandName)) { errorOutput.accept("ERROR: '" + commandName + "' is not a valid command."); } else if (canHandle(aliasName)) { - errorOutput.accept("ERROR: Cannot overwrite command '" - + aliasName + "'"); + errorOutput.accept("ERROR: Cannot overwrite command '" + aliasName + "'"); } else { addCommandAlias(commandName, aliasName); } @@ -251,12 +246,12 @@ public class GenericCommandMode implements ICommandMode { } else if (defaultHandlers.containsKey(commandName)) { String desc = defaultHandlers.get(commandName).getHelp().getDescription(); - normalOutput.accept("\n" + desc); + normalOutput.accept("\n" + desc); } else if (helpTopics.containsKey(commandName)) { normalOutput.accept("\n" + helpTopics.get(commandName).getDescription()); } else { - errorOutput.accept("ERROR: I'm sorry, but there is no help available for '" - + commandName + "'"); + errorOutput.accept( + "ERROR: I'm sorry, but there is no help available for '" + commandName + "'"); } } @@ -301,7 +296,7 @@ public class GenericCommandMode implements ICommandMode { normalOutput.accept("\t" + commandName); }); - normalOutput.accept( "\nThe following commands are available in all modes:\n"); + normalOutput.accept("\nThe following commands are available in all modes:\n"); defaultHandlers.keyList().forEach(commandName -> { normalOutput.accept("\t" + commandName); }); @@ -342,8 +337,7 @@ public class GenericCommandMode implements ICommandMode { return commandHandlers.get(command).getHandler().handle(args); } else { if (args != null) { - errorOutput.accept("ERROR: Unrecognized command " - + command + String.join(" ", args)); + errorOutput.accept("ERROR: Unrecognized command " + command + String.join(" ", args)); } else { errorOutput.accept("ERROR: Unrecognized command " + command); } @@ -362,8 +356,8 @@ public class GenericCommandMode implements ICommandMode { * Set the custom prompt for this mode * * @param prompt - * The custom prompt for this mode, or null to disable the - * custom prompt + * The custom prompt for this mode, or null to disable + * the custom prompt */ public void setCustomPrompt(String prompt) { customPrompt = prompt; @@ -373,8 +367,8 @@ public class GenericCommandMode implements ICommandMode { * Set the name of this mode * * @param name - * The desired name of this mode, or null to use the default - * name + * The desired name of this mode, or null to use the + * default name */ public void setModeName(String name) { modeName = name; @@ -384,8 +378,8 @@ public class GenericCommandMode implements ICommandMode { * Set the handler to use for unknown commands * * @param handler - * The handler to use for unknown commands, or null to throw - * on unknown commands + * The handler to use for unknown commands, or null to + * throw on unknown commands */ public void setUnknownCommandHandler(BiConsumer<String, String[]> handler) { if (handler == null) { @@ -396,15 +390,16 @@ public class GenericCommandMode implements ICommandMode { } private void setupDefaultCommands() { - defaultHandlers.put("list", buildListCommand()); + defaultHandlers.put("list", buildListCommand()); defaultHandlers.put("alias", buildAliasCommand()); - defaultHandlers.put("help", buildHelpCommand()); + defaultHandlers.put("help", buildHelpCommand()); addCommandAlias("help", "man"); // Add commands handled in a upper layer. - // @TODO figure out a place to put commands that apply across all + // @TODO figure out a place to put commands that apply across + // all // modes, but only apply to a specific application defaultHandlers.put("clear", buildClearCommands()); defaultHandlers.put("exit", buildExitCommand()); diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java index fc7cf20..595d7d9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java @@ -15,12 +15,12 @@ public class GenericHelp implements ICommandHelp { * Create a new help topic * * @param summary - * The summary of this help topic + * The summary of this help topic * @param description - * The description of this help topic, or null if this help - * topic doesn't have a more detailed description + * The description of this help topic, or null if this + * help topic doesn't have a more detailed description */ - public GenericHelp(String summary, String description) { + public GenericHelp(String summary, String description) { if (summary == null) { throw new NullPointerException("Help summary must be non-null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java index 33182b3..a774108 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHandler.java @@ -14,7 +14,7 @@ public interface ICommandHandler extends Function<String[], ICommandMode> { * Execute this command * * @param args - * The arguments for this command + * The arguments for this command * @return The command mode to switch to after this command, or null to * stop executing commands */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java index 00b83ed..56f7869 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java @@ -12,7 +12,7 @@ public interface ICommandMode { * Check to see if this mode can handle the specified command * * @param command - * The command to check + * The command to check * @return Whether or not this mode can handle the command. It is * assumed not by default */ @@ -26,7 +26,7 @@ public interface ICommandMode { * @return the custom prompt for this mode * * @throws UnsupportedOperationException - * if this mode doesn't support a custom prompt + * if this mode doesn't support a custom prompt */ public default String getCustomPrompt() { throw new UnsupportedOperationException("This mode doesn't support a custom prompt"); @@ -55,9 +55,9 @@ public interface ICommandMode { * Process a command in this mode * * @param command - * The command to process + * The command to process * @param args - * A list of arguments to the command + * A list of arguments to the command * @return The command mode to use for the next command. Defaults to * returning this, and doing nothing else */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java index 1ec5b80..c473150 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java @@ -7,50 +7,47 @@ package bjc.utils.components; * */ public class ComponentDescription implements IDescribedComponent { - private static void sanityCheckArgs(String name, String author, - String description, int version) { + private static void sanityCheckArgs(String name, String author, String description, int version) { if (name == null) { throw new NullPointerException("Component name can't be null"); } else if (version <= 0) { - throw new IllegalArgumentException( - "Component version must be greater than 0"); + throw new IllegalArgumentException("Component version must be greater than 0"); } } /** * The author of the component */ - private String author; + private String author; /** * The description of the component */ - private String description; + private String description; /** * The name of the component */ - private String name; + private String name; /** * The version of the component */ - private int version; + private int version; /** * Create a new component description * * @param name - * The name of the component + * The name of the component * @param author - * The author of the component + * The author of the component * @param description - * The description of the component + * The description of the component * @param version - * The version of the component + * The version of the component * @throws IllegalArgumentException - * thrown if version is less than 1 + * thrown if version is less than 1 */ - public ComponentDescription(String name, String author, - String description, int version) { + public ComponentDescription(String name, String author, String description, int version) { sanityCheckArgs(name, author, description, version); this.name = name; @@ -61,19 +58,19 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getAuthor() { - if(author == null) { + if (author == null) { return IDescribedComponent.super.getAuthor(); } - + return author; } @Override public String getDescription() { - if(description == null) { + if (description == null) { return IDescribedComponent.super.getDescription(); } - + return description; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java index ad5e1a2..22221d2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java @@ -19,7 +19,8 @@ public class ComponentDescriptionFileParser { // Initialize the reader and its pragmas static { - // This reader works entirely off of pragmas, so no need to handle + // This reader works entirely off of pragmas, so no need to + // handle // rules reader = new RuleBasedConfigReader<>((tokenizer, statePair) -> { // Don't need to do anything on rule start @@ -36,17 +37,15 @@ public class ComponentDescriptionFileParser { * Parse a component description from a stream * * @param inputSource - * The stream to parse from + * The stream to parse from * @return The description parsed from the stream */ - public static ComponentDescription fromStream( - InputStream inputSource) { - if(inputSource == null) { + public static ComponentDescription fromStream(InputStream inputSource) { + if (inputSource == null) { throw new NullPointerException("Input source must not be null"); } - - ComponentDescriptionState readState = reader - .fromStream(inputSource, new ComponentDescriptionState()); + + ComponentDescriptionState readState = reader.fromStream(inputSource, new ComponentDescriptionState()); return readState.toDescription(); } @@ -55,17 +54,13 @@ public class ComponentDescriptionFileParser { * Create all the pragmas the reader needs to function */ private static void setupReaderPragmas() { - reader.addPragma("name", buildStringCollapser("name", - (name, state) -> state.setName(name))); + reader.addPragma("name", buildStringCollapser("name", (name, state) -> state.setName(name))); - reader.addPragma("author", buildStringCollapser("author", - (author, state) -> state.setAuthor(author))); + reader.addPragma("author", buildStringCollapser("author", (author, state) -> state.setAuthor(author))); - reader.addPragma("description", - buildStringCollapser("description", (description, - state) -> state.setDescription(description))); + reader.addPragma("description", buildStringCollapser("description", + (description, state) -> state.setDescription(description))); - reader.addPragma("version", buildInteger("version", - (version, state) -> state.setVersion(version))); + reader.addPragma("version", buildInteger("version", (version, state) -> state.setVersion(version))); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java index a17a70b..70f308b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java @@ -8,22 +8,22 @@ package bjc.utils.components; */ public class ComponentDescriptionState { // Tentative name of this component - private String name; + private String name; // Tentative description of this componet - private String description; + private String description; // Tentative author of this component - private String author; + private String author; // Tentative version of this component - private int version; + private int version; /** * Set the author of this component * * @param author - * The author of this component + * The author of this component */ public void setAuthor(String author) { this.author = author; @@ -33,7 +33,7 @@ public class ComponentDescriptionState { * Set the description of this component * * @param description - * The description of this component + * The description of this component */ public void setDescription(String description) { this.description = description; @@ -43,7 +43,7 @@ public class ComponentDescriptionState { * Set the name of this component * * @param name - * The name of this component + * The name of this component */ public void setName(String name) { this.name = name; @@ -53,7 +53,7 @@ public class ComponentDescriptionState { * Set the version of this component * * @param version - * The version of this component + * The version of this component */ public void setVersion(int version) { this.version = version; @@ -65,7 +65,6 @@ public class ComponentDescriptionState { * @return The description represented by this state */ public ComponentDescription toDescription() { - return new ComponentDescription(name, author, description, - version); + return new ComponentDescription(name, author, description, version); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java index e98c06b..7aa7c07 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -17,51 +17,45 @@ import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.FileUtils; /** - * A component repository that loads its components from files in a - * directory + * A component repository that loads its components from files in a directory * * @author ben * * @param <ComponentType> - * The type of component being read in + * The type of component being read in */ public class FileComponentRepository<ComponentType extends IDescribedComponent> implements IComponentRepository<ComponentType> { // The logger to use for storing data about this class - private static final Logger CLASS_LOGGER = Logger - .getLogger("FileComponentRepository"); + private static final Logger CLASS_LOGGER = Logger.getLogger("FileComponentRepository"); // The internal storage of components - private IMap<String, ComponentType> components; + private IMap<String, ComponentType> components; // The path that all the components came from - private Path sourceDirectory; + private Path sourceDirectory; /** - * Create a new component repository sourcing components from files in - * a directory + * Create a new component repository sourcing components from files in a + * directory * - * An exception thrown during the loading of a component will only - * cause the loading of that component to fail, but a warning will be - * logged. + * An exception thrown during the loading of a component will only cause + * the loading of that component to fail, but a warning will be logged. * * @param directory - * The directory to read component files from + * The directory to read component files from * @param componentReader - * The function to use to convert files to components + * The function to use to convert files to components */ - public FileComponentRepository(File directory, - Function<File, ? extends ComponentType> componentReader) { + public FileComponentRepository(File directory, Function<File, ? extends ComponentType> componentReader) { // Make sure we have valid arguments if (directory == null) { throw new NullPointerException("Directory must not be null"); } else if (!directory.isDirectory()) { - throw new IllegalArgumentException("File " + directory - + " is not a directory.\n" + throw new IllegalArgumentException("File " + directory + " is not a directory.\n" + "Components can only be read from a directory"); } else if (componentReader == null) { - throw new NullPointerException( - "Component reader must not be null"); + throw new NullPointerException("Component reader must not be null"); } // Initialize our fields @@ -71,20 +65,21 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> // Marker for making sure we don't skip the parent IHolder<Boolean> isFirstDir = new Identity<>(true); - // Predicate to use to traverse all the files in a directory, but + // Predicate to use to traverse all the files in a directory, + // but // not recurse into sub-directories - BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, - attr) -> { + BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, attr) -> { if (attr.isDirectory() && !isFirstDir.getValue()) { /* - * Skip directories, they probably have component support - * files. + * Skip directories, they probably have + * component support files. */ return false; } /* - * Don't skip the first directory, that's the parent directory + * Don't skip the first directory, that's the parent + * directory */ isFirstDir.replace(false); @@ -93,16 +88,15 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> // Try reading components try { - FileUtils.traverseDirectory(sourceDirectory, - firstLevelTraverser, (pth, attr) -> { - loadComponent(componentReader, pth); + FileUtils.traverseDirectory(sourceDirectory, firstLevelTraverser, (pth, attr) -> { + loadComponent(componentReader, pth); - // Keep loading components, even if this one failed - return true; - }); + // Keep loading components, even if this one + // failed + return true; + }); } catch (IOException ioex) { - CLASS_LOGGER.log(Level.WARNING, ioex, - () -> "Error found reading component from file."); + CLASS_LOGGER.log(Level.WARNING, ioex, () -> "Error found reading component from file."); } } @@ -129,20 +123,17 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> /* * Load a component from a file */ - private void loadComponent( - Function<File, ? extends ComponentType> componentReader, - Path pth) { + private void loadComponent(Function<File, ? extends ComponentType> componentReader, Path pth) { try { // Try to load the component ComponentType component = componentReader.apply(pth.toFile()); if (component == null) { - throw new NullPointerException( - "Component reader read null component"); + throw new NullPointerException("Component reader read null component"); } else if (!components.containsKey(component.getName())) { - // We only care about the latest version of a component - ComponentType oldComponent = components - .put(component.getName(), component); + // We only care about the latest version of a + // component + ComponentType oldComponent = components.put(component.getName(), component); if (oldComponent.getVersion() > component.getVersion()) { components.put(oldComponent.getName(), oldComponent); @@ -150,14 +141,12 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> } else { CLASS_LOGGER.warning("Found a duplicate component.\n" + "Multiple versions of the same component are not currently supported.\n" - + "Only the latest version of the component" - + component + " will be registered ."); + + "Only the latest version of the component" + component + + " will be registered ."); } } catch (Exception ex) { - CLASS_LOGGER.log(Level.WARNING, ex, - () -> "Error found reading component from file " - + pth.toString() - + ". This component will not be loaded"); + CLASS_LOGGER.log(Level.WARNING, ex, () -> "Error found reading component from file " + + pth.toString() + ". This component will not be loaded"); } } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java index a4dbfde..f3aab76 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java @@ -10,15 +10,14 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <ComponentType> - * The type of components contained in this repository + * The type of components contained in this repository */ -public interface IComponentRepository< - ComponentType extends IDescribedComponent> { +public interface IComponentRepository<ComponentType extends IDescribedComponent> { /** * Get all of the components this repository knows about * - * @return A map from component name to component, containing all of - * the components in the repositories + * @return A map from component name to component, containing all of the + * components in the repositories */ public IMap<String, ComponentType> getAll(); @@ -26,7 +25,7 @@ public interface IComponentRepository< * Get a component with a specific name * * @param name - * The name of the component to retrieve + * The name of the component to retrieve * @return The named component, or null if no component with that name * exists */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java b/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java index c3576a3..6b87ba7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IDescribedComponent.java @@ -1,8 +1,8 @@ package bjc.utils.components; /** - * Represents a optional component that has status information associated - * with it + * Represents a optional component that has status information associated with + * it * * @author ben * diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java index 04a93fa..8e0bf86 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/CircularIterator.java @@ -27,8 +27,8 @@ public class CircularIterator<E> implements Iterator<E> { } public E next() { - if(!curr.hasNext()) { - if(doCircle) { + if (!curr.hasNext()) { + if (doCircle) { curr = source.iterator(); } else { return curElm; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Either.java b/BJC-Utils2/src/main/java/bjc/utils/data/Either.java index 3ab4c00..7ec1720 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Either.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Either.java @@ -8,26 +8,24 @@ import java.util.function.Function; * * @author ben * @param <LeftType> - * The type that could be on the left + * The type that could be on the left * @param <RightType> - * The type that could be on the right + * The type that could be on the right * */ -public class Either<LeftType, RightType> - implements IPair<LeftType, RightType> { +public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { /** * Create a new either with the left value occupied * * @param <LeftType> - * The type of the left value + * The type of the left value * @param <RightType> - * The type of the empty right value + * The type of the empty right value * @param left - * The value to put on the left + * The value to put on the left * @return An either with the left side occupied */ - public static <LeftType, RightType> Either<LeftType, RightType> fromLeft( - LeftType left) { + public static <LeftType, RightType> Either<LeftType, RightType> fromLeft(LeftType left) { return new Either<>(left, null); } @@ -35,25 +33,24 @@ public class Either<LeftType, RightType> * Create a new either with the right value occupied * * @param <LeftType> - * The type of the empty left value + * The type of the empty left value * @param <RightType> - * The type of the right value + * The type of the right value * @param right - * The value to put on the right + * The value to put on the right * @return An either with the right side occupied */ - public static <LeftType, RightType> Either<LeftType, RightType> fromRight( - RightType right) { + public static <LeftType, RightType> Either<LeftType, RightType> fromRight(RightType right) { return new Either<>(null, right); } - private LeftType leftVal; + private LeftType leftVal; - private RightType rightVal; + private RightType rightVal; - private boolean isLeft; + private boolean isLeft; - private Either( LeftType left, RightType right) { + private Either(LeftType left, RightType right) { if (left == null) { rightVal = right; } else { @@ -91,8 +88,7 @@ public class Either<LeftType, RightType> public <BoundRight> IPair<LeftType, BoundRight> bindRight( Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { if (rightBinder == null) { - throw new NullPointerException( - "Right binder must not be null"); + throw new NullPointerException("Right binder must not be null"); } if (isLeft) { @@ -110,29 +106,24 @@ public class Either<LeftType, RightType> if (otherPair == null) { throw new NullPointerException("Other pair must not be null"); } else if (leftCombiner == null) { - throw new NullPointerException( - "Left combiner must not be null"); + throw new NullPointerException("Left combiner must not be null"); } else if (rightCombiner == null) { - throw new NullPointerException( - "Right combiner must not be null"); + throw new NullPointerException("Right combiner must not be null"); } if (isLeft) { return otherPair.bind((otherLeft, otherRight) -> { - return new Either<>(leftCombiner.apply(leftVal, otherLeft), - null); + return new Either<>(leftCombiner.apply(leftVal, otherLeft), null); }); } return otherPair.bind((otherLeft, otherRight) -> { - return new Either<>(null, - rightCombiner.apply(rightVal, otherRight)); + return new Either<>(null, rightCombiner.apply(rightVal, otherRight)); }); } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft( - Function<LeftType, NewLeft> mapper) { + public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } @@ -145,8 +136,7 @@ public class Either<LeftType, RightType> } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight( - Function<RightType, NewRight> mapper) { + public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } @@ -159,8 +149,7 @@ public class Either<LeftType, RightType> } @Override - public <MergedType> MergedType merge( - BiFunction<LeftType, RightType, MergedType> merger) { + public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { if (merger == null) { throw new NullPointerException("Merger must not be null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java index a05d90e..7b6c8d5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java @@ -16,26 +16,25 @@ import bjc.utils.funcdata.theory.Functor; * @author ben * * @param <ContainedType> - * The type of value held + * The type of value held */ public interface IHolder<ContainedType> extends Functor<ContainedType> { /** * Bind a function across the value in this container * * @param <BoundType> - * The type of value in this container + * The type of value in this container * @param binder - * The function to bind to the value + * The function to bind to the value * @return A holder from binding the value */ - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder); + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder); /** * Apply an action to the value * * @param action - * The action to apply to the value + * The action to apply to the value */ public default void doWith(Consumer<? super ContainedType> action) { transform((value) -> { @@ -46,10 +45,8 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { } @Override - default <ArgType, - ReturnType> Function<Functor<ArgType>, - Functor<ReturnType>> fmap( - Function<ArgType, ReturnType> func) { + default <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( + Function<ArgType, ReturnType> func) { return (argumentFunctor) -> { if (!(argumentFunctor instanceof IHolder<?>)) { throw new IllegalArgumentException( @@ -71,13 +68,12 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Lifts a function to bind over this holder * * @param <NewType> - * The type of the functions return + * The type of the functions return * @param func - * The function to lift over the holder + * The function to lift over the holder * @return The function lifted over the holder */ - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func); + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func); /** * Make this holder lazy @@ -113,19 +109,18 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Does not change the internal state of this holder * * @param <MappedType> - * The type of the mapped value + * The type of the mapped value * @param mapper - * The function to do mapping with + * The function to do mapping with * @return A holder with the mapped value */ - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper); + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper); /** * Replace the held value with a new one * * @param newValue - * The value to hold instead + * The value to hold instead * @return The holder itself */ public default IHolder<ContainedType> replace(ContainedType newValue) { @@ -138,22 +133,20 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Transform the value held in this holder * * @param transformer - * The function to transform the value with + * The function to transform the value with * @return The holder itself, for easy chaining */ - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer); + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer); /** * Unwrap the value contained in this holder so that it is no longer * held * * @param <UnwrappedType> - * The type of the unwrapped value + * The type of the unwrapped value * @param unwrapper - * The function to use to unwrap the value + * The function to use to unwrap the value * @return The unwrapped held value */ - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper); + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java index c82cc8e..1405d75 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java @@ -11,35 +11,33 @@ import bjc.utils.funcdata.theory.Bifunctor; * * @author ben * @param <LeftType> - * The type of the left side of the pair + * The type of the left side of the pair * @param <RightType> - * The type of the right side of the pair + * The type of the right side of the pair * */ -public interface IPair<LeftType, RightType> - extends Bifunctor<LeftType, RightType> { +public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightType> { /** * Bind a function across the values in this pair * * @param <BoundLeft> - * The type of the bound left + * The type of the bound left * @param <BoundRight> - * The type of the bound right + * The type of the bound right * @param binder - * The function to bind with + * The function to bind with * @return The bound pair */ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, - IPair<BoundLeft, BoundRight>> binder); + BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder); /** * Bind a function to the left value in this pair * * @param <BoundLeft> - * The type of the bound value + * The type of the bound value * @param leftBinder - * The function to use to bind + * The function to use to bind * @return A pair with the left type bound */ public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( @@ -49,9 +47,9 @@ public interface IPair<LeftType, RightType> * Bind a function to the right value in this pair * * @param <BoundRight> - * The type of the bound value + * The type of the bound value * @param rightBinder - * The function to use to bind + * The function to use to bind * @return A pair with the right type bound */ public <BoundRight> IPair<LeftType, BoundRight> bindRight( @@ -61,19 +59,16 @@ public interface IPair<LeftType, RightType> * Pairwise combine two pairs together * * @param <OtherLeft> - * The left type of the other pair + * The left type of the other pair * @param <OtherRight> - * The right type of the other pair + * The right type of the other pair * @param otherPair - * The pair to combine with + * The pair to combine with * @return The pairs, pairwise combined together */ - public default <OtherLeft, - OtherRight> IPair<IPair<LeftType, OtherLeft>, - IPair<RightType, OtherRight>> combine( - IPair<OtherLeft, OtherRight> otherPair) { - return combine(otherPair, - (left, otherLeft) -> new Pair<>(left, otherLeft), + public default <OtherLeft, OtherRight> IPair<IPair<LeftType, OtherLeft>, IPair<RightType, OtherRight>> combine( + IPair<OtherLeft, OtherRight> otherPair) { + return combine(otherPair, (left, otherLeft) -> new Pair<>(left, otherLeft), (right, otherRight) -> new Pair<>(right, otherRight)); } @@ -81,33 +76,30 @@ public interface IPair<LeftType, RightType> * Combine the contents of two pairs together * * @param <OtherLeft> - * The type of the left value of the other pair + * The type of the left value of the other pair * @param <OtherRight> - * The type of the right value of the other pair + * The type of the right value of the other pair * @param <CombinedLeft> - * The type of the left value of the combined pair + * The type of the left value of the combined pair * @param <CombinedRight> - * The type of the right value of the combined pair + * The type of the right value of the combined pair * @param otherPair - * The other pair to combine with + * The other pair to combine with * @param leftCombiner * @param rightCombiner * @return A pair with its values combined */ - public <OtherLeft, OtherRight, CombinedLeft, - CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, - CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, - CombinedRight> rightCombiner); + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( + IPair<OtherLeft, OtherRight> otherPair, + BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + BiFunction<RightType, OtherRight, CombinedRight> rightCombiner); /** * Immediately perfom the specified action with the contents of this * pair * * @param consumer - * The action to perform on the pair + * The action to perform on the pair */ public default void doWith(BiConsumer<LeftType, RightType> consumer) { merge((leftValue, rightValue) -> { @@ -118,26 +110,22 @@ public interface IPair<LeftType, RightType> } @Override - default <OldLeft, OldRight, - NewLeft> Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<NewLeft, OldRight>> fmapLeft( - Function<OldLeft, NewLeft> func) { + default <OldLeft, OldRight, NewLeft> Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, OldRight>> fmapLeft( + Function<OldLeft, NewLeft> func) { return (argumentPair) -> { if (!(argumentPair instanceof IPair<?, ?>)) { throw new IllegalArgumentException( "This function can only be applied to instances of IPair"); } - IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, - OldRight>) argumentPair; + IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapLeft(func); }; } @Override - default <OldLeft, OldRight, NewRight> Function< - Bifunctor<OldLeft, OldRight>, Bifunctor<OldLeft, NewRight>> + default <OldLeft, OldRight, NewRight> Function<Bifunctor<OldLeft, OldRight>, Bifunctor<OldLeft, NewRight>> fmapRight(Function<OldRight, NewRight> func) { return (argumentPair) -> { @@ -146,8 +134,7 @@ public interface IPair<LeftType, RightType> "This function can only be applied to instances of IPair"); } - IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, - OldRight>) argumentPair; + IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapRight(func); }; @@ -178,38 +165,35 @@ public interface IPair<LeftType, RightType> * pair * * @param <NewLeft> - * The new type of the left part of the pair + * The new type of the left part of the pair * @param mapper - * The function to use to transform the left part of the - * pair + * The function to use to transform the left part of the + * pair * @return The pair, with its left part transformed */ - public <NewLeft> IPair<NewLeft, RightType> mapLeft( - Function<LeftType, NewLeft> mapper); + public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper); /** - * Transform the value on the right side of the pair. Doesn't modify - * the pair + * Transform the value on the right side of the pair. Doesn't modify the + * pair * * @param <NewRight> - * The new type of the right part of the pair + * The new type of the right part of the pair * @param mapper - * The function to use to transform the right part of the - * pair + * The function to use to transform the right part of the + * pair * @return The pair, with its right part transformed */ - public <NewRight> IPair<LeftType, NewRight> mapRight( - Function<RightType, NewRight> mapper); + public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper); /** * Merge the two values in this pair into a single value * * @param <MergedType> - * The type of the single value + * The type of the single value * @param merger - * The function to use for merging + * The function to use for merging * @return The pair, merged into a single value */ - public <MergedType> MergedType merge( - BiFunction<LeftType, RightType, MergedType> merger); + public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java b/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java index 7d5988f..4b6725c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ITree.java @@ -13,7 +13,7 @@ import bjc.utils.funcdata.bst.TreeLinearizationMethod; * * @author ben * @param <ContainedType> - * The type of data contained in the tree nodes + * The type of data contained in the tree nodes * */ public interface ITree<ContainedType> { @@ -21,7 +21,7 @@ public interface ITree<ContainedType> { * Add a child to this node * * @param child - * The child to add to this node + * The child to add to this node */ public void addChild(ITree<ContainedType> child); @@ -29,49 +29,46 @@ public interface ITree<ContainedType> { * Collapse a tree into a single version * * @param <NewType> - * The intermediate type being folded + * The intermediate type being folded * @param <ReturnedType> - * The type that is the end result + * The type that is the end result * @param leafTransform - * The function to use to convert leaf values + * The function to use to convert leaf values * @param nodeCollapser - * The function to use to convert internal nodes and their - * children + * The function to use to convert internal nodes and + * their children * @param resultTransformer - * The function to use to convert a state to the returned - * version + * The function to use to convert a state to the returned + * version * @return The final transformed state */ - public <NewType, ReturnedType> ReturnedType collapse( - Function<ContainedType, NewType> leafTransform, - Function<ContainedType, - Function<IList<NewType>, NewType>> nodeCollapser, + public <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, + Function<ContainedType, Function<IList<NewType>, NewType>> nodeCollapser, Function<NewType, ReturnedType> resultTransformer); /** * Execute a given action for each of this tree's children * * @param action - * The action to execute for each child + * The action to execute for each child */ void doForChildren(Consumer<ITree<ContainedType>> action); /** - * Expand the nodes of a tree into trees, and then merge the contents - * of those trees into a single tree + * Expand the nodes of a tree into trees, and then merge the contents of + * those trees into a single tree * * @param mapper - * The function to use to map values into trees + * The function to use to map values into trees * @return A tree, with some nodes expanded into trees */ - public ITree<ContainedType> flatMapTree( - Function<ContainedType, ITree<ContainedType>> mapper); + public ITree<ContainedType> flatMapTree(Function<ContainedType, ITree<ContainedType>> mapper); /** * Get the specified child of this tree * * @param childNo - * The number of the child to get + * The number of the child to get * @return The specified child of this tree */ default ITree<ContainedType> getChild(int childNo) { @@ -98,56 +95,52 @@ public interface ITree<ContainedType> { * Rebuild the tree with the same structure, but different nodes * * @param <MappedType> - * The type of the new tree + * The type of the new tree * @param leafTransformer - * The function to use to transform leaf tokens + * The function to use to transform leaf tokens * @param operatorTransformer - * The function to use to transform internal tokens + * The function to use to transform internal tokens * @return The tree, with the nodes changed */ - public <MappedType> ITree<MappedType> rebuildTree( - Function<ContainedType, MappedType> leafTransformer, + public <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, Function<ContainedType, MappedType> operatorTransformer); /** * Transform some of the nodes in this tree * * @param nodePicker - * The predicate to use to pick nodes to transform + * The predicate to use to pick nodes to transform * @param transformer - * The function to use to transform picked nodes + * The function to use to transform picked nodes */ - public void selectiveTransform(Predicate<ContainedType> nodePicker, - UnaryOperator<ContainedType> transformer); + public void selectiveTransform(Predicate<ContainedType> nodePicker, UnaryOperator<ContainedType> transformer); /** * Do a top-down transform of the tree * * @param transformPicker - * The function to use to pick how to progress + * The function to use to pick how to progress * @param transformer - * The function used to transform picked subtrees + * The function used to transform picked subtrees * @return The tree with the transform applied to picked subtrees */ - public ITree<ContainedType> topDownTransform( - Function<ContainedType, - TopDownTransformResult> transformPicker, + public ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, UnaryOperator<ITree<ContainedType>> transformer); /** * Transform one of this nodes children * * @param <TransformedType> - * The type of the transformed value + * The type of the transformed value * @param childNo - * The number of the child to transform + * The number of the child to transform * @param transformer - * The function to use to transform the value + * The function to use to transform the value * @return The transformed value * * @throws IllegalArgumentException - * if the childNo is out of bounds (0 <= childNo <= - * childCount()) + * if the childNo is out of bounds (0 <= childNo <= + * childCount()) */ public <TransformedType> TransformedType transformChild(int childNo, Function<ITree<ContainedType>, TransformedType> transformer); @@ -156,34 +149,31 @@ public interface ITree<ContainedType> { * Transform the value that is the head of this node * * @param <TransformedType> - * The type of the transformed value + * The type of the transformed value * @param transformer - * The function to use to transform the value + * The function to use to transform the value * @return The transformed value */ - public <TransformedType> TransformedType transformHead( - Function<ContainedType, TransformedType> transformer); + public <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer); /** * Transform the tree into a tree with a different type of token * * @param <MappedType> - * The type of the new tree + * The type of the new tree * @param transformer - * The function to use to transform tokens + * The function to use to transform tokens * @return A tree with the token types transformed */ - public <MappedType> ITree<MappedType> transformTree( - Function<ContainedType, MappedType> transformer); + public <MappedType> ITree<MappedType> transformTree(Function<ContainedType, MappedType> transformer); /** * Perform an action on each part of the tree * * @param linearizationMethod - * The way to traverse the tree + * The way to traverse the tree * @param action - * The action to perform on each tree node + * The action to perform on each tree node */ - public void traverse(TreeLinearizationMethod linearizationMethod, - Consumer<ContainedType> action); + public void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java b/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java index 8fcaf98..aa3f7aa 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Identity.java @@ -14,7 +14,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type contained in the holder + * The type contained in the holder */ public class Identity<ContainedType> implements IHolder<ContainedType> { private ContainedType heldValue; @@ -30,15 +30,14 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * Create a holder holding the specified value * * @param value - * The value to hold + * The value to hold */ public Identity(ContainedType value) { heldValue = value; } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { return binder.apply(heldValue); } @@ -89,16 +88,14 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new Identity<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { return new Identity<>(mapper.apply(heldValue)); } @@ -108,16 +105,14 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { heldValue = transformer.apply(heldValue); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValue); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java index 6339795..3a037d7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java @@ -9,28 +9,27 @@ import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; /** - * A holder that holds a means to create a value, but doesn't actually - * compute the value until it's needed + * A holder that holds a means to create a value, but doesn't actually compute + * the value until it's needed * * @author ben * * @param <ContainedType> */ public class Lazy<ContainedType> implements IHolder<ContainedType> { - private Supplier<ContainedType> valueSupplier; + private Supplier<ContainedType> valueSupplier; - private IList<UnaryOperator< - ContainedType>> actions = new FunctionalList<>(); + private IList<UnaryOperator<ContainedType>> actions = new FunctionalList<>(); - private boolean valueMaterialized; + private boolean valueMaterialized; - private ContainedType heldValue; + private ContainedType heldValue; /** * Create a new lazy value from the specified seed value * * @param value - * The seed value to use + * The seed value to use */ public Lazy(ContainedType value) { heldValue = value; @@ -42,7 +41,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * Create a new lazy value from the specified value source * * @param supp - * The source of a value to use + * The source of a value to use */ public Lazy(Supplier<ContainedType> supp) { valueSupplier = new SingleSupplier<>(supp); @@ -50,18 +49,15 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { valueMaterialized = false; } - private Lazy(Supplier<ContainedType> supp, - IList<UnaryOperator<ContainedType>> pendingActions) { + private Lazy(Supplier<ContainedType> supp, IList<UnaryOperator<ContainedType>> pendingActions) { valueSupplier = supp; actions = pendingActions; } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { - IList<UnaryOperator< - ContainedType>> pendingActions = new FunctionalList<>(); + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { + IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); @@ -79,18 +75,15 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { - IList<UnaryOperator< - ContainedType>> pendingActions = new FunctionalList<>(); + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { + IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); @@ -101,8 +94,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { currVal = valueSupplier.get(); } - return pendingActions.reduceAux(currVal, - UnaryOperator<ContainedType>::apply, + return pendingActions.reduceAux(currVal, UnaryOperator<ContainedType>::apply, (value) -> mapper.apply(value)); }); } @@ -121,16 +113,14 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { actions.add(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { if (!valueMaterialized) { heldValue = valueSupplier.get(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java index e03b46e..29e37ac 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java @@ -13,29 +13,28 @@ import bjc.utils.data.internals.HalfBoundLazyPair; * @author ben * * @param <LeftType> - * The type on the left side of the pair + * The type on the left side of the pair * @param <RightType> - * The type on the right side of the pair + * The type on the right side of the pair * */ -public class LazyPair<LeftType, RightType> - implements IPair<LeftType, RightType> { - private LeftType leftValue; - private RightType rightValue; +public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> { + private LeftType leftValue; + private RightType rightValue; - private Supplier<LeftType> leftSupplier; - private Supplier<RightType> rightSupplier; + private Supplier<LeftType> leftSupplier; + private Supplier<RightType> rightSupplier; - private boolean leftMaterialized; - private boolean rightMaterialized; + private boolean leftMaterialized; + private boolean rightMaterialized; /** * Create a new lazy pair, using the set values * * @param leftVal - * The value for the left side of the pair + * The value for the left side of the pair * @param rightVal - * The value for the right side of the pair + * The value for the right side of the pair */ public LazyPair(LeftType leftVal, RightType rightVal) { leftValue = leftVal; @@ -49,12 +48,11 @@ public class LazyPair<LeftType, RightType> * Create a new lazy pair from the given value sources * * @param leftSupp - * The source for a value on the left side of the pair + * The source for a value on the left side of the pair * @param rightSupp - * The source for a value on the right side of the pair + * The source for a value on the right side of the pair */ - public LazyPair(Supplier<LeftType> leftSupp, - Supplier<RightType> rightSupp) { + public LazyPair(Supplier<LeftType> leftSupp, Supplier<RightType> rightSupp) { // Use single suppliers to catch double-instantiation bugs leftSupplier = new SingleSupplier<>(leftSupp); rightSupplier = new SingleSupplier<>(rightSupp); @@ -70,7 +68,8 @@ public class LazyPair<LeftType, RightType> } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( + Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { Supplier<LeftType> leftSupp = () -> { if (leftMaterialized) { return leftValue; @@ -97,17 +96,13 @@ public class LazyPair<LeftType, RightType> } @Override - public <OtherLeft, OtherRight, CombinedLeft, - CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, - CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, - CombinedRight> rightCombiner) { + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( + IPair<OtherLeft, OtherRight> otherPair, + BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - return new LazyPair<>( - leftCombiner.apply(leftVal, otherLeft), + return new LazyPair<>(leftCombiner.apply(leftVal, otherLeft), rightCombiner.apply(rightVal, otherRight)); }); }); @@ -136,8 +131,7 @@ public class LazyPair<LeftType, RightType> } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft( - Function<LeftType, NewLeft> mapper) { + public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { Supplier<NewLeft> leftSupp = () -> { if (leftMaterialized) { return mapper.apply(leftValue); @@ -158,8 +152,7 @@ public class LazyPair<LeftType, RightType> } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight( - Function<RightType, NewRight> mapper) { + public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { Supplier<LeftType> leftSupp = () -> { if (leftMaterialized) { return leftValue; @@ -180,8 +173,7 @@ public class LazyPair<LeftType, RightType> } @Override - public <MergedType> MergedType merge( - BiFunction<LeftType, RightType, MergedType> merger) { + public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { if (!leftMaterialized) { leftValue = leftSupplier.get(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java index a77cd16..5c14475 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java @@ -13,7 +13,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <ContainedType> - * The type of contained value + * The type of contained value */ public class ListHolder<ContainedType> implements IHolder<ContainedType> { private IList<ContainedType> heldValues; @@ -22,7 +22,7 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { * Create a new list holder * * @param values - * The possible values for the computation + * The possible values for the computation */ @SafeVarargs public ListHolder(ContainedType... values) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java index 33b6327..210d2aa 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java @@ -9,7 +9,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type of the value that may or may not be held + * The type of the value that may or may not be held */ public class Option<ContainedType> implements IHolder<ContainedType> { private ContainedType held; @@ -18,7 +18,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { * Create a new optional, using the given initial value * * @param seed - * The initial value for the optional + * The initial value for the optional */ public Option(ContainedType seed) { held = seed; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java index 74040e8..b22fd28 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java @@ -9,16 +9,16 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type of the left value + * The type of the left value * @param <RightType> - * The type of the right value + * The type of the right value */ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { // The left value - private LeftType leftValue; + private LeftType leftValue; // The right value - private RightType rightValue; + private RightType rightValue; /** * Create a new pair with both sides set to null @@ -31,9 +31,9 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new pair with both sides set to the specified values * * @param left - * The value of the left side + * The value of the left side * @param right - * The value of the right side + * The value of the right side */ public Pair(LeftType left, RightType right) { leftValue = left; @@ -51,7 +51,8 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( + Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { if (leftBinder == null) { throw new NullPointerException("Binder must not be null"); } @@ -60,7 +61,8 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { } @Override - public <BoundRight> IPair<LeftType, BoundRight> bindRight(Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { + public <BoundRight> IPair<LeftType, BoundRight> bindRight( + Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { if (rightBinder == null) { throw new NullPointerException("Binder must not be null"); } @@ -73,9 +75,10 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { IPair<OtherLeft, OtherRight> otherPair, BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { - return otherPair.bind((otherLeft, otherRight) -> { - return new Pair<>(leftCombiner.apply(leftValue, otherLeft), rightCombiner.apply(rightValue, otherRight)); - }); + return otherPair.bind((otherLeft, otherRight) -> { + return new Pair<>(leftCombiner.apply(leftValue, otherLeft), + rightCombiner.apply(rightValue, otherRight)); + }); } @Override diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java index b5ff1e3..bf8b0a0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java @@ -5,31 +5,30 @@ import java.util.function.Supplier; /** * A supplier that can only supply one value. * - * Attempting to retrieve another value will cause an exception to be - * thrown. + * Attempting to retrieve another value will cause an exception to be thrown. * * @author ben * * @param <T> */ public class SingleSupplier<T> implements Supplier<T> { - private static long nextID = 0; + private static long nextID = 0; - private Supplier<T> source; + private Supplier<T> source; - private boolean gotten; + private boolean gotten; - private long id; + private long id; // This is bad practice, but I want to know where the single // instantiation was, in case of duplicate initiations - private Exception instSite; + private Exception instSite; /** * Create a new single supplier from an existing value * * @param supp - * The supplier to give a single value from + * The supplier to give a single value from */ public SingleSupplier(Supplier<T> supp) { source = supp; @@ -42,10 +41,8 @@ public class SingleSupplier<T> implements Supplier<T> { @Override public T get() { if (gotten == true) { - IllegalStateException isex = new IllegalStateException( - "Attempted to get value more than once" - + " from single supplier #" + id - + ". Previous instantiation below."); + IllegalStateException isex = new IllegalStateException("Attempted to get value more than once" + + " from single supplier #" + id + ". Previous instantiation below."); isex.initCause(instSite); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java index d37123f..8a24512 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformIterator.java @@ -12,13 +12,11 @@ import static bjc.utils.data.TopDownTransformResult.*; public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<ContainedType>> { private Function<ContainedType, TopDownTransformResult> picker; - private BiFunction<ITree<ContainedType>, - Consumer<Iterator<ITree<ContainedType>>>, - ITree<ContainedType>> transform; + private BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transform; private ITree<ContainedType> preParent; private ITree<ContainedType> postParent; - + private Deque<ITree<ContainedType>> preChildren; private Deque<ITree<ContainedType>> postChildren; @@ -28,29 +26,29 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C private boolean initial; private Deque<Iterator<ITree<ContainedType>>> toYield; - private Iterator<ITree<ContainedType>> curYield; + private Iterator<ITree<ContainedType>> curYield; - public TopDownTransformIterator(Function<ContainedType, TopDownTransformResult> pickr, + public TopDownTransformIterator(Function<ContainedType, TopDownTransformResult> pickr, BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> transfrm, ITree<ContainedType> tree) { preParent = tree; - preChildren = new LinkedList<>(); + preChildren = new LinkedList<>(); postChildren = new LinkedList<>(); - toYield = new LinkedList<>(); + toYield = new LinkedList<>(); - picker = pickr; + picker = pickr; transform = transfrm; - done = false; + done = false; initial = true; } public void addYield(Iterator<ITree<ContainedType>> src) { - if(curYield != null) { + if (curYield != null) { toYield.push(curYield); } - + curYield = src; } @@ -59,17 +57,17 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } public ITree<ContainedType> flushYields(ITree<ContainedType> val) { - if(curYield != null) { + if (curYield != null) { toYield.add(new SingleIterator<>(val)); - if(curYield.hasNext()) { + if (curYield.hasNext()) { return curYield.next(); } else { - while(toYield.size() != 0 && !curYield.hasNext()) { + while (toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if(toYield.size() == 0 && !curYield.hasNext()) { + if (toYield.size() == 0 && !curYield.hasNext()) { curYield = null; return val; } else { @@ -82,17 +80,18 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } public ITree<ContainedType> next() { - if(done) throw new NoSuchElementException(); + if (done) + throw new NoSuchElementException(); - if(curYield != null) { - if(curYield.hasNext()) { + if (curYield != null) { + if (curYield.hasNext()) { return curYield.next(); } else { - while(toYield.size() != 0 && !curYield.hasNext()) { + while (toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if(toYield.size() == 0 && !curYield.hasNext()) { + if (toYield.size() == 0 && !curYield.hasNext()) { curYield = null; } else { return curYield.next(); @@ -100,73 +99,74 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } } - if(initial) { + if (initial) { TopDownTransformResult res = picker.apply(preParent.getHead()); - switch(res) { - case PASSTHROUGH: - postParent = new Tree<>(preParent.getHead()); - - if(preParent.getChildrenCount() != 0) { - for(int i = 0; i < preParent.getChildrenCount(); i++) { - preChildren.add(preParent.getChild(i)); - } - - // Return whatever the first child is - break; - } else { - done = true; - return flushYields(postParent); + switch (res) { + case PASSTHROUGH: + postParent = new Tree<>(preParent.getHead()); + + if (preParent.getChildrenCount() != 0) { + for (int i = 0; i < preParent.getChildrenCount(); i++) { + preChildren.add(preParent.getChild(i)); } - case SKIP: - done = true; - return flushYields(preParent); - case TRANSFORM: + + // Return whatever the first child is + break; + } else { done = true; - return flushYields(transform.apply(preParent, this::addYield)); - case RTRANSFORM: - preParent = transform.apply(preParent, this::addYield); - return flushYields(preParent); - case PUSHDOWN: - if(preParent.getChildrenCount() != 0) { - for(int i = 0; i < preParent.getChildrenCount(); i++) { - preChildren.add(preParent.getChild(i)); - } - - // Return whatever the first child is - break; - } else { - done = true; - return flushYields(transform.apply(new Tree<>(preParent.getHead()), this::addYield)); + return flushYields(postParent); + } + case SKIP: + done = true; + return flushYields(preParent); + case TRANSFORM: + done = true; + return flushYields(transform.apply(preParent, this::addYield)); + case RTRANSFORM: + preParent = transform.apply(preParent, this::addYield); + return flushYields(preParent); + case PUSHDOWN: + if (preParent.getChildrenCount() != 0) { + for (int i = 0; i < preParent.getChildrenCount(); i++) { + preChildren.add(preParent.getChild(i)); } - case PULLUP: - ITree<ContainedType> intRes = transform.apply(preParent, this::addYield); - - postParent = new Tree<>(intRes.getHead()); - - if(intRes.getChildrenCount() != 0) { - for(int i = 0; i < intRes.getChildrenCount(); i++) { - preChildren.add(intRes.getChild(i)); - } - - // Return whatever the first child is - break; - } else { - done = true; - return flushYields(postParent); + + // Return whatever the first child is + break; + } else { + done = true; + return flushYields(transform.apply(new Tree<>(preParent.getHead()), + this::addYield)); + } + case PULLUP: + ITree<ContainedType> intRes = transform.apply(preParent, this::addYield); + + postParent = new Tree<>(intRes.getHead()); + + if (intRes.getChildrenCount() != 0) { + for (int i = 0; i < intRes.getChildrenCount(); i++) { + preChildren.add(intRes.getChild(i)); } - default: - throw new IllegalArgumentException("Unknown result type " + res); + + // Return whatever the first child is + break; + } else { + done = true; + return flushYields(postParent); + } + default: + throw new IllegalArgumentException("Unknown result type " + res); } - if(res != RTRANSFORM) initial = false; + if (res != RTRANSFORM) + initial = false; } - - if(curChild == null || !curChild.hasNext()) { - if(preChildren.size() != 0) { + if (curChild == null || !curChild.hasNext()) { + if (preChildren.size() != 0) { curChild = new TopDownTransformIterator<>(picker, transform, preChildren.pop()); - + ITree<ContainedType> res = curChild.next(); System.out.println("\t\tTRACE: adding node " + res + " to children"); postChildren.add(res); @@ -175,21 +175,22 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } else { ITree<ContainedType> res = null; - if(postParent == null) { + if (postParent == null) { res = new Tree<>(preParent.getHead()); System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for(ITree<ContainedType> child : postChildren) { + for (ITree<ContainedType> child : postChildren) { res.addChild(child); } - - // res = transform.apply(res, this::addYield); + + // res = transform.apply(res, + // this::addYield); } else { res = postParent; System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for(ITree<ContainedType> child : postChildren) { + for (ITree<ContainedType> child : postChildren) { res.addChild(child); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java b/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java index 848b6ac..742a73b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TransformedIterator.java @@ -10,7 +10,7 @@ public class TransformedIterator<PreType, PostType> implements Iterator<PostType public TransformedIterator(Iterator<PreType> src, Function<PreType, PostType> trans) { source = src; - trans = transform; + trans = transform; } public boolean hasNext() { diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java index 5fed73f..6a16491 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java @@ -17,11 +17,11 @@ import bjc.utils.funcdata.bst.TreeLinearizationMethod; * @param <ContainedType> */ public class Tree<ContainedType> implements ITree<ContainedType> { - private ContainedType data; + private ContainedType data; - private IList<ITree<ContainedType>> children; - private boolean hasChildren; - private int childCount = 0; + private IList<ITree<ContainedType>> children; + private boolean hasChildren; + private int childCount = 0; private int ID; private static int nextID = 0; @@ -30,7 +30,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new leaf node in a tree * * @param leaf - * The data to store as a leaf node + * The data to store as a leaf node */ public Tree(ContainedType leaf) { data = leaf; @@ -44,9 +44,9 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children * * @param leaf - * The data to hold in this node + * The data to hold in this node * @param childrn - * A list of children for this node + * A list of children for this node */ public Tree(ContainedType leaf, IList<ITree<ContainedType>> childrn) { this(leaf); @@ -60,9 +60,9 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children * * @param leaf - * The data to hold in this node + * The data to hold in this node * @param childrn - * A list of children for this node + * A list of children for this node */ @SafeVarargs public Tree(ContainedType leaf, ITree<ContainedType>... childrn) { @@ -95,8 +95,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <NewType, ReturnedType> ReturnedType collapse( - Function<ContainedType, NewType> leafTransform, + public <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, Function<ContainedType, Function<IList<NewType>, NewType>> nodeCollapser, Function<NewType, ReturnedType> resultTransformer) { @@ -127,14 +126,13 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return childCount; } - protected <NewType> NewType internalCollapse( - Function<ContainedType, NewType> leafTransform, + protected <NewType> NewType internalCollapse(Function<ContainedType, NewType> leafTransform, Function<ContainedType, Function<IList<NewType>, NewType>> nodeCollapser) { if (hasChildren) { Function<IList<NewType>, NewType> nodeTransformer = nodeCollapser.apply(data); IList<NewType> collapsedChildren = (IList<NewType>) children.map((child) -> { - return child.collapse(leafTransform, nodeCollapser, (subTreeVal) -> subTreeVal); + return child.collapse(leafTransform, nodeCollapser, (subTreeVal) -> subTreeVal); }); return nodeTransformer.apply(collapsedChildren); @@ -144,7 +142,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } protected void internalToString(StringBuilder builder, int indentLevel, boolean initial) { - for(int i = 0; i < indentLevel; i++) { + for (int i = 0; i < indentLevel; i++) { builder.append(">\t"); } @@ -156,19 +154,17 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach((child) -> { - ((Tree<ContainedType>) child).internalToString(builder, indentLevel+1, false); + ((Tree<ContainedType>) child).internalToString(builder, indentLevel + 1, false); }); } } @Override - public <MappedType> ITree<MappedType> rebuildTree( - Function<ContainedType, MappedType> leafTransformer, + public <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, Function<ContainedType, MappedType> operatorTransformer) { if (hasChildren) { IList<ITree<MappedType>> mappedChildren = children.map((child) -> { - return child.rebuildTree(leafTransformer, - operatorTransformer); + return child.rebuildTree(leafTransformer, operatorTransformer); }); return new Tree<>(operatorTransformer.apply(data), mappedChildren); @@ -187,50 +183,49 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public ITree<ContainedType> topDownTransform( - Function<ContainedType, TopDownTransformResult> transformPicker, + public ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, UnaryOperator<ITree<ContainedType>> transformer) { TopDownTransformResult transformResult = transformPicker.apply(data); switch (transformResult) { - case PASSTHROUGH: - ITree<ContainedType> result = new Tree<>(data); + case PASSTHROUGH: + ITree<ContainedType> result = new Tree<>(data); - if (hasChildren) { - children.forEach((child) -> { - result.addChild(child.topDownTransform(transformPicker, transformer)); - }); - } + if (hasChildren) { + children.forEach((child) -> { + result.addChild(child.topDownTransform(transformPicker, transformer)); + }); + } - return result; - case SKIP: - return this; - case TRANSFORM: - return transformer.apply(this); - case RTRANSFORM: - return transformer.apply(this).topDownTransform(transformPicker, transformer); - case PUSHDOWN: - result = new Tree<>(data); - - if (hasChildren) { - children.forEach((child) -> { - result.addChild(child.topDownTransform(transformPicker, transformer)); - }); - } + return result; + case SKIP: + return this; + case TRANSFORM: + return transformer.apply(this); + case RTRANSFORM: + return transformer.apply(this).topDownTransform(transformPicker, transformer); + case PUSHDOWN: + result = new Tree<>(data); + + if (hasChildren) { + children.forEach((child) -> { + result.addChild(child.topDownTransform(transformPicker, transformer)); + }); + } - return transformer.apply(result); - case PULLUP: - ITree<ContainedType> intermediateResult = transformer.apply(this); + return transformer.apply(result); + case PULLUP: + ITree<ContainedType> intermediateResult = transformer.apply(this); - result = new Tree<>(intermediateResult.getHead()); + result = new Tree<>(intermediateResult.getHead()); - intermediateResult.doForChildren((child) -> { - result.addChild(child.topDownTransform(transformPicker, transformer)); - }); + intermediateResult.doForChildren((child) -> { + result.addChild(child.topDownTransform(transformPicker, transformer)); + }); - return result; - default: - throw new IllegalArgumentException("Recieved unknown transform result " + transformResult); + return result; + default: + throw new IllegalArgumentException("Recieved unknown transform result " + transformResult); } } @@ -247,8 +242,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <TransformedType> TransformedType transformChild( - int childNo, Function<ITree<ContainedType>, TransformedType> transformer) { + public <TransformedType> TransformedType transformChild(int childNo, + Function<ITree<ContainedType>, TransformedType> transformer) { if (childNo < 0 || childNo > (childCount - 1)) { throw new IllegalArgumentException("Child index #" + childNo + " is invalid"); } @@ -264,7 +259,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public <MappedType> ITree<MappedType> transformTree(Function<ContainedType, MappedType> transformer) { if (hasChildren) { - IList<ITree<MappedType>> transformedChildren = children.map((child) -> child.transformTree(transformer)); + IList<ITree<MappedType>> transformedChildren = children + .map((child) -> child.transformTree(transformer)); return new Tree<>(transformer.apply(data), transformedChildren); } @@ -276,29 +272,30 @@ public class Tree<ContainedType> implements ITree<ContainedType> { public void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action) { if (hasChildren) { switch (linearizationMethod) { - case INORDER: - if (childCount != 2) { - throw new IllegalArgumentException("Can only do in-order traversal for binary trees."); - } + case INORDER: + if (childCount != 2) { + throw new IllegalArgumentException( + "Can only do in-order traversal for binary trees."); + } - children.getByIndex(0).traverse(linearizationMethod, action); + children.getByIndex(0).traverse(linearizationMethod, action); - action.accept(data); + action.accept(data); - children.getByIndex(1).traverse(linearizationMethod, action); - break; - case POSTORDER: - children.forEach((child) -> child.traverse(linearizationMethod, action)); + children.getByIndex(1).traverse(linearizationMethod, action); + break; + case POSTORDER: + children.forEach((child) -> child.traverse(linearizationMethod, action)); - action.accept(data); - break; - case PREORDER: - action.accept(data); + action.accept(data); + break; + case PREORDER: + action.accept(data); - children.forEach((child) -> child.traverse(linearizationMethod, action)); - break; - default: - break; + children.forEach((child) -> child.traverse(linearizationMethod, action)); + break; + default: + break; } } else { @@ -307,24 +304,31 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } public boolean equals(Object other) { - if(!(other instanceof Tree<?>)) return false; + if (!(other instanceof Tree<?>)) + return false; @SuppressWarnings("unchecked") Tree<ContainedType> otr = (Tree<ContainedType>) other; - if(!otr.data.equals(data)) return false; + if (!otr.data.equals(data)) + return false; - if(children == null && otr.children == null) return true; + if (children == null && otr.children == null) + return true; - if(children == null && otr.children != null) return false; - if(children != null && otr.children == null) return false; + if (children == null && otr.children != null) + return false; + if (children != null && otr.children == null) + return false; - if(children.getSize() != otr.children.getSize()) return false; + if (children.getSize() != otr.children.getSize()) + return false; int childNo = 0; - for(ITree<ContainedType> child : children) { - if(!otr.children.getByIndex(childNo).equals(child)) return false; + for (ITree<ContainedType> child : children) { + if (!otr.children.getByIndex(childNo).equals(child)) + return false; childNo += 1; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java index beb2465..57bf006 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazy.java @@ -12,45 +12,42 @@ import bjc.utils.funcdata.IList; /** * Implements a lazy holder that has been bound */ -public class BoundLazy<OldType, BoundContainedType> - implements IHolder<BoundContainedType> { +public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundContainedType> { /* * The old value */ - private Supplier<IHolder<OldType>> oldSupplier; + private Supplier<IHolder<OldType>> oldSupplier; /* * The function to use to transform the old value into a new value */ - private Function<OldType, IHolder<BoundContainedType>> binder; + private Function<OldType, IHolder<BoundContainedType>> binder; /* * The bound value being held */ - private IHolder<BoundContainedType> boundHolder; + private IHolder<BoundContainedType> boundHolder; /* * Whether the bound value has been actualized or not */ - private boolean holderBound; + private boolean holderBound; /* * Transformations currently pending on the bound value */ - private IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); + private IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); /* * Create a new bound lazy value */ - public BoundLazy(Supplier<IHolder<OldType>> supp, - Function<OldType, IHolder<BoundContainedType>> binder) { + public BoundLazy(Supplier<IHolder<OldType>> supp, Function<OldType, IHolder<BoundContainedType>> binder) { oldSupplier = supp; this.binder = binder; } @Override - public <BoundType> IHolder<BoundType> bind( - Function<BoundContainedType, IHolder<BoundType>> bindr) { + public <BoundType> IHolder<BoundType> bind(Function<BoundContainedType, IHolder<BoundType>> bindr) { if (bindr == null) { throw new NullPointerException("Binder must not be null"); } @@ -89,8 +86,7 @@ public class BoundLazy<OldType, BoundContainedType> public <NewType> Function<BoundContainedType, IHolder<NewType>> lift( Function<BoundContainedType, NewType> func) { if (func == null) { - throw new NullPointerException( - "Function to lift must not be null"); + throw new NullPointerException("Function to lift must not be null"); } return (val) -> { @@ -99,8 +95,7 @@ public class BoundLazy<OldType, BoundContainedType> } @Override - public <MappedType> IHolder<MappedType> map( - Function<BoundContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(Function<BoundContainedType, MappedType> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } @@ -118,10 +113,9 @@ public class BoundLazy<OldType, BoundContainedType> oldHolder = oldSupplier.get().unwrap(binder); } - return pendingActions.reduceAux(oldHolder.getValue(), - (action, state) -> { - return action.apply(state); - }, (value) -> mapper.apply(value)); + return pendingActions.reduceAux(oldHolder.getValue(), (action, state) -> { + return action.apply(state); + }, (value) -> mapper.apply(value)); }; return new Lazy<>(typeSupplier); @@ -137,8 +131,7 @@ public class BoundLazy<OldType, BoundContainedType> } @Override - public IHolder<BoundContainedType> transform( - UnaryOperator<BoundContainedType> transformer) { + public IHolder<BoundContainedType> transform(UnaryOperator<BoundContainedType> transformer) { if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -149,8 +142,7 @@ public class BoundLazy<OldType, BoundContainedType> } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<BoundContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<BoundContainedType, UnwrappedType> unwrapper) { if (unwrapper == null) { throw new NullPointerException("Unwrapper must not be null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java index 977fb37..d425d99 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundLazyPair.java @@ -12,34 +12,32 @@ import bjc.utils.data.LazyPair; /** * Implements a lazy pair that has been bound */ -public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> - implements IPair<NewLeft, NewRight> { +public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPair<NewLeft, NewRight> { /* * The supplier of the left value */ - private Supplier<OldLeft> leftSupplier; + private Supplier<OldLeft> leftSupplier; /* * The supplier of the right value */ - private Supplier<OldRight> rightSupplier; + private Supplier<OldRight> rightSupplier; /* * The binder to transform values */ - private BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> binder; + private BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> binder; /* * The bound pair */ - private IPair<NewLeft, NewRight> boundPair; + private IPair<NewLeft, NewRight> boundPair; /* * Whether the pair has been bound yet */ - private boolean pairBound; + private boolean pairBound; - public BoundLazyPair(Supplier<OldLeft> leftSupp, - Supplier<OldRight> rightSupp, + public BoundLazyPair(Supplier<OldLeft> leftSupp, Supplier<OldRight> rightSupp, BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> bindr) { leftSupplier = leftSupp; rightSupplier = rightSupp; @@ -53,14 +51,12 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> throw new NullPointerException("Binder must not be null"); } - IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>( - boundPair); + IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); IHolder<Boolean> newPairMade = new Identity<>(pairBound); Supplier<NewLeft> leftSupp = () -> { if (!newPairMade.getValue()) { - newPair.replace(binder.apply(leftSupplier.get(), - rightSupplier.get())); + newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); } @@ -70,8 +66,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> Supplier<NewRight> rightSupp = () -> { if (!newPairMade.getValue()) { - newPair.replace(binder.apply(leftSupplier.get(), - rightSupplier.get())); + newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); } @@ -93,8 +88,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> IPair<NewLeft, NewRight> newPair = boundPair; if (!pairBound) { - newPair = binder.apply(leftSupplier.get(), - rightSupplier.get()); + newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } return newPair.getLeft(); @@ -107,16 +101,14 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> public <BoundRight> IPair<NewLeft, BoundRight> bindRight( Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { if (rightBinder == null) { - throw new NullPointerException( - "Right binder must not be null"); + throw new NullPointerException("Right binder must not be null"); } Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; if (!pairBound) { - newPair = binder.apply(leftSupplier.get(), - rightSupplier.get()); + newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } return newPair.getRight(); @@ -133,34 +125,28 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> if (otherPair == null) { throw new NullPointerException("Other pair must not be null"); } else if (leftCombiner == null) { - throw new NullPointerException( - "Left combiner must not be null"); + throw new NullPointerException("Left combiner must not be null"); } else if (rightCombiner == null) { - throw new NullPointerException( - "Right combiner must not be null"); + throw new NullPointerException("Right combiner must not be null"); } return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - return new LazyPair<>( - leftCombiner.apply(leftVal, otherLeft), + return new LazyPair<>(leftCombiner.apply(leftVal, otherLeft), rightCombiner.apply(rightVal, otherRight)); }); }); } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft( - Function<NewLeft, NewLeftType> mapper) { + public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(Function<NewLeft, NewLeftType> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } Supplier<NewLeftType> leftSupp = () -> { if (!pairBound) { - NewLeft leftVal = binder - .apply(leftSupplier.get(), rightSupplier.get()) - .getLeft(); + NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return mapper.apply(leftVal); } @@ -170,9 +156,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> Supplier<NewRight> rightSupp = () -> { if (!pairBound) { - return binder - .apply(leftSupplier.get(), rightSupplier.get()) - .getRight(); + return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); } return boundPair.getRight(); @@ -182,17 +166,14 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight( - Function<NewRight, NewRightType> mapper) { + public <NewRightType> IPair<NewLeft, NewRightType> mapRight(Function<NewRight, NewRightType> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } Supplier<NewLeft> leftSupp = () -> { if (!pairBound) { - return binder - .apply(leftSupplier.get(), rightSupplier.get()) - .getLeft(); + return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); } return boundPair.getLeft(); @@ -200,9 +181,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> Supplier<NewRightType> rightSupp = () -> { if (!pairBound) { - NewRight rightVal = binder - .apply(leftSupplier.get(), rightSupplier.get()) - .getRight(); + NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return mapper.apply(rightVal); } @@ -214,15 +193,13 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> } @Override - public <MergedType> MergedType merge( - BiFunction<NewLeft, NewRight, MergedType> merger) { + public <MergedType> MergedType merge(BiFunction<NewLeft, NewRight, MergedType> merger) { if (merger == null) { throw new NullPointerException("Merger must not be null"); } if (!pairBound) { - boundPair = binder.apply(leftSupplier.get(), - rightSupplier.get()); + boundPair = binder.apply(leftSupplier.get(), rightSupplier.get()); pairBound = true; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java index 7a3eaa8..f363b7e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/BoundListHolder.java @@ -18,26 +18,22 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { if (binder == null) { throw new NullPointerException("Binder must not be null"); } - IList<IHolder<BoundType>> boundHolders = heldHolders - .map((containedHolder) -> { - return containedHolder.bind(binder); - }); + IList<IHolder<BoundType>> boundHolders = heldHolders.map((containedHolder) -> { + return containedHolder.bind(binder); + }); return new BoundListHolder<>(boundHolders); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { if (func == null) { - throw new NullPointerException( - "Function to lift must not be null"); + throw new NullPointerException("Function to lift must not be null"); } return (val) -> { @@ -46,23 +42,20 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } - IList<IHolder<MappedType>> mappedHolders = heldHolders - .map((containedHolder) -> { - return containedHolder.map(mapper); - }); + IList<IHolder<MappedType>> mappedHolders = heldHolders.map((containedHolder) -> { + return containedHolder.map(mapper); + }); return new BoundListHolder<>(mappedHolders); } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -75,8 +68,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { if (unwrapper == null) { throw new NullPointerException("Unwrapper must not be null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java index 1e8d109..a8bdb6a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java @@ -12,17 +12,15 @@ import bjc.utils.data.LazyPair; /* * A lazy pair, with only one side bound */ -public class HalfBoundLazyPair<OldType, NewLeft, NewRight> - implements IPair<NewLeft, NewRight> { - private Supplier<OldType> oldSupplier; +public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewLeft, NewRight> { + private Supplier<OldType> oldSupplier; - private Function<OldType, IPair<NewLeft, NewRight>> binder; + private Function<OldType, IPair<NewLeft, NewRight>> binder; - private IPair<NewLeft, NewRight> boundPair; - private boolean pairBound; + private IPair<NewLeft, NewRight> boundPair; + private boolean pairBound; - public HalfBoundLazyPair(Supplier<OldType> oldSupp, - Function<OldType, IPair<NewLeft, NewRight>> bindr) { + public HalfBoundLazyPair(Supplier<OldType> oldSupp, Function<OldType, IPair<NewLeft, NewRight>> bindr) { oldSupplier = oldSupp; binder = bindr; } @@ -30,8 +28,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { - IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>( - boundPair); + IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); IHolder<Boolean> newPairMade = new Identity<>(pairBound); Supplier<NewLeft> leftSupp = () -> { @@ -94,16 +91,14 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - return new LazyPair<>( - leftCombiner.apply(leftVal, otherLeft), + return new LazyPair<>(leftCombiner.apply(leftVal, otherLeft), rightCombiner.apply(rightVal, otherRight)); }); }); } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft( - Function<NewLeft, NewLeftType> mapper) { + public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(Function<NewLeft, NewLeftType> mapper) { Supplier<NewLeftType> leftSupp = () -> { if (pairBound) { return mapper.apply(boundPair.getLeft()); @@ -126,8 +121,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight( - Function<NewRight, NewRightType> mapper) { + public <NewRightType> IPair<NewLeft, NewRightType> mapRight(Function<NewRight, NewRightType> mapper) { Supplier<NewLeft> leftSupp = () -> { if (pairBound) { return boundPair.getLeft(); @@ -150,8 +144,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> } @Override - public <MergedType> MergedType merge( - BiFunction<NewLeft, NewRight, MergedType> merger) { + public <MergedType> MergedType merge(BiFunction<NewLeft, NewRight, MergedType> merger) { if (!pairBound) { boundPair = binder.apply(oldSupplier.get()); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java index 65c2463..2b03f62 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/internals/WrappedOption.java @@ -17,7 +17,8 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { held = toHold; } - @Override public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { + @Override + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { return containedHolder.bind((containedValue) -> { if (containedValue == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java index 734bbd8..3d02c9c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Directory.java @@ -9,8 +9,10 @@ import bjc.utils.funcdata.IMap; * What's useful about this is that you can hand sub-directories to people and * be able to ensure that they can't write outside of it. * - * @param K The key type of the map. - * @param V The value type of the map. + * @param K + * The key type of the map. + * @param V + * The value type of the map. */ public class Directory<K, V> { private IMap<K, Directory<K, V>> children; @@ -22,7 +24,7 @@ public class Directory<K, V> { */ public Directory() { children = new FunctionalMap<>(); - data = new FunctionalMap<>(); + data = new FunctionalMap<>(); } /** @@ -30,13 +32,15 @@ public class Directory<K, V> { * * Will fail if a sub-directory of that name already exists. * - * @param key The name of the new sub-directory. + * @param key + * The name of the new sub-directory. * * @return The new sub-directory, or null if one by that name already - * exists. + * exists. */ public Directory<K, V> newSubdirectory(K key) { - if(children.containsKey(key)) return null; + if (children.containsKey(key)) + return null; Directory<K, V> kid = new Directory<>(); children.put(key, kid); @@ -46,7 +50,8 @@ public class Directory<K, V> { /** * Check if a given sub-directory exists. * - * @param key The key to look for the sub-directory under. + * @param key + * The key to look for the sub-directory under. * * @return Whether or not a sub-directory of that name exists. */ @@ -57,12 +62,13 @@ public class Directory<K, V> { /** * Retrieves a given sub-directory. * - * @param key The key to retrieve the sub-directory for. + * @param key + * The key to retrieve the sub-directory for. * * @return The sub-directory under that name. * - * @throws IllegalArgumentException If the given sub-directory doesn't - * exist. + * @throws IllegalArgumentException + * If the given sub-directory doesn't exist. */ public Directory<K, V> getSubdirectory(K key) { return children.get(key); @@ -71,8 +77,10 @@ public class Directory<K, V> { /** * Insert a data-item into the directory. * - * @param key The key to insert into. - * @param val The value to insert. + * @param key + * The key to insert into. + * @param val + * The value to insert. * * @return The old value of key, or null if such a value didn't exist. */ @@ -83,7 +91,8 @@ public class Directory<K, V> { /** * Check if the directory contains a data-item under the given key. * - * @param key The key to check for. + * @param key + * The key to check for. * * @return Whether or not there is a data item for the given key. */ @@ -94,12 +103,13 @@ public class Directory<K, V> { /** * Retrive a given data-item from the directory. * - * @param key The key to retrieve data for. + * @param key + * The key to retrieve data for. * * @return The value for the given key. * - * @throws IllegalArgumentException If no value exists for the given - * key. + * @throws IllegalArgumentException + * If no value exists for the given key. */ public V get(K key) { return data.get(key); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java index bc8ac51..85abbdc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/DoubleTape.java @@ -1,22 +1,26 @@ package bjc.utils.esodata; /** - * Double-sided tape is essentially two tapes stuck together with a shared cursor. + * Double-sided tape is essentially two tapes stuck together with a shared + * cursor. * - * The main way a double-sided tape differs is that it can be flipped, allowing access to - * another set of data. + * The main way a double-sided tape differs is that it can be flipped, allowing + * access to another set of data. * - * However, there is only one cursor, and the position of the cursor on one side is the inverse - * of the position on the other side. + * However, there is only one cursor, and the position of the cursor on one side + * is the inverse of the position on the other side. * - * When one side is extended, a null will be inserted into the inactive side regardless of the - * auto-extension policy of the tape. The policy will still be respected for the active side. + * When one side is extended, a null will be inserted into the inactive side + * regardless of the auto-extension policy of the tape. The policy will still be + * respected for the active side. * - * All operations that refer to the tape refer to the currently active side of the tape, except for flip. + * All operations that refer to the tape refer to the currently active side of + * the tape, except for flip. * * Flip refers to the entire tape for 'obvious' reasons. * - * @param T The element type of the tape. + * @param T + * The element type of the tape. * @author bjculkin */ public class DoubleTape<T> implements Tape<T> { @@ -31,14 +35,16 @@ public class DoubleTape<T> implements Tape<T> { } /** - * Create a new empty double-sided tape that follows the specified auto-extension policy. + * Create a new empty double-sided tape that follows the specified + * auto-extension policy. * - * @param autoExtnd Whether or not to auto-extend the tape to the right - * w/ nulls. + * @param autoExtnd + * Whether or not to auto-extend the tape to the right w/ + * nulls. */ public DoubleTape(boolean autoExtnd) { front = new SingleTape<>(autoExtnd); - back = new SingleTape<>(autoExtnd); + back = new SingleTape<>(autoExtnd); } /** @@ -53,7 +59,8 @@ public class DoubleTape<T> implements Tape<T> { /** * Set the item the tape is currently on. * - * @param itm The new value for the tape item. + * @param itm + * The new value for the tape item. */ public void item(T itm) { front.item(itm); @@ -71,7 +78,8 @@ public class DoubleTape<T> implements Tape<T> { /** * Insert an element before the current item. * - * @param itm The item to add. + * @param itm + * The item to add. */ public void insertBefore(T itm) { front.insertBefore(itm); @@ -89,8 +97,8 @@ public class DoubleTape<T> implements Tape<T> { /** * Remove the current element. * - * Also moves the cursor back one step if possible to maintain - * relative position, and removes the corresponding item from the non-active side + * Also moves the cursor back one step if possible to maintain relative + * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ @@ -130,23 +138,23 @@ public class DoubleTape<T> implements Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. - * Attempts to move the cursor by amounts that would exceed zero - * don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts + * that would exceed zero don't move the cursor at all. * - * @param amt The amount to attempt to move the cursor left. + * @param amt + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ public boolean left(int amt) { boolean succ = front.left(amt); - if(succ) back.right(amt); + if (succ) + back.right(amt); return succ; } - /** * Move the cursor one space right. * @@ -163,14 +171,16 @@ public class DoubleTape<T> implements Tape<T> { * * Moving the cursor right will auto-extend the tape if that is enabled. * - * @param amt The amount to move the cursor right by. + * @param amt + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ public boolean right(int amt) { boolean succ = front.right(amt); - if(succ) back.left(amt); + if (succ) + back.left(amt); return succ; } @@ -178,7 +188,8 @@ public class DoubleTape<T> implements Tape<T> { /** * Flips the tape. * - * The active side becomes inactive, and the inactive side becomes active. + * The active side becomes inactive, and the inactive side becomes + * active. */ public void flip() { Tape<T> tmp = front; diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java index 00b1555..c1a21b6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/QueueStack.java @@ -6,7 +6,8 @@ import java.util.LinkedList; /** * A FIFO implementation of a stack. * - * @param T The datatype stored in the stack. + * @param T + * The datatype stored in the stack. * @author Ben Culkin */ public class QueueStack<T> extends Stack<T> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java index 5f86ecc..1344754 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SimpleStack.java @@ -6,7 +6,8 @@ import java.util.LinkedList; /** * Simple implementation of a stack. * - * @param T The datatype stored in the stack. + * @param T + * The datatype stored in the stack. * @author Ben Culkin */ public class SimpleStack<T> extends Stack<T> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java index 0e0deb2..a323ba4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SingleTape.java @@ -3,16 +3,19 @@ package bjc.utils.esodata; import java.util.ArrayList; /** - * A tape is a one-dimensional array that can only be accessed in one position at a time. + * A tape is a one-dimensional array that can only be accessed in one position + * at a time. * - * A tape is essentially a 1D array with a cursor attached to it, and you can only - * affect elements at that cursor. The size of the array is theoretically unbounded - * to the right, but in practice bounded by available memory. + * A tape is essentially a 1D array with a cursor attached to it, and you can + * only affect elements at that cursor. The size of the array is theoretically + * unbounded to the right, but in practice bounded by available memory. * - * You can choose whether or not you want the tape to automatically extend itself to the - * right with null elements by specifiying its auto-extension policy. + * You can choose whether or not you want the tape to automatically extend + * itself to the right with null elements by specifiying its auto-extension + * policy. * - * @param T The element type of the tape. + * @param T + * The element type of the tape. * @author bjculkin */ public class SingleTape<T> implements Tape<T> { @@ -29,10 +32,12 @@ public class SingleTape<T> implements Tape<T> { } /** - * Create a new empty tape that follows the specified auto-extension policy. + * Create a new empty tape that follows the specified auto-extension + * policy. * - * @param autoExtnd Whether or not to auto-extend the tape to the right - * w/ nulls. + * @param autoExtnd + * Whether or not to auto-extend the tape to the right w/ + * nulls. */ public SingleTape(boolean autoExtnd) { autoExtend = autoExtnd; @@ -52,7 +57,8 @@ public class SingleTape<T> implements Tape<T> { /** * Set the item the tape is currently on. * - * @param itm The new value for the tape item. + * @param itm + * The new value for the tape item. */ public void item(T itm) { backing.set(pos, itm); @@ -70,7 +76,8 @@ public class SingleTape<T> implements Tape<T> { /** * Insert an element before the current item. * - * @param itm The item to add. + * @param itm + * The item to add. */ public void insertBefore(T itm) { backing.add(pos, itm); @@ -80,21 +87,24 @@ public class SingleTape<T> implements Tape<T> { * Insert an element after the current item. */ public void insertAfter(T itm) { - if(pos == (backing.size() - 1)) backing.add(itm); - else backing.add(pos+1, itm); + if (pos == (backing.size() - 1)) + backing.add(itm); + else + backing.add(pos + 1, itm); } /** * Remove the current element. * - * Also moves the cursor back one step if possible to maintain - * relative position. + * Also moves the cursor back one step if possible to maintain relative + * position. * * @return The removed item. */ public T remove() { T res = backing.remove(pos); - if(pos != 0) pos -= 1; + if (pos != 0) + pos -= 1; return res; } @@ -126,16 +136,17 @@ public class SingleTape<T> implements Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. - * Attempts to move the cursor by amounts that would exceed zero - * don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts + * that would exceed zero don't move the cursor at all. * - * @param amt The amount to attempt to move the cursor left. + * @param amt + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ public boolean left(int amt) { - if((pos - amt) < 0) return false; + if ((pos - amt) < 0) + return false; pos -= amt; return true; @@ -157,14 +168,15 @@ public class SingleTape<T> implements Tape<T> { * * Moving the cursor right will auto-extend the tape if that is enabled. * - * @param amt The amount to move the cursor right by. + * @param amt + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ public boolean right(int amt) { - if((pos + amt) >= (backing.size() - 1)) { - if(autoExtend) { - while((pos + amt) >= (backing.size() - 1)) { + if ((pos + amt) >= (backing.size() - 1)) { + if (autoExtend) { + while ((pos + amt) >= (backing.size() - 1)) { backing.add(null); } } else { diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java index e5b1422..c650cdc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/SpaghettiStack.java @@ -15,7 +15,8 @@ class SpaghettiStack<T> extends Stack<T> { /** * Create a new empty spaghetti stack, off of the specified parent. * - * @param par The parent stack + * @param par + * The parent stack */ public SpaghettiStack(Stack<T> par) { backing = new SimpleStack<>(); @@ -30,7 +31,7 @@ class SpaghettiStack<T> extends Stack<T> { @Override public T pop() { - if(backing.empty()) { + if (backing.empty()) { return parent.pop(); } @@ -39,7 +40,7 @@ class SpaghettiStack<T> extends Stack<T> { @Override public T top() { - if(backing.empty()) { + if (backing.empty()) { return parent.top(); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java index 1fc644e..21a922d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Stack.java @@ -9,14 +9,16 @@ import java.util.function.Consumer; * * A FILO stack with support for forth/factor style combinators. * - * @param T The datatype stored in the stack. + * @param T + * The datatype stored in the stack. * @author Ben Culkin */ public abstract class Stack<T> { /** * Push an element onto the stack. * - * @param elm The element to insert. + * @param elm + * The element to insert. */ public abstract void push(T elm); @@ -36,7 +38,8 @@ public abstract class Stack<T> { */ public abstract int size(); - /** Check if the stack is empty. + /** + * Check if the stack is empty. * * @return Whether or not the stack is empty. */ @@ -54,14 +57,15 @@ public abstract class Stack<T> { /* * Basic combinators */ - + /** * Drop n items from the stack. * - * @param n The number of items to drop. + * @param n + * The number of items to drop. */ public void drop(int n) { - for(int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) { pop(); } } @@ -76,7 +80,8 @@ public abstract class Stack<T> { /** * Delete n items below the current one. * - * @param n The number of items below the top to delete. + * @param n + * The number of items below the top to delete. */ public void nip(int n) { T elm = pop(); @@ -96,18 +101,20 @@ public abstract class Stack<T> { /** * Replicate the top n items of the stack m times. * - * @param n The number of items to duplicate. - * @param m The number of times to duplicate items. + * @param n + * The number of items to duplicate. + * @param m + * The number of times to duplicate items. */ public void multidup(int n, int m) { List<T> lst = new ArrayList<>(n); - for(int i = n; i > 0; i--) { + for (int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - - for(int i = 0; i < m; i++) { - for(T elm : lst) { + + for (int i = 0; i < m; i++) { + for (T elm : lst) { push(elm); } } @@ -116,7 +123,8 @@ public abstract class Stack<T> { /** * Duplicate the top n items of the stack. * - * @param n The number of items to duplicate. + * @param n + * The number of items to duplicate. */ public void dup(int n) { multidup(n, 2); @@ -132,25 +140,27 @@ public abstract class Stack<T> { /** * Replicate the n elements below the top one m times. * - * @param n The number of items to duplicate. - * @param m The number of times to duplicate items. + * @param n + * The number of items to duplicate. + * @param m + * The number of times to duplicate items. */ public void multiover(int n, int m) { List<T> lst = new ArrayList<>(n); T elm = pop(); - for(int i = n; i > 0; i--) { + for (int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for(T nelm : lst) { + for (T nelm : lst) { push(nelm); } push(elm); - for(int i = 1; i < m; i++) { - for(T nelm : lst) { + for (int i = 1; i < m; i++) { + for (T nelm : lst) { push(nelm); } } @@ -159,7 +169,8 @@ public abstract class Stack<T> { /** * Duplicate the n elements below the top one. * - * @param n The number of items to duplicate. + * @param n + * The number of items to duplicate. */ public void over(int n) { multiover(n, 2); @@ -254,19 +265,21 @@ public abstract class Stack<T> { /** * Hides the top n elements on the stack from cons. * - * @param n The number of elements to hide. - * @param cons The action to hide the elements from + * @param n + * The number of elements to hide. + * @param cons + * The action to hide the elements from */ public void dip(int n, Consumer<Stack<T>> cons) { List<T> elms = new ArrayList<>(n); - for(int i = n; i > 0; i--) { + for (int i = n; i > 0; i--) { elms.set(i - 1, pop()); } cons.accept(this); - for(T elm : elms) { + for (T elm : elms) { push(elm); } } @@ -274,7 +287,8 @@ public abstract class Stack<T> { /** * Hide the top element of the stack from cons. * - * @param cons The action to hide the top from + * @param cons + * The action to hide the top from */ public void dip(Consumer<Stack<T>> cons) { dip(1, cons); @@ -284,8 +298,10 @@ public abstract class Stack<T> { * Copy the top n elements on the stack, replacing them once cons is * done. * - * @param n The number of elements to copy. - * @param cons The action to execute. + * @param n + * The number of elements to copy. + * @param cons + * The action to execute. */ public void keep(int n, Consumer<Stack<T>> cons) { dup(n); @@ -295,18 +311,20 @@ public abstract class Stack<T> { /** * Apply all the actions in conses to the top n elements of the stack. * - * @param n The number of elements to give to cons. - * @param conses The actions to execute. + * @param n + * The number of elements to give to cons. + * @param conses + * The actions to execute. */ public void multicleave(int n, List<Consumer<Stack<T>>> conses) { List<T> elms = new ArrayList<>(n); - for(int i = n; i > 0; i--) { + for (int i = n; i > 0; i--) { elms.set(i - 1, pop()); } - for(Consumer<Stack<T>> cons : conses) { - for(T elm : elms) { + for (Consumer<Stack<T>> cons : conses) { + for (T elm : elms) { push(elm); } @@ -317,7 +335,8 @@ public abstract class Stack<T> { /** * Apply all the actions in conses to the top element of the stack. * - * @param conses The actions to execute. + * @param conses + * The actions to execute. */ public void cleave(List<Consumer<Stack<T>>> conses) { multicleave(1, conses); @@ -326,16 +345,18 @@ public abstract class Stack<T> { /** * Apply every action in cons to n arguments. * - * @param n The number of parameters each action takes. - * @param conses The actions to execute. + * @param n + * The number of parameters each action takes. + * @param conses + * The actions to execute. */ public void multispread(int n, List<Consumer<Stack<T>>> conses) { List<List<T>> nelms = new ArrayList<>(conses.size()); - for(int i = conses.size(); i > 0; i--) { + for (int i = conses.size(); i > 0; i--) { List<T> elms = new ArrayList<>(n); - for(int j = n; j > 0; j--) { + for (int j = n; j > 0; j--) { elms.set(j, pop()); } @@ -343,8 +364,8 @@ public abstract class Stack<T> { } int i = 0; - for(List<T> elms : nelms) { - for(T elm : elms) { + for (List<T> elms : nelms) { + for (T elm : elms) { push(elm); } @@ -365,14 +386,17 @@ public abstract class Stack<T> { /** * Apply the action in cons to the first m groups of n arguments. * - * @param n The number of arguments cons takes. - * @param m The number of time to call cons. - * @param cons The action to execute. + * @param n + * The number of arguments cons takes. + * @param m + * The number of time to call cons. + * @param cons + * The action to execute. */ public void multiapply(int n, int m, Consumer<Stack<T>> cons) { List<Consumer<Stack<T>>> conses = new ArrayList<>(m); - for(int i = 0; i < m; i++) { + for (int i = 0; i < m; i++) { conses.add(cons); } @@ -382,8 +406,10 @@ public abstract class Stack<T> { /** * Apply cons n times to the corresponding elements in the stack. * - * @param n The number of times to execute cons. - * @param cons The action to execute. + * @param n + * The number of times to execute cons. + * @param cons + * The action to execute. */ public void apply(int n, Consumer<Stack<T>> cons) { multiapply(1, n, cons); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java index 425feb0..3d4e0b1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/Tape.java @@ -3,11 +3,12 @@ package bjc.utils.esodata; /** * Interface for something that acts like a tape. * - * A tape is essentially a 1D array with a cursor attached to it, and you can only - * affect elements at that cursor. The size of the array is theoretically unbounded - * to the right, but in practice bounded by available memory. + * A tape is essentially a 1D array with a cursor attached to it, and you can + * only affect elements at that cursor. The size of the array is theoretically + * unbounded to the right, but in practice bounded by available memory. * - * @param T The element type of the tape. + * @param T + * The element type of the tape. * @author bjculkin */ public interface Tape<T> { @@ -21,7 +22,8 @@ public interface Tape<T> { /** * Set the item the tape is currently on. * - * @param itm The new value for the tape item. + * @param itm + * The new value for the tape item. */ void item(T itm); @@ -35,7 +37,8 @@ public interface Tape<T> { /** * Insert an element before the current item. * - * @param itm The item to add. + * @param itm + * The item to add. */ void insertBefore(T itm); @@ -47,8 +50,8 @@ public interface Tape<T> { /** * Remove the current element. * - * Also moves the cursor back one step if possible to maintain - * relative position. + * Also moves the cursor back one step if possible to maintain relative + * position. * * @return The removed item. */ @@ -76,11 +79,11 @@ public interface Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. - * Attempts to move the cursor by amounts that would exceed zero - * don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts + * that would exceed zero don't move the cursor at all. * - * @param amt The amount to attempt to move the cursor left. + * @param amt + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ @@ -96,7 +99,8 @@ public interface Tape<T> { /** * Move the cursor the specified amount right. * - * @param amt The amount to move the cursor right by. + * @param amt + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java index 790e3fd..4030960 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeChanger.java @@ -3,15 +3,18 @@ package bjc.utils.esodata; /** * A tape changer is essentially a tape of tapes. * - * It has a current tape that you can do operations to, but also operations to add/remove other tapes. + * It has a current tape that you can do operations to, but also operations to + * add/remove other tapes. * - * If there is no tape currently loaded into the changer, all the methods will either return null/false. + * If there is no tape currently loaded into the changer, all the methods will + * either return null/false. * - * @param T The element type of the tapes. + * @param T + * The element type of the tapes. */ public class TapeChanger<T> implements Tape<T> { private Tape<Tape<T>> tapes; - private Tape<T> currentTape; + private Tape<T> currentTape; /** * Create a new empty tape changer. @@ -25,7 +28,8 @@ public class TapeChanger<T> implements Tape<T> { * * The first tape in the list will be mounted. * - * @param taps The tapes to put in this tape changer. + * @param taps + * The tapes to put in this tape changer. */ @SafeVarargs public TapeChanger(Tape<T> current, Tape<T>... others) { @@ -33,7 +37,7 @@ public class TapeChanger<T> implements Tape<T> { tapes.insertBefore(current); - for(Tape<T> tp : others) { + for (Tape<T> tp : others) { tapes.insertAfter(tp); tapes.right(); } @@ -48,7 +52,8 @@ public class TapeChanger<T> implements Tape<T> { * @return The item the tape is on. */ public T item() { - if(currentTape == null) return null; + if (currentTape == null) + return null; return currentTape.item(); } @@ -56,10 +61,12 @@ public class TapeChanger<T> implements Tape<T> { /** * Set the item the tape is currently on. * - * @param itm The new value for the tape item. + * @param itm + * The new value for the tape item. */ public void item(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.item(itm); } @@ -70,7 +77,8 @@ public class TapeChanger<T> implements Tape<T> { * @return The current number of elements in the tape. */ public int size() { - if(currentTape == null) return 0; + if (currentTape == null) + return 0; return currentTape.size(); } @@ -78,10 +86,12 @@ public class TapeChanger<T> implements Tape<T> { /** * Insert an element before the current item. * - * @param itm The item to add. + * @param itm + * The item to add. */ public void insertBefore(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.insertBefore(itm); } @@ -90,7 +100,8 @@ public class TapeChanger<T> implements Tape<T> { * Insert an element after the current item. */ public void insertAfter(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.insertAfter(itm); } @@ -98,13 +109,14 @@ public class TapeChanger<T> implements Tape<T> { /** * Remove the current element. * - * Also moves the cursor back one step if possible to maintain - * relative position, and removes the corresponding item from the non-active side + * Also moves the cursor back one step if possible to maintain relative + * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ public T remove() { - if(currentTape == null) return null; + if (currentTape == null) + return null; return currentTape.remove(); } @@ -113,7 +125,8 @@ public class TapeChanger<T> implements Tape<T> { * Move the cursor to the left-most position. */ public void first() { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.first(); } @@ -122,7 +135,8 @@ public class TapeChanger<T> implements Tape<T> { * Move the cursor the right-most position. */ public void last() { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.last(); } @@ -141,21 +155,21 @@ public class TapeChanger<T> implements Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. - * Attempts to move the cursor by amounts that would exceed zero - * don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts + * that would exceed zero don't move the cursor at all. * - * @param amt The amount to attempt to move the cursor left. + * @param amt + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ public boolean left(int amt) { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.left(amt); } - /** * Move the cursor one space right. * @@ -172,12 +186,14 @@ public class TapeChanger<T> implements Tape<T> { * * Moving the cursor right will auto-extend the tape if that is enabled. * - * @param amt The amount to move the cursor right by. + * @param amt + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ public boolean right(int amt) { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.right(amt); } @@ -185,21 +201,24 @@ public class TapeChanger<T> implements Tape<T> { /** * Flips the tape. * - * The active side becomes inactive, and the inactive side becomes active. + * The active side becomes inactive, and the inactive side becomes + * active. * * If the current tape is not double-sided, does nothing. */ public void flip() { - if(currentTape == null) return; + if (currentTape == null) + return; - if(currentTape.isDoubleSided()) { - ((DoubleTape<T>)currentTape).flip(); + if (currentTape.isDoubleSided()) { + ((DoubleTape<T>) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.isDoubleSided(); } @@ -216,14 +235,16 @@ public class TapeChanger<T> implements Tape<T> { /** * Move to the next tape in the changer. * - * Attempting to load a tape that isn't there won't eject the current tape. + * Attempting to load a tape that isn't there won't eject the current + * tape. * * @return Whether or not the next tape was loaded. */ public boolean nextTape() { boolean succ = tapes.right(); - if(succ) currentTape = tapes.item(); + if (succ) + currentTape = tapes.item(); return succ; } @@ -231,14 +252,16 @@ public class TapeChanger<T> implements Tape<T> { /** * Move to the previous tape in the changer. * - * Attempting to load a tape that isn't there won't eject the current tape. + * Attempting to load a tape that isn't there won't eject the current + * tape. * * @return Whether or not the previous tape was loaded. */ public boolean prevTape() { boolean succ = tapes.left(); - if(succ) currentTape = tapes.item(); + if (succ) + currentTape = tapes.item(); return succ; } @@ -250,12 +273,13 @@ public class TapeChanger<T> implements Tape<T> { * * The specified tape is loaded. * - * @param The tape to insert and load. + * @param The + * tape to insert and load. */ public void insertTape(Tape<T> tp) { tapes.insertAfter(tp); tapes.right(); - + currentTape = tapes.item(); } @@ -269,7 +293,8 @@ public class TapeChanger<T> implements Tape<T> { * @return The removed tape. */ public Tape<T> removeTape() { - if(currentTape == null) return null; + if (currentTape == null) + return null; Tape<T> tp = tapes.remove(); currentTape = tapes.item(); diff --git a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java index 711c15e..3a49175 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java +++ b/BJC-Utils2/src/main/java/bjc/utils/esodata/TapeLibrary.java @@ -6,15 +6,18 @@ import java.util.Map; /** * A tape changer is essentially a map of tapes. * - * It has a current tape that you can do operations to, but also operations to add/remove other tapes. + * It has a current tape that you can do operations to, but also operations to + * add/remove other tapes. * - * If there is no tape currently loaded into the changer, all the methods will either return null/false. + * If there is no tape currently loaded into the changer, all the methods will + * either return null/false. * - * @param T The element type of the tapes. + * @param T + * The element type of the tapes. */ public class TapeLibrary<T> implements Tape<T> { private Map<String, Tape<T>> tapes; - private Tape<T> currentTape; + private Tape<T> currentTape; /** * Create a new empty tape library. @@ -29,7 +32,8 @@ public class TapeLibrary<T> implements Tape<T> { * @return The item the tape is on. */ public T item() { - if(currentTape == null) return null; + if (currentTape == null) + return null; return currentTape.item(); } @@ -37,10 +41,12 @@ public class TapeLibrary<T> implements Tape<T> { /** * Set the item the tape is currently on. * - * @param itm The new value for the tape item. + * @param itm + * The new value for the tape item. */ public void item(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.item(itm); } @@ -51,7 +57,8 @@ public class TapeLibrary<T> implements Tape<T> { * @return The current number of elements in the tape. */ public int size() { - if(currentTape == null) return 0; + if (currentTape == null) + return 0; return currentTape.size(); } @@ -59,10 +66,12 @@ public class TapeLibrary<T> implements Tape<T> { /** * Insert an element before the current item. * - * @param itm The item to add. + * @param itm + * The item to add. */ public void insertBefore(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.insertBefore(itm); } @@ -71,7 +80,8 @@ public class TapeLibrary<T> implements Tape<T> { * Insert an element after the current item. */ public void insertAfter(T itm) { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.insertAfter(itm); } @@ -79,13 +89,14 @@ public class TapeLibrary<T> implements Tape<T> { /** * Remove the current element. * - * Also moves the cursor back one step if possible to maintain - * relative position, and removes the corresponding item from the non-active side + * Also moves the cursor back one step if possible to maintain relative + * position, and removes the corresponding item from the non-active side * * @return The removed item from the active side. */ public T remove() { - if(currentTape == null) return null; + if (currentTape == null) + return null; return currentTape.remove(); } @@ -94,7 +105,8 @@ public class TapeLibrary<T> implements Tape<T> { * Move the cursor to the left-most position. */ public void first() { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.first(); } @@ -103,7 +115,8 @@ public class TapeLibrary<T> implements Tape<T> { * Move the cursor the right-most position. */ public void last() { - if(currentTape == null) return; + if (currentTape == null) + return; currentTape.last(); } @@ -122,21 +135,21 @@ public class TapeLibrary<T> implements Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. - * Attempts to move the cursor by amounts that would exceed zero - * don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts + * that would exceed zero don't move the cursor at all. * - * @param amt The amount to attempt to move the cursor left. + * @param amt + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ public boolean left(int amt) { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.left(amt); } - /** * Move the cursor one space right. * @@ -153,12 +166,14 @@ public class TapeLibrary<T> implements Tape<T> { * * Moving the cursor right will auto-extend the tape if that is enabled. * - * @param amt The amount to move the cursor right by. + * @param amt + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ public boolean right(int amt) { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.right(amt); } @@ -166,21 +181,24 @@ public class TapeLibrary<T> implements Tape<T> { /** * Flips the tape. * - * The active side becomes inactive, and the inactive side becomes active. + * The active side becomes inactive, and the inactive side becomes + * active. * * If the current tape is not double-sided, does nothing. */ public void flip() { - if(currentTape == null) return; + if (currentTape == null) + return; - if(currentTape.isDoubleSided()) { - ((DoubleTape<T>)currentTape).flip(); + if (currentTape.isDoubleSided()) { + ((DoubleTape<T>) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if(currentTape == null) return false; + if (currentTape == null) + return false; return currentTape.isDoubleSided(); } @@ -197,14 +215,16 @@ public class TapeLibrary<T> implements Tape<T> { /** * Move to the specified tape in the library. * - * Attempting to load a tape that isn't there won't eject the current tape. + * Attempting to load a tape that isn't there won't eject the current + * tape. * - * @param label The label of the tape to load. + * @param label + * The label of the tape to load. * * @return Whether or not the next tape was loaded. */ public boolean switchTape(String label) { - if(tapes.containsKey(label)) { + if (tapes.containsKey(label)) { currentTape = tapes.get(label); return true; } @@ -221,7 +241,8 @@ public class TapeLibrary<T> implements Tape<T> { * * Adding a duplicate tape will overwrite any existing types. * - * @param The tape to insert and load. + * @param The + * tape to insert and load. */ public void insertTape(String label, Tape<T> tp) { tapes.put(label, tp); @@ -234,7 +255,8 @@ public class TapeLibrary<T> implements Tape<T> { * * Does nothing if there is not a tape of that name loaded. * - * @param label The tape to remove. + * @param label + * The tape to remove. * * @return The removed tape. */ @@ -263,7 +285,8 @@ public class TapeLibrary<T> implements Tape<T> { /** * Check if a specific tape is loaded into the library. * - * @param label The tape to check for. + * @param label + * The tape to check for. * * @return Whether or not a tape of that name exists */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java index 1fb3dc4..d70b5bd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java @@ -23,7 +23,7 @@ public class FileNotChosenException extends IOException { * Create a new exception with the given cause * * @param cause - * The cause of why the exception was thrown + * The cause of why the exception was thrown */ public FileNotChosenException(String cause) { super(cause); diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java index 41938a5..f6ad517 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java @@ -23,7 +23,7 @@ public class PragmaFormatException extends InputMismatchException { * Create a new exception with the given message * * @param message - * The message to explain why the exception was thrown + * The message to explain why the exception was thrown */ public PragmaFormatException(String message) { super(message); diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java index 6e2ef15..7164bea 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java @@ -16,7 +16,7 @@ public class UnknownPragmaException extends InputMismatchException { * Create a new exception with the given cause * * @param cause - * The cause for throwing this exception + * The cause for throwing this exception */ public UnknownPragmaException(String cause) { super(cause); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java index 0a2ee39..7e6c23b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java @@ -7,12 +7,11 @@ import java.util.function.Function; import bjc.utils.funcutils.ListUtils; class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { - private IMap<KeyType, ValueType> delegate; + private IMap<KeyType, ValueType> delegate; - private IMap<KeyType, ValueType> store; + private IMap<KeyType, ValueType> store; - public ExtendedMap(IMap<KeyType, ValueType> delegate, - IMap<KeyType, ValueType> store) { + public ExtendedMap(IMap<KeyType, ValueType> delegate, IMap<KeyType, ValueType> store) { this.delegate = delegate; this.store = store; } @@ -77,8 +76,7 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { } @Override - public <MappedValue> IMap<KeyType, MappedValue> mapValues( - Function<ValueType, MappedValue> transformer) { + public <MappedValue> IMap<KeyType, MappedValue> mapValues(Function<ValueType, MappedValue> transformer) { return new TransformedValueMap<>(this, transformer); } @@ -94,7 +92,6 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public IList<ValueType> valueList() { - return ListUtils.mergeLists(store.valueList(), - delegate.valueList()); + return ListUtils.mergeLists(store.valueList(), delegate.valueList()); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java index 3f61303..f98f32c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -18,16 +18,16 @@ import bjc.utils.data.Identity; import bjc.utils.data.Pair; /** - * A wrapper over another list that provides eager functional operations - * over it. + * A wrapper over another list that provides eager functional operations over + * it. * - * Differs from a stream in every way except for the fact that - * they both provide functional operations. + * Differs from a stream in every way except for the fact that they both provide + * functional operations. * * @author ben * * @param <E> - * The type in this list + * The type in this list */ public class FunctionalList<E> implements Cloneable, IList<E> { /* @@ -48,7 +48,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(n) time, where n is the number of items specified * * @param items - * The items to put into this functional list. + * The items to put into this functional list. */ @SafeVarargs public FunctionalList(E... items) { @@ -63,7 +63,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Create a new functional list with the specified size. * * @param size - * The size of the backing list . + * The size of the backing list . */ private FunctionalList(int size) { wrapped = new ArrayList<>(size); @@ -75,12 +75,11 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(1) time, since it doesn't copy the list. * * @param backing - * The list to use as a backing list. + * The list to use as a backing list. */ public FunctionalList(List<E> backing) { if (backing == null) { - throw new NullPointerException( - "Backing list must be non-null"); + throw new NullPointerException("Backing list must be non-null"); } wrapped = backing; @@ -144,10 +143,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T, F> IList<F> combineWith(IList<T> rightList, - BiFunction<E, T, F> itemCombiner) { + public <T, F> IList<F> combineWith(IList<T> rightList, BiFunction<E, T, F> itemCombiner) { if (rightList == null) { - throw new NullPointerException( "Target combine list must not be null"); + throw new NullPointerException("Target combine list must not be null"); } else if (itemCombiner == null) { throw new NullPointerException("Combiner must not be null"); } @@ -157,8 +155,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { // Get the iterator for the other list Iterator<T> rightIterator = rightList.toIterable().iterator(); - for (Iterator<E> leftIterator = wrapped.iterator(); - leftIterator.hasNext() && rightIterator.hasNext();) { + for (Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() + && rightIterator.hasNext();) { // Add the transformed items to the result list E leftVal = leftIterator.next(); T rightVal = rightIterator.next(); @@ -220,7 +218,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { throw new NullPointerException("Action must not be null"); } - // This is held b/c ref'd variables must be final/effectively final + // This is held b/c ref'd variables must be final/effectively + // final IHolder<Integer> currentIndex = new Identity<>(0); wrapped.forEach((element) -> { @@ -256,7 +255,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { wrapped.forEach((element) -> { if (predicate.test(element)) { - // The item matches, so add it to the returned list + // The item matches, so add it to the returned + // list returned.add(element); } }); @@ -277,8 +277,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* * Check if a partition has room for another item */ - private Boolean isPartitionFull(int numberPerPartition, - IHolder<IList<E>> currentPartition) { + private Boolean isPartitionFull(int numberPerPartition, IHolder<IList<E>> currentPartition) { return currentPartition.unwrap((partition) -> partition.getSize() >= numberPerPartition); } @@ -305,18 +304,15 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public IList<IList<E>> partition(int numberPerPartition) { - if (numberPerPartition < 1 - || numberPerPartition > wrapped.size()) { + if (numberPerPartition < 1 || numberPerPartition > wrapped.size()) { throw new IllegalArgumentException("" + numberPerPartition - + " is an invalid partition size. Must be between 1 and " - + wrapped.size()); + + " is an invalid partition size. Must be between 1 and " + wrapped.size()); } IList<IList<E>> returned = new FunctionalList<>(); // The current partition being filled - IHolder<IList<E>> currentPartition = new Identity<>( - new FunctionalList<>()); + IHolder<IList<E>> currentPartition = new Identity<>(new FunctionalList<>()); this.forEach((element) -> { if (isPartitionFull(numberPerPartition, currentPartition)) { @@ -351,8 +347,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T, F> F reduceAux(T initialValue, - BiFunction<E, T, T> stateAccumulator, + public <T, F> F reduceAux(T initialValue, BiFunction<E, T, T> stateAccumulator, Function<T, F> resultTransformer) { if (stateAccumulator == null) { throw new NullPointerException("Accumulator must not be null"); @@ -394,8 +389,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E search(E searchKey, Comparator<E> comparator) { // Search our internal list - int foundIndex = Collections.binarySearch(wrapped, searchKey, - comparator); + int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); if (foundIndex >= 0) { // We found a matching element @@ -431,21 +425,22 @@ public class FunctionalList<E> implements Cloneable, IList<E> { public String toString() { int lSize = getSize(); - if(lSize == 0) return "()"; + if (lSize == 0) + return "()"; StringBuilder sb = new StringBuilder("("); Iterator<E> itr = toIterable().iterator(); E itm = itr.next(); int i = 0; - if(lSize == 1) { + if (lSize == 1) { return "(" + itm + ")"; } - for(E item : toIterable()) { + for (E item : toIterable()) { sb.append(item.toString()); - if(i < lSize-1) { + if (i < lSize - 1) { sb.append(", "); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java index cc70ae1..3d3fed1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java @@ -14,9 +14,9 @@ import bjc.utils.data.IPair; * @author ben * * @param <KeyType> - * The type of the map's keys + * The type of the map's keys * @param <ValueType> - * The type of the map's values + * The type of the map's values */ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { private Map<KeyType, ValueType> wrappedMap; @@ -32,7 +32,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map with the specified entries * * @param entries - * The entries to put into the map + * The entries to put into the map */ @SafeVarargs public FunctionalMap(IPair<KeyType, ValueType>... entries) { @@ -49,7 +49,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map wrapping the specified map * * @param wrap - * The map to wrap + * The map to wrap */ public FunctionalMap(Map<KeyType, ValueType> wrap) { if (wrap == null) { @@ -119,8 +119,7 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp } @Override - public <MappedValue> IMap<KeyType, MappedValue> mapValues( - Function<ValueType, MappedValue> transformer) { + public <MappedValue> IMap<KeyType, MappedValue> mapValues(Function<ValueType, MappedValue> transformer) { if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java index 078bba6..93f2dca 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -15,13 +15,12 @@ public class FunctionalStringTokenizer { * Create a new tokenizer from the specified string. * * @param strang - * The string to create a tokenizer from. + * The string to create a tokenizer from. * @return A new tokenizer that splits the provided string on spaces. */ public static FunctionalStringTokenizer fromString(String strang) { if (strang == null) { - throw new NullPointerException( - "String to tokenize must be non-null"); + throw new NullPointerException("String to tokenize must be non-null"); } return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); @@ -36,7 +35,7 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a given string * * @param inp - * The string to tokenize + * The string to tokenize */ public FunctionalStringTokenizer(String inp) { if (inp == null) { @@ -51,12 +50,11 @@ public class FunctionalStringTokenizer { * separators * * @param input - * The string to tokenize + * The string to tokenize * @param seperators - * The set of separating tokens to use for splitting + * The set of separating tokens to use for splitting */ - public FunctionalStringTokenizer(String input, - String seperators) { + public FunctionalStringTokenizer(String input, String seperators) { if (input == null) { throw new NullPointerException("String to tokenize must not be null"); } else if (seperators == null) { @@ -70,7 +68,7 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a non-functional one * * @param toWrap - * The non-functional string tokenizer to wrap + * The non-functional string tokenizer to wrap */ public FunctionalStringTokenizer(StringTokenizer toWrap) { if (toWrap == null) { @@ -84,7 +82,7 @@ public class FunctionalStringTokenizer { * Execute a provided action for each of the remaining tokens * * @param action - * The action to execute for each token + * The action to execute for each token */ public void forEachToken(Consumer<String> action) { if (action == null) { @@ -145,10 +143,10 @@ public class FunctionalStringTokenizer { * the input from this tokenizer. * * @param <E> - * The type of the converted tokens + * The type of the converted tokens * * @param transformer - * The function to use to convert tokens. + * The function to use to convert tokens. * @return A list containing all of the converted tokens. */ public <E> IList<E> toList(Function<String, E> transformer) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java index f6b207a..0feaf06 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java @@ -17,14 +17,14 @@ import bjc.utils.data.IPair; * @author ben * * @param <ContainedType> - * The type in this list + * The type in this list */ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Add an item to this list * * @param item - * The item to add to this list. + * The item to add to this list. * @return Whether the item was added to the list successfully. */ boolean add(ContainedType item); @@ -33,7 +33,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Add all of the elements in the provided list to this list * * @param items - * The list of items to add + * The list of items to add * @return True if every item was successfully added to the list, false * otherwise */ @@ -46,7 +46,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * predicate. * * @param matcher - * The predicate to use for checking. + * The predicate to use for checking. * @return Whether all of the elements of the list match the specified * predicate. */ @@ -56,7 +56,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Check if any of the elements in this list match the specified list. * * @param matcher - * The predicate to use for checking. + * The predicate to use for checking. * @return Whether any element in the list matches the provided * predicate. */ @@ -66,11 +66,11 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce the contents of this list using a collector * * @param <StateType> - * The intermediate accumulation type + * The intermediate accumulation type * @param <ReducedType> - * The final, reduced type + * The final, reduced type * @param collector - * The collector to use for reduction + * The collector to use for reduction * @return The reduced list */ default <StateType, ReducedType> ReducedType collect( @@ -88,32 +88,31 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Combine this list with another one into a new list and merge the * results. * - * Works sort of like a combined zip/map over resulting pairs. - * Does not change the underlying list. + * Works sort of like a combined zip/map over resulting pairs. Does not + * change the underlying list. * * NOTE: The returned list will have the length of the shorter of this * list and the combined one. * * @param <OtherType> - * The type of the second list + * The type of the second list * @param <CombinedType> - * The type of the combined list + * The type of the combined list * * @param list - * The list to combine with + * The list to combine with * @param combiner - * The function to use for combining element pairs. + * The function to use for combining element pairs. * @return A new list containing the merged pairs of lists. */ - <OtherType, CombinedType> IList<CombinedType> combineWith( - IList<OtherType> list, + <OtherType, CombinedType> IList<CombinedType> combineWith(IList<OtherType> list, BiFunction<ContainedType, OtherType, CombinedType> combiner); /** * Check if the list contains the specified item * * @param item - * The item to see if it is contained + * The item to see if it is contained * @return Whether or not the specified item is in the list */ boolean contains(ContainedType item); @@ -132,21 +131,20 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Does not change the underlying list. * * @param <MappedType> - * The type of the flattened list + * The type of the flattened list * * @param expander - * The function to apply to each member of the list. + * The function to apply to each member of the list. * @return A new list containing the flattened results of applying the * provided function. */ - <MappedType> IList<MappedType> flatMap( - Function<ContainedType, IList<MappedType>> expander); + <MappedType> IList<MappedType> flatMap(Function<ContainedType, IList<MappedType>> expander); /** * Apply a given action for each member of the list * * @param action - * The action to apply to each member of the list. + * The action to apply to each member of the list. */ void forEach(Consumer<? super ContainedType> action); @@ -154,8 +152,8 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Apply a given function to each element in the list and its index. * * @param action - * The function to apply to each element in the list and its - * index. + * The function to apply to each element in the list and + * its index. */ void forEachIndexed(BiConsumer<Integer, ContainedType> action); @@ -163,7 +161,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a value in the list by its index. * * @param index - * The index to retrieve a value from. + * The index to retrieve a value from. * @return The value at the specified index in the list. */ ContainedType getByIndex(int index); @@ -172,7 +170,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a list containing all elements matching a predicate * * @param predicate - * The predicate to match by + * The predicate to match by * @return A list containing all elements that match the predicate */ IList<ContainedType> getMatching(Predicate<ContainedType> predicate); @@ -193,28 +191,27 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Create a new list by applying the given function to each element in - * the list. + * the list. * * Does not change the underlying list. * * @param <MappedType> - * The type of the transformed list + * The type of the transformed list * * @param transformer - * The function to apply to each element in the list + * The function to apply to each element in the list * @return A new list containing the mapped elements of this list. */ - <MappedType> IList<MappedType> map( - Function<ContainedType, MappedType> transformer); + <MappedType> IList<MappedType> map(Function<ContainedType, MappedType> transformer); /** * Zip two lists into a list of pairs * * @param <OtherType> - * The type of the second list + * The type of the second list * * @param list - * The list to use as the left side of the pair + * The list to use as the left side of the pair * @return A list containing pairs of this element and the specified * list */ @@ -224,7 +221,8 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Partition this list into a list of sublists * * @param partitionSize - * The size of elements to put into each one of the sublists + * The size of elements to put into each one of the + * sublists * @return A list partitioned into partitions of size nPerPart */ IList<IList<ContainedType>> partition(int partitionSize); @@ -233,7 +231,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Prepend an item to the list * * @param item - * The item to prepend to the list + * The item to prepend to the list */ void prepend(ContainedType item); @@ -248,11 +246,11 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { } /** - * Select a random item from this list, using the provided random - * number generator. + * Select a random item from this list, using the provided random number + * generator. * * @param rnd - * The random number generator to use. + * The random number generator to use. * @return A random element from this list. */ ContainedType randItem(Function<Integer, Integer> rnd); @@ -261,18 +259,18 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce this list to a single value, using a accumulative approach. * * @param <StateType> - * The in-between type of the values + * The in-between type of the values * @param <ReducedType> - * The final value type + * The final value type * * @param initial - * The initial value of the accumulative state. + * The initial value of the accumulative state. * @param accumulator - * The function to use to combine a list element with the - * accumulative state. + * The function to use to combine a list element with the + * accumulative state. * @param transformer - * The function to use to convert the accumulative state - * into a final result. + * The function to use to convert the accumulative state + * into a final result. * @return A single value condensed from this list and transformed into * its final state. */ @@ -284,7 +282,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Remove all elements that match a given predicate * * @param predicate - * The predicate to use to determine elements to delete + * The predicate to use to determine elements to delete * @return Whether there was anything that satisfied the predicate */ boolean removeIf(Predicate<ContainedType> predicate); @@ -293,7 +291,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Remove all parameters that match a given parameter * * @param element - * The object to remove all matching copies of + * The object to remove all matching copies of */ void removeMatching(ContainedType element); @@ -304,29 +302,29 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Perform a binary search for the specified key using the provided - * means of comparing elements. + * means of comparing elements. * - * Since this IS a binary search, the list must have been sorted before hand. + * Since this IS a binary search, the list must have been sorted before + * hand. * * @param key - * The key to search for. + * The key to search for. * @param comparator - * The way to compare elements for searching. Pass null to - * use the natural ordering for E + * The way to compare elements for searching. Pass null + * to use the natural ordering for E * @return The element if it is in this list, or null if it is not. */ - ContainedType search(ContainedType key, - Comparator<ContainedType> comparator); + ContainedType search(ContainedType key, Comparator<ContainedType> comparator); /** * Sort the elements of this list using the provided way of comparing - * elements. + * elements. * * Does change the underlying list. * * @param comparator - * The way to compare elements for sorting. Pass null to use - * E's natural ordering + * The way to compare elements for sorting. Pass null to + * use E's natural ordering */ void sort(Comparator<ContainedType> comparator); @@ -341,7 +339,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Convert this list into an array * * @param type - * The type of array to return + * The type of array to return * @return The list, as an array */ ContainedType[] toArray(ContainedType[] type); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java index 9e74628..ff8f973 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java @@ -10,9 +10,9 @@ import java.util.function.Function; * @author ben * * @param <KeyType> - * The type of this map's keys + * The type of this map's keys * @param <ValueType> - * The type of this map's values + * The type of this map's values * */ public interface IMap<KeyType, ValueType> { @@ -25,7 +25,7 @@ public interface IMap<KeyType, ValueType> { * Check if this map contains the specified key * * @param key - * The key to check + * The key to check * @return Whether or not the map contains the key */ boolean containsKey(KeyType key); @@ -42,7 +42,7 @@ public interface IMap<KeyType, ValueType> { * Execute an action for each entry in the map * * @param action - * the action to execute for each entry in the map + * the action to execute for each entry in the map */ void forEach(BiConsumer<KeyType, ValueType> action); @@ -50,7 +50,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each key in the map * * @param action - * The action to perform on each key in the map + * The action to perform on each key in the map */ void forEachKey(Consumer<KeyType> action); @@ -58,7 +58,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each value in the map * * @param action - * The action to perform on each value in the map + * The action to perform on each value in the map */ void forEachValue(Consumer<ValueType> action); @@ -66,7 +66,7 @@ public interface IMap<KeyType, ValueType> { * Get the value assigned to the given key * * @param key - * The key to look for a value under + * The key to look for a value under * @return The value of the key * * @@ -78,9 +78,9 @@ public interface IMap<KeyType, ValueType> { * doesn't exist * * @param key - * The key to attempt to retrieve + * The key to attempt to retrieve * @param defaultValue - * The value to return if the key doesn't exist + * The value to return if the key doesn't exist * @return The value associated with the key, or the default value if * the key doesn't exist */ @@ -88,7 +88,8 @@ public interface IMap<KeyType, ValueType> { try { return get(key); } catch (IllegalArgumentException iaex) { - // We don't care about this, because it indicates a key is + // We don't care about this, because it indicates a key + // is // missing return defaultValue; } @@ -116,9 +117,9 @@ public interface IMap<KeyType, ValueType> { * likely not work as expected. * * @param <V2> - * The new type of returned values + * The new type of returned values * @param transformer - * The function to use to transform values + * The function to use to transform values * @return The map where each value will be transformed after lookup */ <V2> IMap<KeyType, V2> mapValues(Function<ValueType, V2> transformer); @@ -127,16 +128,16 @@ public interface IMap<KeyType, ValueType> { * Add an entry to the map * * @param key - * The key to put the value under + * The key to put the value under * @param val - * The value to add + * The value to add * @return The previous value of the key in the map, or null if the key - * wasn't in the map. However, note that it may also return - * null if the key was set to null. + * wasn't in the map. However, note that it may also return null + * if the key was set to null. * * @throws UnsupportedOperationException - * if the map implementation doesn't support modifying the - * map + * if the map implementation doesn't support modifying + * the map */ ValueType put(KeyType key, ValueType val); @@ -144,11 +145,11 @@ public interface IMap<KeyType, ValueType> { * Remove the value bound to the key * * @param key - * The key to remove from the map - * @return The previous value for the key in the map, or null if the - * key wasn't in the class. NOTE: Just because you received - * null, doesn't mean the map wasn't changed. It may mean that - * someone put a null value for that key into the map + * The key to remove from the map + * @return The previous value for the key in the map, or null if the key + * wasn't in the class. NOTE: Just because you received null, + * doesn't mean the map wasn't changed. It may mean that someone + * put a null value for that key into the map */ ValueType remove(KeyType key); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java index 49cb106..32ec7cd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/SentryList.java @@ -13,8 +13,8 @@ public class SentryList<T> extends FunctionalList<T> { public boolean add(T item) { boolean val = super.add(item); - - if(val) + + if (val) System.out.println("Added item (" + item + ") to list"); return val; diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java index c87c34b..36bfaab 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java @@ -10,19 +10,17 @@ import java.util.function.Function; * @author ben * * @param <OldKey> - * The type of the map's keys + * The type of the map's keys * @param <OldValue> - * The type of the map's values + * The type of the map's values * @param <NewValue> - * The type of the transformed values + * The type of the transformed values */ -final class TransformedValueMap<OldKey, OldValue, NewValue> - implements IMap<OldKey, NewValue> { - private IMap<OldKey, OldValue> backing; - private Function<OldValue, NewValue> transformer; +final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldKey, NewValue> { + private IMap<OldKey, OldValue> backing; + private Function<OldValue, NewValue> transformer; - public TransformedValueMap(IMap<OldKey, OldValue> backingMap, - Function<OldValue, NewValue> transform) { + public TransformedValueMap(IMap<OldKey, OldValue> backingMap, Function<OldValue, NewValue> transform) { backing = backingMap; transformer = transform; } @@ -77,8 +75,7 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> } @Override - public <MappedValue> IMap<OldKey, MappedValue> - mapValues(Function<NewValue, MappedValue> transform) { + public <MappedValue> IMap<OldKey, MappedValue> mapValues(Function<NewValue, MappedValue> transform) { return new TransformedValueMap<>(this, transform); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java index b595946..b3772a4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java @@ -14,29 +14,29 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <T> - * The data type stored in the node. + * The data type stored in the node. */ public class BinarySearchTree<T> { /* * The comparator for use in ordering items */ - private Comparator<T> comparator; + private Comparator<T> comparator; /* * The current count of elements in the tree */ - private int elementCount; + private int elementCount; /* * The root element of the tree */ - private ITreePart<T> root; + private ITreePart<T> root; /** * Create a new tree using the specified way to compare elements. * * @param cmp - * The thing to use for comparing elements + * The thing to use for comparing elements */ public BinarySearchTree(Comparator<T> cmp) { if (cmp == null) { @@ -51,7 +51,7 @@ public class BinarySearchTree<T> { * Add a node to the binary search tree. * * @param element - * The data to add to the binary search tree. + * The data to add to the binary search tree. */ public void addNode(T element) { elementCount++; @@ -67,11 +67,11 @@ public class BinarySearchTree<T> { * Check if an adjusted pivot falls with the bounds of a list * * @param elements - * The list to get bounds from + * The list to get bounds from * @param pivot - * The pivot + * The pivot * @param pivotAdjustment - * The distance from the pivot + * The distance from the pivot * @return Whether the adjusted pivot is with the list */ private boolean adjustedPivotInBounds(IList<T> elements, int pivot, int pivotAdjustment) { @@ -102,7 +102,8 @@ public class BinarySearchTree<T> { // Create a new root element root = new BinarySearchTreeNode<>(elements.getByIndex(pivot), null, null); } else { - // Add the left and right elements in a balanced manner + // Add the left and right elements in a balanced + // manner root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); @@ -123,11 +124,11 @@ public class BinarySearchTree<T> { /** * Soft-delete a node from the tree. * - * Soft-deleted nodes stay in the tree until trim()/balance() is invoked, and - * are not included in traversals/finds. + * Soft-deleted nodes stay in the tree until trim()/balance() is + * invoked, and are not included in traversals/finds. * * @param element - * The node to delete + * The node to delete */ public void deleteNode(T element) { elementCount--; @@ -148,7 +149,7 @@ public class BinarySearchTree<T> { * Check if a node is in the tree * * @param element - * The node to check the presence of for the tree. + * The node to check the presence of for the tree. * @return Whether or not the node is in the tree. */ public boolean isInTree(T element) { @@ -159,9 +160,9 @@ public class BinarySearchTree<T> { * Traverse the tree in a specified way until the function fails * * @param linearizationMethod - * The way to linearize the tree for traversal + * The way to linearize the tree for traversal * @param traversalPredicate - * The function to use until it fails + * The function to use until it fails */ public void traverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (linearizationMethod == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java index d647742..04765b4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java @@ -11,24 +11,24 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data stored in the tree. + * The data stored in the tree. */ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { /** * The data held in this tree leaf */ - protected T data; + protected T data; /** * Whether this node is soft-deleted or not */ - protected boolean isDeleted; + protected boolean isDeleted; /** * Create a new leaf holding the specified data. * * @param element - * The data for the leaf to hold. + * The data for the leaf to hold. */ public BinarySearchTreeLeaf(T element) { data = element; @@ -72,14 +72,14 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } switch (treeWalker.walk(data)) { - case SUCCESS: - return true; - // We don't have any children to care about - case FAILURE: - case LEFT: - case RIGHT: - default: - return false; + case SUCCESS: + return true; + // We don't have any children to care about + case FAILURE: + case LEFT: + case RIGHT: + default: + return false; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java index fa3add0..46a89f2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java @@ -16,31 +16,30 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data type stored in the tree. + * The data type stored in the tree. */ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* * The left child of this node */ - private ITreePart<T> left; + private ITreePart<T> left; /* * The right child of this node */ - private ITreePart<T> right; + private ITreePart<T> right; /** * Create a new node with the specified data and children. * * @param element - * The data to store in this node. + * The data to store in this node. * @param lft - * The left child of this node. + * The left child of this node. * @param rght - * The right child of this node. + * The right child of this node. */ - public BinarySearchTreeNode(T element, ITreePart<T> lft, - ITreePart<T> rght) { + public BinarySearchTreeNode(T element, ITreePart<T> lft, ITreePart<T> rght) { super(element); this.left = lft; this.right = rght; @@ -53,29 +52,29 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } switch (comparator.compare(data, element)) { - case -1: - if (left == null) { - left = new BinarySearchTreeNode<>(element, null, null); - } else { - left.add(element, comparator); - } - break; - case 0: - if (isDeleted) { - isDeleted = false; - } else { - throw new IllegalArgumentException("Can't add duplicate values"); - } - break; - case 1: - if (right == null) { - right = new BinarySearchTreeNode<>(element, null, null); - } else { - right.add(element, comparator); - } - break; - default: - throw new IllegalStateException("Error: Comparator yielded invalid value"); + case -1: + if (left == null) { + left = new BinarySearchTreeNode<>(element, null, null); + } else { + left.add(element, comparator); + } + break; + case 0: + if (isDeleted) { + isDeleted = false; + } else { + throw new IllegalArgumentException("Can't add duplicate values"); + } + break; + case 1: + if (right == null) { + right = new BinarySearchTreeNode<>(element, null, null); + } else { + right.add(element, comparator); + } + break; + default: + throw new IllegalStateException("Error: Comparator yielded invalid value"); } } @@ -118,14 +117,14 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return directedWalk(currentElement -> { switch (comparator.compare(element, currentElement)) { - case -1: - return LEFT; - case 0: - return isDeleted ? FAILURE : SUCCESS; - case 1: - return RIGHT; - default: - return FAILURE; + case -1: + return LEFT; + case 0: + return isDeleted ? FAILURE : SUCCESS; + case 1: + return RIGHT; + default: + return FAILURE; } }); } @@ -138,15 +137,15 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { directedWalk(currentElement -> { switch (comparator.compare(data, element)) { - case -1: - return left == null ? FAILURE : LEFT; - case 0: - isDeleted = true; - return FAILURE; - case 1: - return right == null ? FAILURE : RIGHT; - default: - return FAILURE; + case -1: + return left == null ? FAILURE : LEFT; + case 0: + isDeleted = true; + return FAILURE; + case 1: + return right == null ? FAILURE : RIGHT; + default: + return FAILURE; } }); } @@ -158,16 +157,16 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } switch (treeWalker.walk(data)) { - case SUCCESS: - return true; - case LEFT: - return left.directedWalk(treeWalker); - case RIGHT: - return right.directedWalk(treeWalker); - case FAILURE: - return false; - default: - return false; + case SUCCESS: + return true; + case LEFT: + return left.directedWalk(treeWalker); + case RIGHT: + return right.directedWalk(treeWalker); + case FAILURE: + return false; + default: + return false; } } @@ -180,20 +179,19 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } switch (linearizationMethod) { - case PREORDER: - return preorderTraverse(linearizationMethod, traversalPredicate); - case INORDER: - return inorderTraverse(linearizationMethod, traversalPredicate); - case POSTORDER: - return postorderTraverse(linearizationMethod, traversalPredicate); - default: - throw new IllegalArgumentException( - "Passed an incorrect TreeLinearizationMethod " - + linearizationMethod + ". WAT"); + case PREORDER: + return preorderTraverse(linearizationMethod, traversalPredicate); + case INORDER: + return inorderTraverse(linearizationMethod, traversalPredicate); + case POSTORDER: + return postorderTraverse(linearizationMethod, traversalPredicate); + default: + throw new IllegalArgumentException( + "Passed an incorrect TreeLinearizationMethod " + linearizationMethod + ". WAT"); } } - private boolean inorderTraverse( TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + private boolean inorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { return false; } @@ -209,7 +207,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return true; } - private boolean postorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + private boolean postorderTraverse(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { return false; } @@ -254,7 +253,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return nodeSuccesfullyTraversed; } - private boolean traverseLeftBranch(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + private boolean traverseLeftBranch(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { boolean leftSuccesfullyTraversed; if (left == null) { @@ -266,7 +266,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return leftSuccesfullyTraversed; } - private boolean traverseRightBranch(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { + private boolean traverseRightBranch(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { boolean rightSuccesfullyTraversed; if (right == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java index 3f12fb6..e68bef6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java @@ -6,7 +6,7 @@ package bjc.utils.funcdata.bst; * @author ben * * @param <T> - * The type of element stored in the walked tree + * The type of element stored in the walked tree */ @FunctionalInterface public interface DirectedWalkFunction<T> { @@ -22,7 +22,8 @@ public interface DirectedWalkFunction<T> { */ FAILURE, /** - * Specifies that the function wants to move left in the tree next. + * Specifies that the function wants to move left in the tree + * next. */ LEFT, /** @@ -41,7 +42,7 @@ public interface DirectedWalkFunction<T> { * Perform a directed walk on a node of a tree. * * @param element - * The data stored in the node currently being visited + * The data stored in the node currently being visited * @return The way the function wants the walk to go next. */ public DirectedWalkResult walk(T element); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java index c574196..c648001 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java @@ -11,17 +11,17 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data contained in this part of the tree. + * The data contained in this part of the tree. */ public interface ITreePart<T> { /** * Add a element below this tree part somewhere. * * @param element - * The element to add below this tree part + * The element to add below this tree part * @param comparator - * The thing to use for comparing values to find where to - * insert the tree part. + * The thing to use for comparing values to find where to + * insert the tree part. */ public void add(T element, Comparator<T> comparator); @@ -30,25 +30,25 @@ public interface ITreePart<T> { * underlying tree. * * @param <E> - * The type of the final collapsed value + * The type of the final collapsed value * * @param nodeCollapser - * The function to use to transform data into mapped form. + * The function to use to transform data into mapped + * form. * @param branchCollapser - * The function to use to collapse data in mapped form into - * a single value. + * The function to use to collapse data in mapped form + * into a single value. * @return A single value from collapsing the tree. */ - public <E> E collapse(Function<T, E> nodeCollapser, - BiFunction<E, E, E> branchCollapser); + public <E> E collapse(Function<T, E> nodeCollapser, BiFunction<E, E, E> branchCollapser); /** * Check if this tre part or below it contains the specified data item * * @param element - * The data item to look for. + * The data item to look for. * @param comparator - * The comparator to use to search for the data item + * The comparator to use to search for the data item * @return Whether or not the given item is contained in this tree part * or its children. */ @@ -65,9 +65,9 @@ public interface ITreePart<T> { * Remove the given node from this tree part and any of its children. * * @param element - * The data item to remove. + * The data item to remove. * @param comparator - * The comparator to use to search for the data item. + * The comparator to use to search for the data item. */ public void delete(T element, Comparator<T> comparator); @@ -75,7 +75,8 @@ public interface ITreePart<T> { * Execute a directed walk through the tree. * * @param walker - * The function to use to direct the walk through the tree. + * The function to use to direct the walk through the + * tree. * @return Whether the directed walk finished successfully. */ public boolean directedWalk(DirectedWalkFunction<T> walker); @@ -85,12 +86,11 @@ public interface ITreePart<T> { * completes for * * @param linearizationMethod - * The way to linearize the tree for executing + * The way to linearize the tree for executing * @param predicate - * The predicate to apply to each element, where it returning - * false terminates traversal early + * The predicate to apply to each element, where it + * returning false terminates traversal early * @return Whether the traversal finished succesfully */ - public boolean forEach(TreeLinearizationMethod linearizationMethod, - Predicate<T> predicate); + public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> predicate); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java index eedb189..f7d6280 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/TreeLinearizationMethod.java @@ -8,8 +8,8 @@ package bjc.utils.funcdata.bst; */ public enum TreeLinearizationMethod { /** - * Visit the left side of this tree part, the tree part itself, and - * then the right part. + * Visit the left side of this tree part, the tree part itself, and then + * the right part. */ INORDER, /** @@ -18,8 +18,8 @@ public enum TreeLinearizationMethod { */ POSTORDER, /** - * Visit the tree part itself, then the left side of tthis tree part - * and then the right part. + * Visit the tree part itself, then the left side of tthis tree part and + * then the right part. */ PREORDER }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java index a8f27c6..fa69f31 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java @@ -7,9 +7,9 @@ import java.util.function.Function; * * @author ben * @param <LeftType> - * The type stored on the 'left' of the pair + * The type stored on the 'left' of the pair * @param <RightType> - * The type stored on the 'right' of the pair + * The type stored on the 'right' of the pair * */ public interface Bifunctor<LeftType, RightType> { @@ -18,44 +18,31 @@ public interface Bifunctor<LeftType, RightType> { * parts of a pair * * @param <OldLeft> - * The old left type of the pair + * The old left type of the pair * @param <OldRight> - * The old right type of the pair + * The old right type of the pair * @param <NewLeft> - * The new left type of the pair + * The new left type of the pair * @param <NewRight> - * The new right type of the pair + * The new right type of the pair * @param leftFunc - * The function that maps over the left of the pair + * The function that maps over the left of the pair * @param rightFunc - * The function that maps over the right of the pair + * The function that maps over the right of the pair * @return A function that maps over both parts of the pair */ - public default <OldLeft, OldRight, NewLeft, - NewRight> Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<NewLeft, NewRight>> bimap( - Function<OldLeft, NewLeft> leftFunc, - Function<OldRight, NewRight> rightFunc) { - Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<NewLeft, NewRight>> bimappedFunc = (argPair) -> { - Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<NewLeft, - OldRight>> leftMapper = argPair.< - OldLeft, OldRight, - NewLeft> fmapLeft(leftFunc); + public default <OldLeft, OldRight, NewLeft, NewRight> Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, NewRight>> bimap( + Function<OldLeft, NewLeft> leftFunc, Function<OldRight, NewRight> rightFunc) { + Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, NewRight>> bimappedFunc = (argPair) -> { + Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, OldRight>> leftMapper = argPair + .<OldLeft, OldRight, NewLeft>fmapLeft(leftFunc); - Bifunctor<NewLeft, - OldRight> leftMappedFunctor = leftMapper - .apply(argPair); - Function<Bifunctor<NewLeft, OldRight>, - Bifunctor<NewLeft, - NewRight>> rightMapper = leftMappedFunctor - .<NewLeft, OldRight, - NewRight> fmapRight( - rightFunc); + Bifunctor<NewLeft, OldRight> leftMappedFunctor = leftMapper.apply(argPair); + Function<Bifunctor<NewLeft, OldRight>, Bifunctor<NewLeft, NewRight>> rightMapper = leftMappedFunctor + .<NewLeft, OldRight, NewRight>fmapRight(rightFunc); - return rightMapper.apply(leftMappedFunctor); - }; + return rightMapper.apply(leftMappedFunctor); + }; return bimappedFunc; } @@ -64,40 +51,35 @@ public interface Bifunctor<LeftType, RightType> { * Lift a function to operate over the left part of this pair * * @param <OldLeft> - * The old left type of the pair + * The old left type of the pair * @param <OldRight> - * The old right type of the pair + * The old right type of the pair * @param <NewLeft> - * The new left type of the pair + * The new left type of the pair * @param func - * The function to lift to work over the left side of the - * pair + * The function to lift to work over the left side of the + * pair * @return The function lifted to work over the left side of bifunctors */ - public <OldLeft, OldRight, - NewLeft> Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<NewLeft, OldRight>> fmapLeft( - Function<OldLeft, NewLeft> func); + public <OldLeft, OldRight, NewLeft> Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, OldRight>> fmapLeft( + Function<OldLeft, NewLeft> func); /** * Lift a function to operate over the right part of this pair * * @param <OldLeft> - * The old left type of the pair + * The old left type of the pair * @param <OldRight> - * The old right type of the pair + * The old right type of the pair * @param <NewRight> - * The new right type of the pair + * The new right type of the pair * @param func - * The function to lift to work over the right side of the - * pair - * @return The function lifted to work over the right side of - * bifunctors + * The function to lift to work over the right side of + * the pair + * @return The function lifted to work over the right side of bifunctors */ - public <OldLeft, OldRight, - NewRight> Function<Bifunctor<OldLeft, OldRight>, - Bifunctor<OldLeft, NewRight>> fmapRight( - Function<OldRight, NewRight> func); + public <OldLeft, OldRight, NewRight> Function<Bifunctor<OldLeft, OldRight>, Bifunctor<OldLeft, NewRight>> fmapRight( + Function<OldRight, NewRight> func); /** * Get the value contained on the left of this bifunctor diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java index 9749d95..a5007f1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java @@ -8,28 +8,27 @@ import java.util.function.Function; * * @author ben * @param <ContainedType> - * The value inside the functor + * The value inside the functor */ public interface Functor<ContainedType> { /** * Converts a normal function to operate over values in a functor. * * N.B: Even though the type signature implies that you can apply the - * resulting function to any type of functor, it is only safe to call - * it on instances of the type of functor you called fmap on. + * resulting function to any type of functor, it is only safe to call it + * on instances of the type of functor you called fmap on. * * @param <ArgType> - * The argument of the function + * The argument of the function * @param <ReturnType> - * The return type of the function + * The return type of the function * @param func - * The function to convert + * The function to convert * @return The passed in function converted to work over a particular * type of functors */ - public <ArgType, ReturnType> - Function<Functor<ArgType>, Functor<ReturnType>> - fmap(Function<ArgType, ReturnType> func); + public <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( + Function<ArgType, ReturnType> func); /** * Retrieve the thing inside this functor diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java index eb3695e..1e5d7de 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -16,26 +16,24 @@ public class CollectorUtils { * Create a collector that applies two collectors at once * * @param <InitialType> - * The type of the collection to collect from + * The type of the collection to collect from * @param <AuxType1> - * The intermediate type of the first collector + * The intermediate type of the first collector * @param <AuxType2> - * The intermediate type of the second collector + * The intermediate type of the second collector * @param <FinalType1> - * The final type of the first collector + * The final type of the first collector * @param <FinalType2> - * The final type of the second collector + * The final type of the second collector * @param first - * The first collector to use + * The first collector to use * @param second - * The second collector to use + * The second collector to use * @return A collector that functions as mentioned above */ - public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> - Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> - compoundCollect( - Collector<InitialType, AuxType1, FinalType1> first, - Collector<InitialType, AuxType2, FinalType2> second) { + public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> compoundCollect( + Collector<InitialType, AuxType1, FinalType1> first, + Collector<InitialType, AuxType2, FinalType2> second) { return new CompoundCollector<>(first, second); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java index de5fe85..1f73d0a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -13,15 +13,14 @@ import bjc.utils.data.Identity; import bjc.utils.data.Pair; final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2> - implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> { + implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> { - private Set<java.util.stream.Collector.Characteristics> characteristicSet; + private Set<java.util.stream.Collector.Characteristics> characteristicSet; - private Collector<InitialType, AuxType1, FinalType1> first; - private Collector<InitialType, AuxType2, FinalType2> second; + private Collector<InitialType, AuxType1, FinalType1> first; + private Collector<InitialType, AuxType2, FinalType2> second; - public CompoundCollector( - Collector<InitialType, AuxType1, FinalType1> first, + public CompoundCollector(Collector<InitialType, AuxType1, FinalType1> first, Collector<InitialType, AuxType2, FinalType2> second) { this.first = first; this.second = second; @@ -69,9 +68,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final return (state) -> { return state.unwrap((pair) -> { return pair.bind((left, right) -> { - return new Pair<>( - first.finisher().apply(left), - second.finisher().apply(right)); + return new Pair<>(first.finisher().apply(left), second.finisher().apply(right)); }); }); }; @@ -80,9 +77,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public Supplier<IHolder<IPair<AuxType1, AuxType2>>> supplier() { return () -> { - return new Identity<>(new Pair<>( - first.supplier().get(), - second.supplier().get())); + return new Identity<>(new Pair<>(first.supplier().get(), second.supplier().get())); }; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java index d6e77c7..747b39f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/DoubleMatcher.java @@ -10,56 +10,63 @@ import java.util.regex.Pattern; class DoubleMatcher { private static final String Digits = "(\\p{Digit}+)"; private static final String HexDigits = "(\\p{XDigit}+)"; - + /* * an exponent is 'e' or 'E' followed by an optionally signed decimal * integer. */ private static final String Exp = "[eE][+-]?" + Digits; - private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional leading "whitespace" - "[+-]?(" + // Optional sign character - "NaN|" + // "NaN" string - "Infinity|" + // "Infinity" string + private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional + // leading + // "whitespace" + "[+-]?(" + // Optional sign character + "NaN|" + // "NaN" string + "Infinity|" + // "Infinity" string - /* A decimal floating-point string representing a finite positive - * number without a leading sign has at most five basic pieces: - * Digits . Digits ExponentPart FloatTypeSuffix - * - * Since this method allows integer-only strings as input - * in addition to strings of floating-point literals, the - * two sub-patterns below are simplifications of the grammar - * productions from section 3.10.2 of - * The Javaâ„¢ Language Specification. - */ + /* + * A decimal floating-point string representing a finite + * positive number without a leading sign has at most + * five basic pieces: Digits . Digits ExponentPart + * FloatTypeSuffix + * + * Since this method allows integer-only strings as + * input in addition to strings of floating-point + * literals, the two sub-patterns below are + * simplifications of the grammar productions from + * section 3.10.2 of The Javaâ„¢ Language Specification. + */ - /* - * Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt - */ - "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ + /* + * Digits ._opt Digits_opt ExponentPart_opt + * FloatTypeSuffix_opt + */ + "(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|" + - /* - * . Digits ExponentPart_opt FloatTypeSuffix_opt - */ - "(\\.("+Digits+")("+Exp+")?)|"+ + /* + * . Digits ExponentPart_opt FloatTypeSuffix_opt + */ + "(\\.(" + Digits + ")(" + Exp + ")?)|" + - /* - * Hexadecimal strings - */ - "((" + - /* - * 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt - */ - "(0[xX]" + HexDigits + "(\\.)?)|" + + /* + * Hexadecimal strings + */ + "((" + + /* + * 0[xX] HexDigits ._opt BinaryExponent + * FloatTypeSuffix_opt + */ + "(0[xX]" + HexDigits + "(\\.)?)|" + - /* - * 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt - */ - "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + + /* + * 0[xX] HexDigits_opt . HexDigits BinaryExponent + * FloatTypeSuffix_opt + */ + "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + - ")[pP][+-]?" + Digits + "))" + - "[fFdD]?))" + - "[\\x00-\\x20]*"); // Optional trailing "whitespace" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*"); // Optional + // trailing + // "whitespace" public static final Pattern floatingLiteral = Pattern.compile("\\A" + fpRegex + "\\Z"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java index 9be6080..82a29a2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -17,18 +17,18 @@ public class EnumUtils { * Do an action for a random number of enum values * * @param <E> - * The type of the enum + * The type of the enum * @param clasz - * The enum class + * The enum class * @param nValues - * The number of values to execute the action on + * The number of values to execute the action on * @param action - * The action to perform on random values + * The action to perform on random values * @param rnd - * The source of randomness to use + * The source of randomness to use */ - public static <E extends Enum<E>> void doForValues(Class<E> clasz, - int nValues, Consumer<E> action, Random rnd) { + public static <E extends Enum<E>> void doForValues(Class<E> clasz, int nValues, Consumer<E> action, + Random rnd) { E[] enumValues = clasz.getEnumConstants(); IList<E> valueList = new FunctionalList<>(enumValues); @@ -48,15 +48,14 @@ public class EnumUtils { * Get a random value from an enum * * @param <E> - * The type of the enum + * The type of the enum * @param clasz - * The class of the enum + * The class of the enum * @param rnd - * The random source to use + * The random source to use * @return A random value from the specified enum */ - public static <E extends Enum<E>> E getRandomValue(Class<E> clasz, - Random rnd) { + public static <E extends Enum<E>> E getRandomValue(Class<E> clasz, Random rnd) { E[] enumValues = clasz.getEnumConstants(); return new FunctionalList<>(enumValues).randItem(rnd::nextInt); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java index 6fc09ff..35a6b3d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -18,24 +18,23 @@ public class FileUtils { * * * @param root - * The directory to start the traversal at + * The directory to start the traversal at * @param predicate - * The predicate to determine whether or not to traverse a - * directory + * The predicate to determine whether or not to traverse + * a directory * @param action - * The action to invoke upon each file in the directory. - * Returning true means to continue the traversal, returning - * false stops it + * The action to invoke upon each file in the directory. + * Returning true means to continue the traversal, + * returning false stops it * @throws IOException - * if the walk throws an exception + * if the walk throws an exception * - * TODO If it becomes necessary, write another overload for - * this with all the buttons and knobs from walkFileTree + * TODO If it becomes necessary, write another overload + * for this with all the buttons and knobs from + * walkFileTree */ - public static void traverseDirectory(Path root, - BiPredicate<Path, BasicFileAttributes> predicate, - BiPredicate<Path, BasicFileAttributes> action) - throws IOException { + public static void traverseDirectory(Path root, BiPredicate<Path, BasicFileAttributes> predicate, + BiPredicate<Path, BasicFileAttributes> action) throws IOException { Files.walkFileTree(root, new FunctionalFileVisitor(predicate, action)); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java index 679af52..3eb086b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -16,13 +16,13 @@ public class FuncUtils { * function * * @param <A> - * The initial type of the function + * The initial type of the function * @param <B> - * The intermediate type of the function + * The intermediate type of the function * @param <C> - * The terminal type of the function + * The terminal type of the function * @param func - * The function to transform + * The function to transform * @return The function transformed into a unary function returning a * function */ @@ -36,9 +36,9 @@ public class FuncUtils { * Do the specified action the specified number of times * * @param nTimes - * The number of times to do the action + * The number of times to do the action * @param cons - * The action to perform + * The action to perform */ public static void doTimes(int nTimes, Consumer<Integer> cons) { for (int i = 0; i < nTimes; i++) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java index cd833d9..f1240cf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -8,19 +8,17 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.function.BiPredicate; final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { - private BiPredicate<Path, BasicFileAttributes> predicate; - private BiPredicate<Path, BasicFileAttributes> action; + private BiPredicate<Path, BasicFileAttributes> predicate; + private BiPredicate<Path, BasicFileAttributes> action; - public FunctionalFileVisitor( - BiPredicate<Path, BasicFileAttributes> predicate, + public FunctionalFileVisitor(BiPredicate<Path, BasicFileAttributes> predicate, BiPredicate<Path, BasicFileAttributes> action) { this.predicate = predicate; this.action = action; } @Override - public FileVisitResult preVisitDirectory( - Path dir, BasicFileAttributes attrs) throws IOException { + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (predicate.test(dir, attrs)) { return FileVisitResult.CONTINUE; } @@ -29,8 +27,7 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { } @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) - throws IOException { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (action.test(file, attrs)) { return FileVisitResult.CONTINUE; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java index fc58b6a..2330a40 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -12,21 +12,21 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <E> - * The type of element in the list being partitioned + * The type of element in the list being partitioned */ final class GroupPartIteration<E> implements Consumer<E> { - private IList<IList<E>> returnedList; + private IList<IList<E>> returnedList; - public IList<E> currentPartition; - private IList<E> rejectedItems; + public IList<E> currentPartition; + private IList<E> rejectedItems; - private int numberInCurrentPartition; - private int numberPerPartition; + private int numberInCurrentPartition; + private int numberPerPartition; - private Function<E, Integer> elementCounter; + private Function<E, Integer> elementCounter; - public GroupPartIteration(IList<IList<E>> returned, IList<E> rejects, - int nPerPart, Function<E, Integer> eleCount) { + public GroupPartIteration(IList<IList<E>> returned, IList<E> rejects, int nPerPart, + Function<E, Integer> eleCount) { this.returnedList = returned; this.rejectedItems = rejects; this.numberPerPartition = nPerPart; @@ -49,7 +49,7 @@ final class GroupPartIteration<E> implements Consumer<E> { int currentElementCount = elementCounter.apply(value); boolean shouldReject = (numberInCurrentPartition + currentElementCount) >= numberPerPartition; - + if (shouldReject) { rejectedItems.add(value); } else { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java index a55e8e0..357ce70 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/IBuilder.java @@ -6,7 +6,7 @@ package bjc.utils.funcutils; * @author ben * * @param <E> - * The type of object being built + * The type of object being built */ public interface IBuilder<E> { /** @@ -14,8 +14,8 @@ public interface IBuilder<E> { * * @return The built object * @throws IllegalStateException - * if the data in the builder cannot be built into its - * corresponding object at this point in time + * if the data in the builder cannot be built into its + * corresponding object at this point in time */ public E build(); @@ -23,10 +23,9 @@ public interface IBuilder<E> { * Reset the state of this builder to its initial state * * @throws UnsupportedOperationException - * if the builder doesn't support resetting its state + * if the builder doesn't support resetting its state */ public default void reset() { - throw new UnsupportedOperationException( - "Builder doesn't support state resetting"); + throw new UnsupportedOperationException("Builder doesn't support state resetting"); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java index ad7dbad..4e4ce80 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -11,8 +11,8 @@ import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; /** - * Utilities for manipulating FunctionalLists that don't belong in the - * class itself + * Utilities for manipulating FunctionalLists that don't belong in the class + * itself * * @author ben * @@ -25,7 +25,7 @@ public class ListUtils { * spaces * * @param input - * The list of tokens to collapse + * The list of tokens to collapse * @return The collapsed string of tokens */ public static String collapseTokens(IList<String> input) { @@ -41,9 +41,9 @@ public class ListUtils { * seperator after each token * * @param input - * The list of tokens to collapse + * The list of tokens to collapse * @param seperator - * The seperator to use for seperating tokens + * The seperator to use for seperating tokens * @return The collapsed string of tokens */ public static String collapseTokens(IList<String> input, String seperator) { @@ -61,10 +61,10 @@ public class ListUtils { StringBuilder state = new StringBuilder(); int i = 1; - for(String itm : input.toIterable()) { + for (String itm : input.toIterable()) { state.append(itm); - if(i != input.getSize()) { + if (i != input.getSize()) { state.append(seperator); } @@ -79,14 +79,13 @@ public class ListUtils { * Split off affixes from tokens * * @param input - * The tokens to deaffix + * The tokens to deaffix * @param operators - * The affixes to remove + * The affixes to remove * @return The tokens that have been deaffixed * */ - public static IList<String> deAffixTokens(IList<String> input, - Deque<IPair<String, String>> operators) { + public static IList<String> deAffixTokens(IList<String> input, Deque<IPair<String, String>> operators) { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (operators == null) { @@ -95,7 +94,7 @@ public class ListUtils { IList<String> returned = input; - for(IPair<String, String> op : operators) { + for (IPair<String, String> op : operators) { returned = returned.flatMap(token -> { return op.merge(new TokenDeaffixer(token)); }); @@ -108,28 +107,27 @@ public class ListUtils { * Select a number of random items from the list without replacement * * @param <E> - * The type of items to select + * The type of items to select * @param list - * The list to select from + * The list to select from * @param number - * The number of items to selet + * The number of items to selet * @param rng - * A function that creates a random number from 0 to the - * desired number + * A function that creates a random number from 0 to the + * desired number * @return A new list containing the desired number of items randomly * selected from the specified list without replacement */ - public static <E> IList<E> drawWithoutReplacement( - IList<E> list, int number, Function<Integer, Integer> rng) { + public static <E> IList<E> drawWithoutReplacement(IList<E> list, int number, Function<Integer, Integer> rng) { IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); int total = list.getSize(); - + Iterator<E> itr = list.toIterable().iterator(); E element = null; - for(int index = 0; itr.hasNext(); element = itr.next()) { + for (int index = 0; itr.hasNext(); element = itr.next()) { int winningChance = number - selected.getSize(); // n - m @@ -149,19 +147,18 @@ public class ListUtils { * Select a number of random items from the list, with replacement * * @param <E> - * The type of items to select + * The type of items to select * @param list - * The list to select from + * The list to select from * @param number - * The number of items to selet + * The number of items to selet * @param rng - * A function that creates a random number from 0 to the - * desired number + * A function that creates a random number from 0 to the + * desired number * @return A new list containing the desired number of items randomly * selected from the specified list */ - public static <E> IList<E> drawWithReplacement(IList<E> list, - int number, Function<Integer, Integer> rng) { + public static <E> IList<E> drawWithReplacement(IList<E> list, int number, Function<Integer, Integer> rng) { IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); for (int i = 0; i < number; i++) { @@ -176,28 +173,27 @@ public class ListUtils { * for more than one element in a partition * * @param <E> - * The type of elements in the list to partition + * The type of elements in the list to partition * * @param input - * The list to partition + * The list to partition * @param counter - * The function to determine the count for each element for + * The function to determine the count for each element + * for * @param partitionSize - * The number of elements to put in each partition + * The number of elements to put in each partition * * @return A list partitioned according to the above rules */ - public static <E> IList<IList<E>> groupPartition( - IList<E> input, Function<E, Integer> counter, int partitionSize) { + public static <E> IList<IList<E>> groupPartition(IList<E> input, Function<E, Integer> counter, + int partitionSize) { if (input == null) { throw new NullPointerException("Input list must not be null"); } else if (counter == null) { throw new NullPointerException("Counter must not be null"); } else if (partitionSize < 1 || partitionSize > input.getSize()) { - throw new IllegalArgumentException( - "" + partitionSize + " is not a valid" - + " partition size. Must be between 1 and " - + input.getSize()); + throw new IllegalArgumentException("" + partitionSize + " is not a valid" + + " partition size. Must be between 1 and " + input.getSize()); } /* @@ -225,25 +221,20 @@ public class ListUtils { } } - throw new IllegalArgumentException( - "Heuristic (more than " + MAX_NTRIESPART - + " iterations of partitioning) detected unpartitionable list " - + input.toString() - + "\nThe following elements were not partitioned: " - + rejected.toString() - + "\nCurrent group in formation: " - + it.currentPartition.toString() - + "\nPreviously formed groups: " - + returned.toString()); + throw new IllegalArgumentException("Heuristic (more than " + MAX_NTRIESPART + + " iterations of partitioning) detected unpartitionable list " + input.toString() + + "\nThe following elements were not partitioned: " + rejected.toString() + + "\nCurrent group in formation: " + it.currentPartition.toString() + + "\nPreviously formed groups: " + returned.toString()); } /** * Merge the contents of a bunch of lists together into a single list * * @param <E> - * The type of value in this lists + * The type of value in this lists * @param lists - * The values in the lists to merge + * The values in the lists to merge * @return A list containing all the elements of the lists */ @SafeVarargs @@ -251,7 +242,7 @@ public class ListUtils { IList<E> returned = new FunctionalList<>(); for (IList<E> list : lists) { - for(E itm : list.toIterable()) { + for (E itm : list.toIterable()) { returned.add(itm); } } @@ -263,27 +254,25 @@ public class ListUtils { * Pad the provided list out to the desired size * * @param <E> - * The type of elements in the list + * The type of elements in the list * @param list - * The list to pad out + * The list to pad out * @param counter - * The function to count elements with + * The function to count elements with * @param size - * The desired size of the list + * The desired size of the list * @param padder - * The function to get elements to pad with + * The function to get elements to pad with * @return The list, padded to the desired size * @throws IllegalArgumentException - * if the list couldn't be padded to the desired size + * if the list couldn't be padded to the desired size */ - public static <E> IList<E> padList(IList<E> list, - Function<E, Integer> counter, int size, - Supplier<E> padder) { + public static <E> IList<E> padList(IList<E> list, Function<E, Integer> counter, int size, Supplier<E> padder) { int count = 0; IList<E> returned = new FunctionalList<>(); - - for(E itm : list.toIterable()) { + + for (E itm : list.toIterable()) { count += counter.apply(itm); returned.add(itm); @@ -310,8 +299,7 @@ public class ListUtils { } if (threshold > MAX_NTRIESPART) { - throw new IllegalArgumentException("Heuristic (more than " - + MAX_NTRIESPART + throw new IllegalArgumentException("Heuristic (more than " + MAX_NTRIESPART + " iterations of attempting to pad) detected unpaddable list "); } } @@ -326,15 +314,14 @@ public class ListUtils { * something like 1+1 instead of 1 + 1. * * @param input - * The tokens to split + * The tokens to split * @param operators - * Pairs of operators to split on and regexes that match - * those operators + * Pairs of operators to split on and regexes that match + * those operators * @return A list of tokens split on all the operators * */ - public static IList<String> splitTokens(IList<String> input, - Deque<IPair<String, String>> operators) { + public static IList<String> splitTokens(IList<String> input, Deque<IPair<String, String>> operators) { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (operators == null) { @@ -343,7 +330,7 @@ public class ListUtils { IList<String> returned = input; - for(IPair<String, String> op : operators) { + for (IPair<String, String> op : operators) { returned = returned.flatMap(token -> { return op.merge(new TokenSplitter(token)); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java index 91cbeb5..09c3ef7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NeoTokenSplitter.java @@ -11,9 +11,8 @@ public class NeoTokenSplitter { /* * This string is a format template for the delimiter matching regex * - * It does two things - * 1. Match the provided delimiter by positive lookahead - * 2. Match the provided delimiter by positive lookbehind + * It does two things 1. Match the provided delimiter by positive + * lookahead 2. Match the provided delimiter by positive lookbehind * * Thus, it will only match in places where the delimiter is, but won't * actually match the delimiter, leaving split to put it into the stream @@ -48,21 +47,24 @@ public class NeoTokenSplitter { * * The splitter must be compiled first. * - * @param inp The string to split. + * @param inp + * The string to split. * * @return The split string, including delimiters. * - * @throws IllegalStateException If the splitter isn't compiled. + * @throws IllegalStateException + * If the splitter isn't compiled. */ public String[] split(String inp) { - if(compPatt == null) { + if (compPatt == null) { throw new IllegalStateException("Token splitter has not been compiled yet"); } /* * Don't split something that matches only an operator */ - if(exclusionPatt.matcher(inp).matches()) return new String[] {inp}; + if (exclusionPatt.matcher(inp).matches()) + return new String[] { inp }; return compPatt.split(inp); } @@ -73,14 +75,15 @@ public class NeoTokenSplitter { * * The provided string is regex-escaped before being used. * - * @param delim The delimiter to match on. + * @param delim + * The delimiter to match on. */ public void addDelimiter(String delim) { String quoteDelim = Pattern.quote(delim); String delimPat = String.format(WITH_DELIM, quoteDelim); - if(currPatt == null) { - currPatt = new StringBuilder(); + if (currPatt == null) { + currPatt = new StringBuilder(); currExclusionPatt = new StringBuilder(); currPatt.append("(?:" + delimPat + ")"); @@ -97,13 +100,14 @@ public class NeoTokenSplitter { * The provided string should be a pattern to match one or more * occurances of. * - * @param delim The delimiter to split on. + * @param delim + * The delimiter to split on. */ public void addMultiDelimiter(String delim) { String delimPat = String.format(WITH_MULTI_DELIM, "(?:" + delim + ")"); - if(currPatt == null) { - currPatt = new StringBuilder(); + if (currPatt == null) { + currPatt = new StringBuilder(); currExclusionPatt = new StringBuilder(); currPatt.append("(?:" + delimPat + ")"); @@ -121,7 +125,7 @@ public class NeoTokenSplitter { * Makes this splitter ready to use. */ public void compile() { - compPatt = Pattern.compile(currPatt.toString()); + compPatt = Pattern.compile(currPatt.toString()); exclusionPatt = Pattern.compile(currExclusionPatt.toString()); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java index 24c2014..d3352df 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java @@ -13,9 +13,9 @@ public class NumberUtils { * Compute the falling factorial of a number * * @param value - * The number to compute + * The number to compute * @param power - * The power to do the falling factorial for + * The power to do the falling factorial for * @return The falling factorial of the number to the power */ public static int fallingFactorial(int value, int power) { @@ -38,15 +38,14 @@ public class NumberUtils { * Evaluates a linear probability distribution * * @param winning - * The number of winning possibilities + * The number of winning possibilities * @param total - * The number of total possibilities + * The number of total possibilities * @param rng - * The function to use to generate a random possibility + * The function to use to generate a random possibility * @return Whether or not a random possibility was a winning one */ - public static boolean isProbable(int winning, int total, - Function<Integer, Integer> rng) { + public static boolean isProbable(int winning, int total, Function<Integer, Integer> rng) { return rng.apply(total) < winning; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java index 2307f11..2afb783 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -18,18 +18,18 @@ public class StringUtils { * situation that indicates its use as an infix operator. * * @param expression - * The expression to check + * The expression to check * @param operator - * The operator to see if it is contained + * The operator to see if it is contained * @return Whether or not the given expression contains the specified * operator as a infix operator */ public static boolean containsInfixOperator(String expression, String operator) { - // Bit annoying to have to use a full class name, but what are you + // Bit annoying to have to use a full class name, but what are + // you // going to do? return org.apache.commons.lang3.StringUtils.countMatches(expression, operator) == 1 - && !expression.equalsIgnoreCase(operator) - && !expression.startsWith(operator); + && !expression.equalsIgnoreCase(operator) && !expression.startsWith(operator); } /** @@ -37,9 +37,10 @@ public class StringUtils { * expression * * @param input - * The string to check + * The string to check * @param regex - * The regex to see if the string only contains matches of + * The regex to see if the string only contains matches + * of * @return Whether or not the string consists only of multiple matches * of the provided regex */ @@ -54,9 +55,9 @@ public class StringUtils { * This regular expression is fairly simple. * * First, we match the beginning of the string. Then, we start a - * non-capturing group whose contents are the passed in regex. That - * group is then matched one or more times and the pattern matches - * to the end of the string + * non-capturing group whose contents are the passed in regex. + * That group is then matched one or more times and the pattern + * matches to the end of the string */ return input.matches("\\A(?:" + regex + ")+\\Z"); } @@ -65,9 +66,9 @@ public class StringUtils { * Indent the string being built in a StringBuilder n levels * * @param builder - * The builder to indent in + * The builder to indent in * @param levels - * The number of levels to indent + * The number of levels to indent */ public static void indentNLevels(StringBuilder builder, int levels) { for (int i = 0; i < levels; i++) { @@ -80,9 +81,9 @@ public class StringUtils { * empty * * @param <ContainedType> - * The type in the deque + * The type in the deque * @param queue - * The deque to print + * The deque to print * @return A string version of the deque, with allowance for an empty * deque */ @@ -93,29 +94,44 @@ public class StringUtils { /* * This regex matches java-style string escapes */ - private static String escapeString = - "\\\\([btnfr\"'\\\\]" // Match shortform escape sequences like \t or \" - + "|[0-3]?[0-7]{1,2}" // Match octal escape sequences - + "|u[0-9a-fA-F]{4})"; // Match unicode escape sequences + private static String escapeString = "\\\\([btnfr\"'\\\\]" // Match + // shortform + // escape + // sequences + // like + // \t or + // \" + + "|[0-3]?[0-7]{1,2}" // Match octal escape sequences + + "|u[0-9a-fA-F]{4})"; // Match unicode escape sequences private static Pattern escapePatt = Pattern.compile(escapeString); /* * This regular expression matches java style double quoted strings */ - private static Pattern doubleQuotePatt = Pattern.compile("(\"(" - + "[^\\\\\"]+" // Match one or more characters that aren't quotes or slashes + private static Pattern doubleQuotePatt = Pattern.compile("(\"(" + "[^\\\\\"]+" // Match + // one + // or + // more + // characters + // that + // aren't + // quotes + // or + // slashes + "|" + escapeString + ")" // Match escape sequences - + "*\")"); // Match all of those things zero or more times, followed by a closing quote + + "*\")"); // Match all of those things zero or more + // times, followed by a closing quote /** * Remove double quoted strings from a string. * * Splits a string around instances of java-style double-quoted strings. * - * @param inp The string to split. + * @param inp + * The string to split. * * @return An list containing alternating bits of the string and the - * embedded double-quoted strings that seperated them. + * embedded double-quoted strings that seperated them. */ public static List<String> removeDQuotedStrings(String inp) { StringBuffer work = new StringBuffer(); @@ -123,7 +139,7 @@ public class StringUtils { Matcher mt = doubleQuotePatt.matcher(inp); - while(mt.find()) { + while (mt.find()) { mt.appendReplacement(work, ""); res.add(work.toString()); @@ -140,20 +156,21 @@ public class StringUtils { /** * Replace escape characters with their actual equivalents. * - * @param inp The string to replace escape sequences in. + * @param inp + * The string to replace escape sequences in. * * @return The string with escape sequences replaced by their equivalent - * characters. + * characters. */ public static String descapeString(String inp) { StringBuffer work = new StringBuffer(); Matcher escapeFinder = escapePatt.matcher(inp); - while(escapeFinder.find()) { + while (escapeFinder.find()) { String escapeSeq = escapeFinder.group(); String escapeRep = ""; - switch(escapeSeq) { + switch (escapeSeq) { case "\\b": escapeRep = "\b"; break; @@ -179,7 +196,7 @@ public class StringUtils { escapeRep = "\\"; break; default: - if(escapeSeq.startsWith("u")) { + if (escapeSeq.startsWith("u")) { escapeRep = handleUnicodeEscape(escapeSeq.substring(1)); } else { escapeRep = handleOctalEscape(escapeSeq); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java index 0ce6dc1..151b7e2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java @@ -5,8 +5,7 @@ import java.util.function.BiFunction; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; -final class TokenDeaffixer - implements BiFunction<String, String, IList<String>> { +final class TokenDeaffixer implements BiFunction<String, String, IList<String>> { private String token; public TokenDeaffixer(String tok) { @@ -24,7 +23,7 @@ final class TokenDeaffixer if (StringUtils.containsOnly(token, operatorRegex)) { return new FunctionalList<>(token); } else if (token.startsWith(operatorName)) { - if(token.endsWith(operatorName)) { + if (token.endsWith(operatorName)) { return new FunctionalList<>(operatorName, token.split(operatorRegex)[1], operatorName); } @@ -35,11 +34,11 @@ final class TokenDeaffixer String[] tokenParts = token.split(operatorRegex); IList<String> returned = new FunctionalList<>(); - - for(int i = 0; i < tokenParts.length; i++) { + + for (int i = 0; i < tokenParts.length; i++) { returned.add(tokenParts[i]); - if(i < tokenParts.length - 1) { + if (i < tokenParts.length - 1) { returned.add(operatorName); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java index f04b68d..4176088 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java @@ -6,8 +6,7 @@ import java.util.function.BiFunction; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; -final class TokenSplitter - implements BiFunction<String, String, IList<String>> { +final class TokenSplitter implements BiFunction<String, String, IList<String>> { private String tokenToSplit; public TokenSplitter(String tok) { @@ -17,11 +16,9 @@ final class TokenSplitter @Override public IList<String> apply(String operatorName, String operatorRegex) { if (operatorName == null) { - throw new NullPointerException( - "Operator name must not be null"); + throw new NullPointerException("Operator name must not be null"); } else if (operatorRegex == null) { - throw new NullPointerException( - "Operator regex must not be null"); + throw new NullPointerException("Operator regex must not be null"); } if (tokenToSplit.contains(operatorName)) { @@ -37,10 +34,10 @@ final class TokenSplitter String elm = itr.next(); - for(int i = 0; itr.hasNext(); elm = itr.next()) { + for (int i = 0; itr.hasNext(); elm = itr.next()) { result.add(elm); - if(i != tokenExpansionSize) { + if (i != tokenExpansionSize) { result.add(operatorName); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java index 7ed476e..5d054cf 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -9,7 +9,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <E> - * The type of grammar elements to use. + * The type of grammar elements to use. */ public class RandomGrammar<E> extends WeightedGrammar<E> { /** @@ -23,9 +23,9 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Add cases to a specified rule. * * @param rule - * The name of the rule to add cases to. + * The name of the rule to add cases to. * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ @SafeVarargs public final void addCases(E rule, IList<E>... cases) { @@ -38,9 +38,9 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Create a rule with the specified name and cases. * * @param rule - * The name of the rule to add. + * The name of the rule to add. * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ @SafeVarargs public final void makeRule(E rule, IList<E>... cases) { @@ -55,9 +55,9 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Create a rule with the specified name and cases. * * @param rule - * The name of the rule to add. + * The name of the rule to add. * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ public void makeRule(E rule, IList<IList<E>> cases) { if (cases == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java index 2a13be7..c266c7c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -14,13 +14,12 @@ import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; /** - * A random grammar, where certain rules will come up more often than - * others. + * A random grammar, where certain rules will come up more often than others. * * @author ben * * @param <E> - * The values that make up sentances of this grammar. + * The values that make up sentances of this grammar. */ public class WeightedGrammar<E> { /** @@ -31,7 +30,7 @@ public class WeightedGrammar<E> { /** * The rules currently in this grammar */ - protected IMap<E, WeightedRandom<IList<E>>> rules; + protected IMap<E, WeightedRandom<IList<E>>> rules; /** * The random number generator used for random numbers @@ -51,7 +50,7 @@ public class WeightedGrammar<E> { /** * Predicate for marking special tokens */ - + private Predicate<E> specialMarker; /** @@ -73,7 +72,7 @@ public class WeightedGrammar<E> { * randomness. * * @param source - * The source of randomness to use + * The source of randomness to use */ public WeightedGrammar(Random source) { this(); @@ -85,14 +84,13 @@ public class WeightedGrammar<E> { rng = source; } - public void configureSpecial(Predicate<E> marker, - BiFunction<E, WeightedGrammar<E>, IList<E>> action) { + public void configureSpecial(Predicate<E> marker, BiFunction<E, WeightedGrammar<E>, IList<E>> action) { specialMarker = marker; specialAction = action; } public void addSpecialRule(E ruleName, Supplier<IList<E>> cse) { - if(ruleName == null) { + if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); } else if (cse == null) { throw new NullPointerException("Case must not be null"); @@ -105,11 +103,11 @@ public class WeightedGrammar<E> { * Add a case to an already existing rule. * * @param ruleName - * The rule to add a case to. + * The rule to add a case to. * @param probability - * The probability for this rule to be chosen. + * The probability for this rule to be chosen. * @param cse - * The case being added. + * The case being added. */ public void addCase(E ruleName, int probability, IList<E> cse) { if (ruleName == null) { @@ -125,9 +123,9 @@ public class WeightedGrammar<E> { * Add a alias for an existing subgrammar * * @param name - * The name of the subgrammar to alias + * The name of the subgrammar to alias * @param alias - * The alias of the subgrammar + * The alias of the subgrammar * @return Whether the alias was succesfully created */ public boolean addGrammarAlias(E name, E alias) { @@ -153,7 +151,7 @@ public class WeightedGrammar<E> { * Add a new rule with no cases. * * @param name - * The name of the rule to add. + * The name of the rule to add. * @return Whether or not the rule was succesfully added. */ public boolean addRule(E name) { @@ -172,9 +170,9 @@ public class WeightedGrammar<E> { * Add a new rule with a set of cases. * * @param name - * The name of the rule to add. + * The name of the rule to add. * @param cases - * The set of cases for the rule. + * The set of cases for the rule. * @return Whether or not the rule was succesfully added. */ public boolean addRule(E name, WeightedRandom<IList<E>> cases) { @@ -196,9 +194,9 @@ public class WeightedGrammar<E> { * Add a subgrammar. * * @param name - * The name of the subgrammar. + * The name of the subgrammar. * @param subgrammar - * The subgrammar to add. + * The subgrammar to add. * @return Whether or not the subgrammar was succesfully added. */ public boolean addSubgrammar(E name, WeightedGrammar<E> subgrammar) { @@ -220,7 +218,7 @@ public class WeightedGrammar<E> { * Remove a rule with the specified name. * * @param name - * The name of the rule to remove. + * The name of the rule to remove. */ public void deleteRule(E name) { if (name == null) { @@ -234,7 +232,7 @@ public class WeightedGrammar<E> { * Remove a subgrammar with the specified name. * * @param name - * The name of the subgrammar to remove. + * The name of the subgrammar to remove. */ public void deleteSubgrammar(E name) { if (name == null) { @@ -250,7 +248,7 @@ public class WeightedGrammar<E> { * Only generates sentances one layer deep. * * @param ruleName - * The rule to test. + * The rule to test. * @return A set of sentances generated by the specified rule. */ public IList<IList<E>> generateDebugValues(E ruleName) { @@ -273,14 +271,15 @@ public class WeightedGrammar<E> { * Generate a generic sentance from a initial rule. * * @param <T> - * The type of the transformed output + * The type of the transformed output * * @param initRule - * The initial rule to start with. + * The initial rule to start with. * @param tokenTransformer - * The function to transform grammar output into something. + * The function to transform grammar output into + * something. * @param spacer - * The spacer element to add in between output tokens. + * The spacer element to add in between output tokens. * @return A randomly generated sentance from the specified initial * rule. */ @@ -297,39 +296,39 @@ public class WeightedGrammar<E> { IList<E> genRules = new FunctionalList<>(initRules); - if(specialMarker != null) { - if(specialMarker.test(initRules)) { + if (specialMarker != null) { + if (specialMarker.test(initRules)) { genRules = specialAction.apply(initRules, this); } } - for(E initRule : genRules.toIterable()) { - if(specialRules.containsKey(initRule)) { - for(E rulePart : specialRules.get(initRule).get().toIterable()) { - Iterable<T> generatedRuleParts = generateGenericValues( - rulePart, tokenTransformer, spacer).toIterable(); + for (E initRule : genRules.toIterable()) { + if (specialRules.containsKey(initRule)) { + for (E rulePart : specialRules.get(initRule).get().toIterable()) { + Iterable<T> generatedRuleParts = generateGenericValues(rulePart, + tokenTransformer, spacer).toIterable(); - for(T generatedRulePart : generatedRuleParts) { + for (T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } } } else if (subgrammars.containsKey(initRule)) { - Iterable<T> ruleParts = subgrammars.get(initRule).generateGenericValues( - initRule, tokenTransformer, spacer).toIterable(); + Iterable<T> ruleParts = subgrammars.get(initRule) + .generateGenericValues(initRule, tokenTransformer, spacer).toIterable(); - for(T rulePart : ruleParts) { + for (T rulePart : ruleParts) { returnedList.add(rulePart); returnedList.add(spacer); } } else if (rules.containsKey(initRule)) { Iterable<E> ruleParts = rules.get(initRule).generateValue().toIterable(); - for(E rulePart : ruleParts) { - Iterable<T> generatedRuleParts = - generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); + for (E rulePart : ruleParts) { + Iterable<T> generatedRuleParts = generateGenericValues(rulePart, + tokenTransformer, spacer).toIterable(); - for(T generatedRulePart : generatedRuleParts) { + for (T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } @@ -350,13 +349,12 @@ public class WeightedGrammar<E> { } /** - * Generate a random list of grammar elements from a given initial - * rule. + * Generate a random list of grammar elements from a given initial rule. * * @param initRule - * The initial rule to start with. + * The initial rule to start with. * @param spacer - * The item to use to space the list. + * The item to use to space the list. * @return A list of random grammar elements generated by the specified * rule. */ @@ -402,7 +400,7 @@ public class WeightedGrammar<E> { * Get the subgrammar with the specified name. * * @param name - * The name of the subgrammar to get. + * The name of the subgrammar to get. * @return The subgrammar with the specified name. */ public WeightedGrammar<E> getSubgrammar(E name) { @@ -430,16 +428,15 @@ public class WeightedGrammar<E> { * Prefix a given rule with a token multiple times * * @param ruleName - * The name of the rule to prefix + * The name of the rule to prefix * @param prefixToken - * The token to prefix to the rules + * The token to prefix to the rules * @param additionalProbability - * The additional probability of the tokens + * The additional probability of the tokens * @param numberOfTimes - * The number of times to prefix the token + * The number of times to prefix the token */ - public void multiPrefixRule(E ruleName, E prefixToken, - int additionalProbability, int numberOfTimes) { + public void multiPrefixRule(E ruleName, E prefixToken, int additionalProbability, int numberOfTimes) { if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); } else if (prefixToken == null) { @@ -492,11 +489,11 @@ public class WeightedGrammar<E> { * given token * * @param additionalProbability - * The amount to adjust the probability by + * The amount to adjust the probability by * @param ruleName - * The name of the rule to prefix + * The name of the rule to prefix * @param prefixToken - * The token to prefix to the rule + * The token to prefix to the rule */ public void prefixRule(E ruleName, E prefixToken, int additionalProbability) { if (ruleName == null) { @@ -525,16 +522,14 @@ public class WeightedGrammar<E> { newResults.add(new Pair<>(pair.merge((left, right) -> left) + additionalProbability, newCase)); }); - newResults.forEach((pair) -> - pair.doWith((left, right) -> - addCase(ruleName, left, right))); + newResults.forEach((pair) -> pair.doWith((left, right) -> addCase(ruleName, left, right))); } /** * Set the initial rule of the graphic * * @param initRule - * The initial rule of this grammar + * The initial rule of this grammar */ public void setInitialRule(String initRule) { this.initialRule = initRule; @@ -544,11 +539,11 @@ public class WeightedGrammar<E> { * Suffix a token to a rule * * @param ruleName - * The rule to suffix + * The rule to suffix * @param suffixToken - * The token to prefix to the rule + * The token to prefix to the rule * @param additionalProbability - * Additional probability of the prefixed rule + * Additional probability of the prefixed rule */ public void suffixRule(E ruleName, E suffixToken, int additionalProbability) { if (ruleName == null) { @@ -577,8 +572,6 @@ public class WeightedGrammar<E> { newResults.add(new Pair<>(par.merge((left, right) -> left) + additionalProbability, newCase)); }); - newResults.forEach((pair) -> - pair.doWith((left, right) -> - addCase(ruleName, left, right))); + newResults.forEach((pair) -> pair.doWith((left, right) -> addCase(ruleName, left, right))); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java index 2df820c..d5256ee 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -9,46 +9,45 @@ import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; /** - * Represents a random number generator where certain results are weighted - * more heavily than others. + * Represents a random number generator where certain results are weighted more + * heavily than others. * * @author ben * * @param <E> - * The type of values that are randomly selected. + * The type of values that are randomly selected. */ public class WeightedRandom<E> { /* * The list of probabilities for each result */ - private IList<Integer> probabilities; + private IList<Integer> probabilities; /* * The list of possible results to pick from */ - private IList<E> results; + private IList<E> results; /* * The source for any needed random numbers */ - private Random source; + private Random source; - private int totalChance; + private int totalChance; /** * Create a new weighted random generator with the specified source of * randomness * * @param src - * The source of randomness to use. + * The source of randomness to use. */ public WeightedRandom(Random src) { probabilities = new FunctionalList<>(); results = new FunctionalList<>(); if (src == null) { - throw new NullPointerException( - "Source of randomness must not be null"); + throw new NullPointerException("Source of randomness must not be null"); } source = src; @@ -58,9 +57,9 @@ public class WeightedRandom<E> { * Add a probability for a specific result to be given. * * @param chance - * The chance to get this result. + * The chance to get this result. * @param result - * The result to get when the chance comes up. + * The result to get when the chance comes up. */ public void addProbability(int chance, E result) { probabilities.add(chance); @@ -104,8 +103,8 @@ public class WeightedRandom<E> { } /** - * Return a list containing values that can be generated paired with - * the probability of those values being generated + * Return a list containing values that can be generated paired with the + * probability of those values being generated * * @return A list of pairs of values and value probabilities */ diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java index c04aa23..5640ab6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -20,20 +20,19 @@ import bjc.utils.funcutils.FuncUtils; * @author ben * * @param <T> - * The type of the nodes in the graph + * The type of the nodes in the graph */ public class AdjacencyMap<T> { /** * Create an adjacency map from a stream of text * * @param stream - * The stream of text to read in + * The stream of text to read in * @return An adjacency map defined by the text */ public static AdjacencyMap<Integer> fromStream(InputStream stream) { if (stream == null) { - throw new NullPointerException( - "Input source must not be null"); + throw new NullPointerException("Input source must not be null"); } // Create the adjacency map @@ -51,8 +50,7 @@ public class AdjacencyMap<T> { vertexCount = Integer.parseInt(possible); } catch (NumberFormatException nfex) { InputMismatchException imex = new InputMismatchException( - "The first line must contain the number of vertices. " - + possible + "The first line must contain the number of vertices. " + possible + " is not a valid number"); imex.initCause(nfex); @@ -61,8 +59,7 @@ public class AdjacencyMap<T> { } if (vertexCount <= 0) { - throw new InputMismatchException( - "The number of vertices must be greater than 0"); + throw new InputMismatchException("The number of vertices must be greater than 0"); } IList<Integer> vertices = new FunctionalList<>(); @@ -81,14 +78,12 @@ public class AdjacencyMap<T> { return adjacency; } - private static void readRow(AdjacencyMap<Integer> adjacency, - int vertexCount, IHolder<Integer> row, String strang) { + private static void readRow(AdjacencyMap<Integer> adjacency, int vertexCount, IHolder<Integer> row, + String strang) { String[] parts = strang.split(" "); if (parts.length != vertexCount) { - throw new InputMismatchException( - "Must specify a weight for all " + vertexCount - + " vertices"); + throw new InputMismatchException("Must specify a weight for all " + vertexCount + " vertices"); } int column = 0; @@ -124,7 +119,7 @@ public class AdjacencyMap<T> { * Create a new map from a set of vertices * * @param vertices - * The set of vertices to create a map from + * The set of vertices to create a map from */ public AdjacencyMap(IList<T> vertices) { if (vertices == null) { @@ -167,27 +162,23 @@ public class AdjacencyMap<T> { * Set the weight of an edge * * @param source - * The source node of the edge + * The source node of the edge * @param target - * The target node of the edge + * The target node of the edge * @param weight - * The weight of the edge + * The weight of the edge */ public void setWeight(T source, T target, int weight) { if (source == null) { - throw new NullPointerException( - "Source vertex must not be null"); - } else if (target== null) { - throw new NullPointerException( - "Target vertex must not be null"); + throw new NullPointerException("Source vertex must not be null"); + } else if (target == null) { + throw new NullPointerException("Target vertex must not be null"); } if (!adjacency.containsKey(source)) { - throw new IllegalArgumentException("Source vertex " - + source + " isn't present in map"); + throw new IllegalArgumentException("Source vertex " + source + " isn't present in map"); } else if (!adjacency.containsKey(target)) { - throw new IllegalArgumentException("Target vertex " - + target+ " isn't present in map"); + throw new IllegalArgumentException("Target vertex " + target + " isn't present in map"); } adjacency.get(source).put(target, weight); @@ -214,12 +205,11 @@ public class AdjacencyMap<T> { * Convert an adjacency map back into a stream * * @param sink - * The stream to convert to + * The stream to convert to */ public void toStream(OutputStream sink) { if (sink == null) { - throw new NullPointerException( - "Output source must not be null"); + throw new NullPointerException("Output source must not be null"); } PrintStream outputPrinter = new PrintStream(sink); diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java index 2ad4132..c77c0ba 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java @@ -6,36 +6,34 @@ package bjc.utils.graph; * @author ben * * @param <T> - * The type of the nodes in the graph + * The type of the nodes in the graph */ public class Edge<T> { /* * The distance from initial to terminal node */ - private final int distance; + private final int distance; /* * The initial and terminal nodes of this edge */ - private final T source, target; + private final T source, target; /** * Create a new edge with set parameters * * @param initial - * The initial node of the edge + * The initial node of the edge * @param terminal - * The terminal node of the edge + * The terminal node of the edge * @param distance - * The distance between initial and terminal edge + * The distance between initial and terminal edge */ public Edge(T initial, T terminal, int distance) { if (initial == null) { - throw new NullPointerException( - "Initial node must not be null"); + throw new NullPointerException("Initial node must not be null"); } else if (terminal == null) { - throw new NullPointerException( - "Terminal node must not be null"); + throw new NullPointerException("Terminal node must not be null"); } this.source = initial; @@ -109,17 +107,14 @@ public class Edge<T> { int result = 1; result = prime * result + distance; - result = prime * result - + ((source == null) ? 0 : source.hashCode()); - result = prime * result - + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((source == null) ? 0 : source.hashCode()); + result = prime * result + ((target == null) ? 0 : target.hashCode()); return result; } @Override public String toString() { - return " first vertex " + source + " to vertex " + target - + " with distance: " + distance; + return " first vertex " + source + " to vertex " + target + " with distance: " + distance; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java index 66fe580..70fb555 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java @@ -22,25 +22,24 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <T> - * The label for vertices + * The label for vertices */ public class Graph<T> { /** * Create a graph from a list of edges * * @param <E> - * The type of data stored in the edges + * The type of data stored in the edges * * @param edges - * The list of edges to build from + * The list of edges to build from * @return A graph built from the provided edge-list */ public static <E> Graph<E> fromEdgeList(List<Edge<E>> edges) { Graph<E> g = new Graph<>(); edges.forEach(edge -> { - g.addEdge(edge.getSource(), edge.getTarget(), - edge.getDistance(), true); + g.addEdge(edge.getSource(), edge.getTarget(), edge.getDistance(), true); }); return g; @@ -62,29 +61,26 @@ public class Graph<T> { * Add a edge to the graph * * @param source - * The source vertex for this edge + * The source vertex for this edge * @param target - * The target vertex for this edge + * The target vertex for this edge * @param distance - * The distance from the source vertex to the target vertex + * The distance from the source vertex to the target + * vertex * @param directed - * Whether or not + * Whether or not */ - public void addEdge(T source, T target, int distance, - boolean directed) { + public void addEdge(T source, T target, int distance, boolean directed) { // Can't add edges with a null source or target if (source == null) { - throw new NullPointerException( - "The source vertex cannot be null"); + throw new NullPointerException("The source vertex cannot be null"); } else if (target == null) { - throw new NullPointerException( - "The target vertex cannot be null"); + throw new NullPointerException("The target vertex cannot be null"); } // Initialize adjacency list for vertices if necessary if (!backing.containsKey(source)) { - backing.put(source, - new FunctionalMap<T, Integer>()); + backing.put(source, new FunctionalMap<T, Integer>()); } // Add the edge to the graph @@ -93,8 +89,7 @@ public class Graph<T> { // Handle possible directed edges if (!directed) { if (!backing.containsKey(target)) { - backing.put(target, - new FunctionalMap<T, Integer>()); + backing.put(target, new FunctionalMap<T, Integer>()); } backing.get(target).put(source, distance); @@ -106,15 +101,13 @@ public class Graph<T> { * conditions * * @param source - * The vertex to test edges for + * The vertex to test edges for * @param matcher - * The conditions an edge must match + * The conditions an edge must match * @param action - * The action to execute for matching edges + * The action to execute for matching edges */ - public void forAllEdgesMatchingAt(T source, - BiPredicate<T, Integer> matcher, - BiConsumer<T, Integer> action) { + public void forAllEdgesMatchingAt(T source, BiPredicate<T, Integer> matcher, BiConsumer<T, Integer> action) { if (matcher == null) { throw new NullPointerException("Matcher must not be null"); } else if (action == null) { @@ -132,7 +125,7 @@ public class Graph<T> { * Get all the edges that begin at a particular source vertex * * @param source - * The vertex to use as a source + * The vertex to use as a source * @return All of the edges with the specified vertex as a source */ public IMap<T, Integer> getEdges(T source) { @@ -140,8 +133,7 @@ public class Graph<T> { if (source == null) { throw new NullPointerException("The source cannot be null."); } else if (!backing.containsKey(source)) { - throw new IllegalArgumentException( - "Vertex " + source + " is not in graph"); + throw new IllegalArgumentException("Vertex " + source + " is not in graph"); } return backing.get(source); @@ -159,7 +151,8 @@ public class Graph<T> { /** * Uses Prim's algorothm to calculate a MST for the graph. * - * If the graph is non-connected, this will lead to unpredictable results. + * If the graph is non-connected, this will lead to unpredictable + * results. * * @return a list of edges that constitute the MST */ @@ -183,19 +176,17 @@ public class Graph<T> { while (visited.size() != getVertexCount()) { // Grab all edges adjacent to the provided edge - forAllEdgesMatchingAt(source.getValue(), - (target, weight) -> { - return !visited.contains(target); - }, (target, weight) -> { - available.add(new Edge<>( - source.unwrap(vertex -> vertex), - target, weight)); - }); + forAllEdgesMatchingAt(source.getValue(), (target, weight) -> { + return !visited.contains(target); + }, (target, weight) -> { + available.add(new Edge<>(source.unwrap(vertex -> vertex), target, weight)); + }); // Get the edge with the minimum distance IHolder<Edge<T>> minimum = new Identity<>(available.poll()); - // Only consider edges where we haven't visited the target of + // Only consider edges where we haven't visited the + // target of // the edge while (visited.contains(minimum.getValue())) { minimum.transform((edge) -> available.poll()); @@ -236,29 +227,25 @@ public class Graph<T> { * Remove the edge starting at the source and ending at the target * * @param source - * The source vertex for the edge + * The source vertex for the edge * @param target - * The target vertex for the edge + * The target vertex for the edge */ public void removeEdge(T source, T target) { // Can't remove things w/ null vertices if (source == null) { - throw new NullPointerException( - "The source vertex cannot be null"); + throw new NullPointerException("The source vertex cannot be null"); } else if (target == null) { - throw new NullPointerException( - "The target vertex cannot be null"); + throw new NullPointerException("The target vertex cannot be null"); } // Can't remove if one vertice doesn't exists if (!backing.containsKey(source)) { - throw new NoSuchElementException( - "vertex " + source + " does not exist."); + throw new NoSuchElementException("vertex " + source + " does not exist."); } if (!backing.containsKey(target)) { - throw new NoSuchElementException( - "vertex " + target + " does not exist."); + throw new NoSuchElementException("vertex " + target + " does not exist."); } backing.get(source).remove(target); @@ -273,8 +260,7 @@ public class Graph<T> { * @return A adjacency map representing this graph */ public AdjacencyMap<T> toAdjacencyMap() { - AdjacencyMap<T> adjacency = new AdjacencyMap<>( - backing.keyList()); + AdjacencyMap<T> adjacency = new AdjacencyMap<>(backing.keyList()); backing.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java index bb147df..6a5e676 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -23,22 +23,20 @@ public class ExtensionFileFilter extends FileFilter { private IList<String> extensions; /** - * Create a new filter only showing files with the specified - * extensions. + * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(List<String> exts) { extensions = new FunctionalList<>(exts); } /** - * Create a new filter only showing files with the specified - * extensions. + * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(String... exts) { extensions = new FunctionalList<>(exts); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java index 68c4962..7e3cdfd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -25,26 +25,26 @@ public class SimpleDialogs { * Get a bounded integer from the user. * * @param parent - * The parent component for the dialogs. + * The parent component for the dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param lowerBound - * The lower integer bound to accept. + * The lower integer bound to accept. * @param upperBound - * The upper integer bound to accept. + * The upper integer bound to accept. * @return A int within the specified bounds. */ - public static int getBoundedInt(Component parent, String title, - String prompt, int lowerBound, int upperBound) { + public static int getBoundedInt(Component parent, String title, String prompt, int lowerBound, int upperBound) { return getValue(parent, title, prompt, (strang) -> { try { int value = Integer.parseInt(strang); return (value < upperBound) && (value > lowerBound); } catch (NumberFormatException nfex) { - // We don't care about the specifics of the exception, just + // We don't care about the specifics of the + // exception, just // that this value isn't good return false; } @@ -55,21 +55,20 @@ public class SimpleDialogs { * Asks the user to pick an option from a series of choices. * * @param <E> - * The type of choices for the user to pick + * The type of choices for the user to pick * * @param parent - * The parent frame for this dialog + * The parent frame for this dialog * @param title - * The title of this dialog + * The title of this dialog * @param question - * The question being asked + * The question being asked * @param choices - * The available choices for the question + * The available choices for the question * @return The choice the user picked, or null if they didn't pick one */ @SuppressWarnings("unchecked") - public static <E> E getChoice(Frame parent, String title, - String question, E... choices) { + public static <E> E getChoice(Frame parent, String title, String question, E... choices) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -113,21 +112,21 @@ public class SimpleDialogs { * Get a integer from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A int. */ - public static int getInt(Component parent, String title, - String prompt) { + public static int getInt(Component parent, String title, String prompt) { return getValue(parent, title, prompt, strang -> { try { Integer.parseInt(strang); return true; } catch (NumberFormatException nfex) { - // We don't care about this exception, just mark the value + // We don't care about this exception, just mark + // the value // as not good return false; } @@ -138,15 +137,14 @@ public class SimpleDialogs { * Get a string from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A string. */ - public static String getString(Component parent, String title, - String prompt) { + public static String getString(Component parent, String title, String prompt) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -155,30 +153,28 @@ public class SimpleDialogs { throw new NullPointerException("Prompt must not be null"); } - return JOptionPane.showInputDialog(parent, prompt, title, - JOptionPane.QUESTION_MESSAGE); + return JOptionPane.showInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } /** * Get a value parsable from a string from the user. * * @param <E> - * The type of the value parsed from the string + * The type of the value parsed from the string * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param validator - * A predicate to determine if a input is valid. + * A predicate to determine if a input is valid. * @param transformer - * The function to transform the string into a value. + * The function to transform the string into a value. * @return The value parsed from a string. */ - public static <E> E getValue(Component parent, String title, - String prompt, Predicate<String> validator, + public static <E> E getValue(Component parent, String title, String prompt, Predicate<String> validator, Function<String, E> transformer) { if (validator == null) { throw new NullPointerException("Validator must not be null"); @@ -201,15 +197,14 @@ public class SimpleDialogs { * Get a whole number from the user. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A whole number. */ - public static int getWhole(Component parent, String title, - String prompt) { + public static int getWhole(Component parent, String title, String prompt) { return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE); } @@ -217,15 +212,14 @@ public class SimpleDialogs { * Ask the user a Yes/No question. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param question - * The question to ask the user. + * The question to ask the user. * @return True if the user said yes, false otherwise. */ - public static boolean getYesNo(Component parent, String title, - String question) { + public static boolean getYesNo(Component parent, String title, String question) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -234,8 +228,7 @@ public class SimpleDialogs { throw new NullPointerException("Question must not be null"); } - int result = JOptionPane.showConfirmDialog(parent, question, - title, JOptionPane.YES_NO_OPTION); + int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); return (result == JOptionPane.YES_OPTION ? true : false); } @@ -244,39 +237,35 @@ public class SimpleDialogs { * Show a error message to the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param message - * The error to show the user. + * The error to show the user. */ - public static void showError(Component parent, String title, - String message) { + public static void showError(Component parent, String title, String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); } else if (message == null) { - throw new NullPointerException( - "Error message must not be null"); + throw new NullPointerException("Error message must not be null"); } - JOptionPane.showMessageDialog(parent, message, title, - JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } /** * Show an informative message to the user * * @param parent - * The parent for this dialog + * The parent for this dialog * @param title - * Show the title for this dialog + * Show the title for this dialog * @param message - * Show the message for this dialog + * Show the message for this dialog */ - public static void showMessage(Component parent, String title, - String message) { + public static void showMessage(Component parent, String title, String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -285,7 +274,6 @@ public class SimpleDialogs { throw new NullPointerException("Message must not be null"); } - JOptionPane.showMessageDialog(parent, title, message, - JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java index ae77e41..ec4b784 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -16,8 +16,7 @@ import bjc.utils.exceptions.FileNotChosenException; * */ public class SimpleFileChooser { - private static File doOpenFile(Component parent, String title, - JFileChooser files) { + private static File doOpenFile(Component parent, String title, JFileChooser files) { if (title == null) { throw new NullPointerException("Title must not be null"); } @@ -33,16 +32,14 @@ public class SimpleFileChooser { success = true; } catch (FileNotChosenException fncx) { // We don't care about specifics - SimpleDialogs.showError(parent, "I/O Error", - "Please pick a file to open"); + SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open"); } } return files.getSelectedFile(); } - private static File doSaveFile(Component parent, String title, - JFileChooser files) { + private static File doSaveFile(Component parent, String title, JFileChooser files) { if (title == null) { throw new NullPointerException("Title must not be null"); } @@ -58,8 +55,7 @@ public class SimpleFileChooser { return files.getSelectedFile(); } catch (FileNotChosenException fncex) { // We don't care about specifics - SimpleDialogs.showError(parent, "I/O Error", - "Please pick a file to save to"); + SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to"); } } @@ -71,9 +67,9 @@ public class SimpleFileChooser { * until they pick a file. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file the user has chosen. */ public static File getOpenFile(Component parent, String title) { @@ -87,15 +83,14 @@ public class SimpleFileChooser { * until they pick a file. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @param extensions - * The list of file extensions the file should have. + * The list of file extensions the file should have. * @return The file the user has chosen. */ - public static File getOpenFile(Component parent, String title, - String... extensions) { + public static File getOpenFile(Component parent, String title, String... extensions) { JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); @@ -107,9 +102,9 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file the user chose. */ public static File getSaveFile(Component parent, String title) { @@ -122,15 +117,14 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @param extensions - * The extensions of the files the user can choose. + * The extensions of the files the user can choose. * @return The file the user chose. */ - public static File getSaveFile(Component parent, String title, - String... extensions) { + public static File getSaveFile(Component parent, String title, String... extensions) { JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); @@ -138,13 +132,11 @@ public class SimpleFileChooser { return doSaveFile(parent, title, files); } - private static void maybeDoOpenFile(Component parent, - JFileChooser files) throws FileNotChosenException { + private static void maybeDoOpenFile(Component parent, JFileChooser files) throws FileNotChosenException { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (files == null) { - throw new NullPointerException( - "File chooser must not be null"); + throw new NullPointerException("File chooser must not be null"); } int result = files.showSaveDialog(parent); @@ -154,13 +146,11 @@ public class SimpleFileChooser { } } - private static void maybeDoSaveFile(Component parent, - JFileChooser files) throws FileNotChosenException { + private static void maybeDoSaveFile(Component parent, JFileChooser files) throws FileNotChosenException { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (files == null) { - throw new NullPointerException( - "File chooser must not be null"); + throw new NullPointerException("File chooser must not be null"); } int result = files.showSaveDialog(parent); @@ -174,9 +164,9 @@ public class SimpleFileChooser { * Prompt the user with a "Open File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ public static File maybeOpenFile(Component parent, String title) { @@ -200,9 +190,9 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ public static File maybeSaveFile(Component parent, String title) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java index 0152870..b5f0d6c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java @@ -7,7 +7,7 @@ import java.util.function.Predicate; import javax.swing.JOptionPane; /** - * Utility class for getting simple input from the user. + * Utility class for getting simple input from the user. * * Modified to work with JDesktopPanes * @@ -19,26 +19,26 @@ public class SimpleInternalDialogs { * Get a bounded integer from the user. * * @param parent - * The parent component for the dialogs. + * The parent component for the dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param lowerBound - * The lower integer bound to accept. + * The lower integer bound to accept. * @param upperBound - * The upper integer bound to accept. + * The upper integer bound to accept. * @return A int within the specified bounds. */ - public static int getBoundedInt(Component parent, String title, - String prompt, int lowerBound, int upperBound) { + public static int getBoundedInt(Component parent, String title, String prompt, int lowerBound, int upperBound) { return getValue(parent, title, prompt, (strang) -> { try { int value = Integer.parseInt(strang); return (value < upperBound) && (value > lowerBound); } catch (NumberFormatException nfex) { - // We don't care about the specifics of the exception, just + // We don't care about the specifics of the + // exception, just // that this value isn't good return false; } @@ -49,21 +49,21 @@ public class SimpleInternalDialogs { * Get a integer from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A int. */ - public static int getInt(Component parent, String title, - String prompt) { + public static int getInt(Component parent, String title, String prompt) { return getValue(parent, title, prompt, strang -> { try { Integer.parseInt(strang); return true; } catch (NumberFormatException nfex) { - // We don't care about this exception, just mark the value + // We don't care about this exception, just mark + // the value // as not good return false; } @@ -74,15 +74,14 @@ public class SimpleInternalDialogs { * Get a string from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A string. */ - public static String getString(Component parent, String title, - String prompt) { + public static String getString(Component parent, String title, String prompt) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -91,30 +90,28 @@ public class SimpleInternalDialogs { throw new NullPointerException("Prompt must not be null"); } - return JOptionPane.showInternalInputDialog(parent, prompt, title, - JOptionPane.QUESTION_MESSAGE); + return JOptionPane.showInternalInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } /** * Get a value parsable from a string from the user. * * @param <E> - * The type of the value parsed from the string + * The type of the value parsed from the string * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param validator - * A predicate to determine if a input is valid. + * A predicate to determine if a input is valid. * @param transformer - * The function to transform the string into a value. + * The function to transform the string into a value. * @return The value parsed from a string. */ - public static <E> E getValue(Component parent, String title, - String prompt, Predicate<String> validator, + public static <E> E getValue(Component parent, String title, String prompt, Predicate<String> validator, Function<String, E> transformer) { if (validator == null) { throw new NullPointerException("Validator must not be null"); @@ -137,15 +134,14 @@ public class SimpleInternalDialogs { * Get a whole number from the user. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A whole number. */ - public static int getWhole(Component parent, String title, - String prompt) { + public static int getWhole(Component parent, String title, String prompt) { return getBoundedInt(parent, title, prompt, 0, Integer.MAX_VALUE); } @@ -153,15 +149,14 @@ public class SimpleInternalDialogs { * Ask the user a Yes/No question. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param question - * The question to ask the user. + * The question to ask the user. * @return True if the user said yes, false otherwise. */ - public static boolean getYesNo(Component parent, String title, - String question) { + public static boolean getYesNo(Component parent, String title, String question) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -170,8 +165,7 @@ public class SimpleInternalDialogs { throw new NullPointerException("Question must not be null"); } - int result = JOptionPane.showInternalConfirmDialog(parent, - question, title, JOptionPane.YES_NO_OPTION); + int result = JOptionPane.showInternalConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); return (result == JOptionPane.YES_OPTION ? true : false); } @@ -180,39 +174,35 @@ public class SimpleInternalDialogs { * Show a error message to the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param message - * The error to show the user. + * The error to show the user. */ - public static void showError(Component parent, String title, - String message) { + public static void showError(Component parent, String title, String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); } else if (message == null) { - throw new NullPointerException( - "Error message must not be null"); + throw new NullPointerException("Error message must not be null"); } - JOptionPane.showInternalMessageDialog(parent, message, title, - JOptionPane.ERROR_MESSAGE); + JOptionPane.showInternalMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } /** * Show an informative message to the user * * @param parent - * The parent for this dialog + * The parent for this dialog * @param title - * Show the title for this dialog + * Show the title for this dialog * @param message - * Show the message for this dialog + * Show the message for this dialog */ - public static void showMessage(Component parent, String title, - String message) { + public static void showMessage(Component parent, String title, String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -221,7 +211,6 @@ public class SimpleInternalDialogs { throw new NullPointerException("Message must not be null"); } - JOptionPane.showInternalMessageDialog(parent, title, message, - JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showInternalMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java index a7f2183..4fe23e1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalFrame.java @@ -22,7 +22,7 @@ public class SimpleInternalFrame extends JInternalFrame { * Create a new blank internal frame with a specific title * * @param title - * The title of the internal frame + * The title of the internal frame */ public SimpleInternalFrame(String title) { super(title); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java index 136c662..0cac1c9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java @@ -15,10 +15,10 @@ public class SimpleJList { * Create a new JList from a given list. * * @param <E> - * The type of data in the JList + * The type of data in the JList * * @param source - * The list to populate the JList with. + * The list to populate the JList with. * @return A JList populated with the elements from ls. */ public static <E> JList<E> buildFromList(Iterable<E> source) { @@ -33,10 +33,10 @@ public class SimpleJList { * Create a new list model from a given list. * * @param <E> - * The type of data in the list model + * The type of data in the list model * * @param source - * The list to fill the list model from. + * The list to fill the list model from. * @return A list model populated with the elements from ls. */ public static <E> ListModel<E> buildModel(Iterable<E> source) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java index e2fd390..75d89e7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java @@ -17,7 +17,7 @@ public class SimpleTitledBorder extends TitledBorder { * Create a new border with the specified title. * * @param title - * The title for the border. + * The title for the border. */ public SimpleTitledBorder(String title) { super(new EtchedBorder(), title); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java index 6ff716b..2fab8be 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java @@ -18,7 +18,7 @@ public class TextAreaOutputStream extends OutputStream { * Create a new output stream attached to a textarea * * @param console - * The textarea to write to + * The textarea to write to */ public TextAreaOutputStream(JTextArea console) { this.textArea = console; diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java index a375a98..0990f4f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java @@ -22,11 +22,10 @@ public class ExtensionFileFilter implements FilenameFilter { private IList<String> extensions; /** - * Create a new filter only showing files with the specified - * extensions. + * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(List<String> exts) { if (exts == null) { @@ -37,11 +36,10 @@ public class ExtensionFileFilter implements FilenameFilter { } /** - * Create a new filter only showing files with the specified - * extensions. + * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(String... exts) { extensions = new FunctionalList<>(exts); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java index 280c5d8..041a9a2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java @@ -20,9 +20,9 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open * * @param parent - * The parent of the file picker + * The parent of the file picker * @param title - * The title of the file picker + * The title of the file picker * @return The file the user picked */ public static File getOpenFile(Frame parent, String title) { @@ -33,23 +33,21 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open * * @param parent - * The parent of the file picker + * The parent of the file picker * @param title - * The title of the file picker + * The title of the file picker * @param extensions - * The extensions to accept as valid + * The extensions to accept as valid * @return The file the user picked */ - public static File getOpenFile(Frame parent, String title, - String... extensions) { + public static File getOpenFile(Frame parent, String title, String... extensions) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); } - FileDialog chooser = new FileDialog(parent, title, - FileDialog.LOAD); + FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); @@ -59,8 +57,7 @@ public class SimpleFileDialog { chooser.setVisible(true); while (chooser.getFile() == null) { - SimpleDialogs.showError(parent, "File I/O Error", - "Please choose a file to open."); + SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -71,23 +68,21 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open * * @param parent - * The parent of the file picker + * The parent of the file picker * @param title - * The title of the file picker + * The title of the file picker * @param extensions - * The extensions to accept as valid + * The extensions to accept as valid * @return The file the user picked */ - public static File[] getOpenFiles(Frame parent, String title, - String... extensions) { + public static File[] getOpenFiles(Frame parent, String title, String... extensions) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); } - FileDialog chooser = new FileDialog(parent, title, - FileDialog.LOAD); + FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); @@ -98,8 +93,7 @@ public class SimpleFileDialog { chooser.setVisible(true); while (chooser.getFile() == null) { - SimpleDialogs.showError(parent, "File I/O Error", - "Please choose a file to open."); + SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -110,9 +104,9 @@ public class SimpleFileDialog { * Prompt the user to pick a file to save * * @param parent - * The parent of the file picker + * The parent of the file picker * @param title - * The title of the file picker + * The title of the file picker * @return The file the user picked */ public static File getSaveFile(Frame parent, String title) { @@ -123,23 +117,21 @@ public class SimpleFileDialog { * Prompt the user to pick a file to save * * @param parent - * The parent of the file picker + * The parent of the file picker * @param title - * The title of the file picker + * The title of the file picker * @param extensions - * The extensions to accept as valid + * The extensions to accept as valid * @return The file the user picked */ - public static File getSaveFile(Frame parent, String title, - String... extensions) { + public static File getSaveFile(Frame parent, String title, String... extensions) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); } - FileDialog chooser = new FileDialog(parent, title, - FileDialog.SAVE); + FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); @@ -149,8 +141,7 @@ public class SimpleFileDialog { chooser.setVisible(true); while (chooser.getFile() == null) { - SimpleDialogs.showError(parent, "File I/O Error", - "Please choose a file to save to."); + SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to."); chooser.setVisible(true); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java index d8a60ed..07acd56 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java @@ -3,8 +3,8 @@ package bjc.utils.gui.layout; import java.awt.GridLayout; /** - * A layout that simply holds one component that it auto-resizes whenever - * it is resized. + * A layout that simply holds one component that it auto-resizes whenever it is + * resized. * * @author ben * diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java index c986310..3380321 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java @@ -3,8 +3,8 @@ package bjc.utils.gui.layout; import java.awt.GridLayout; /** - * A layout manager that lays out its components horizontally, evenly - * sizing them. + * A layout manager that lays out its components horizontally, evenly sizing + * them. * * @author ben * @@ -17,7 +17,7 @@ public class HLayout extends GridLayout { * Create a new horizontal layout with the specified number of columns. * * @param columns - * The number of columns in this layout. + * The number of columns in this layout. */ public HLayout(int columns) { super(1, columns); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java index 5951ba5..fdae31e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java @@ -3,8 +3,8 @@ package bjc.utils.gui.layout; import java.awt.GridLayout; /** - * A layout that lays out its components vertically, evenly sharing space - * among them. + * A layout that lays out its components vertically, evenly sharing space among + * them. * * @author ben * @@ -17,7 +17,7 @@ public class VLayout extends GridLayout { * Create a new vertical layout with the specified number of rows. * * @param rows - * The number of rows. + * The number of rows. */ public VLayout(int rows) { super(rows, 1); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java index 895faa6..f2d7f7b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java @@ -26,16 +26,15 @@ public class DropdownListPanel extends JPanel { * Create a new dropdown list panel * * @param <T> - * The type of items in the dropdown list + * The type of items in the dropdown list * @param type - * The label of the type of items in the list + * The label of the type of items in the list * @param model - * The model to put items into + * The model to put items into * @param choices - * The items to choose from + * The items to choose from */ - public <T> DropdownListPanel(String type, - DefaultListModel<T> model, IList<T> choices) { + public <T> DropdownListPanel(String type, DefaultListModel<T> model, IList<T> choices) { setLayout(new AutosizeLayout()); JPanel itemInputPanel = new JPanel(); @@ -58,8 +57,7 @@ public class DropdownListPanel extends JPanel { JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { - model.addElement( - addItemBox.getItemAt(addItemBox.getSelectedIndex())); + model.addElement(addItemBox.getItemAt(addItemBox.getSelectedIndex())); }); removeItemButton.addActionListener((ev) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java index a05c06e..ae62a43 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java @@ -15,29 +15,27 @@ import bjc.utils.gui.layout.HLayout; * @author ben * * @param <InputVal> - * The type of value being formatted + * The type of value being formatted */ public class FormattedInputPanel<InputVal> extends JPanel { - private static final long serialVersionUID = 5232016563558588031L; + private static final long serialVersionUID = 5232016563558588031L; - private JFormattedTextField field; + private JFormattedTextField field; /** * Create a new formatted input panel * * @param label - * The label for this panel + * The label for this panel * @param length - * The length of this panel + * The length of this panel * @param formatter - * The formatter to use for input + * The formatter to use for input * @param reciever - * The action to call whenever the value changes + * The action to call whenever the value changes */ @SuppressWarnings("unchecked") - public FormattedInputPanel(String label, int length, - AbstractFormatter formatter, - Consumer<InputVal> reciever) { + public FormattedInputPanel(String label, int length, AbstractFormatter formatter, Consumer<InputVal> reciever) { setLayout(new HLayout(2)); JLabel lab = new JLabel(label); @@ -59,7 +57,7 @@ public class FormattedInputPanel<InputVal> extends JPanel { * Reset the value in this panel to a specified value * * @param value - * The value to set the panel to + * The value to set the panel to */ public void resetValues(InputVal value) { field.setValue(value); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java index f7f2c26..b6fc807 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java @@ -14,25 +14,24 @@ import bjc.utils.gui.layout.HLayout; * */ public class HolderOutputPanel extends JPanel { - private static final long serialVersionUID = 166573313903782080L; + private static final long serialVersionUID = 166573313903782080L; - private Timer updater; - private JLabel value; - private int nDelay; - private IHolder<String> val; + private Timer updater; + private JLabel value; + private int nDelay; + private IHolder<String> val; /** * Create a new display panel, backed by a holder * * @param lab - * The label to attach to this field + * The label to attach to this field * @param valueHolder - * The holder to get the value from + * The holder to get the value from * @param nDelay - * The delay in ms between value updates + * The delay in ms between value updates */ - public HolderOutputPanel(String lab, IHolder<String> valueHolder, - int nDelay) { + public HolderOutputPanel(String lab, IHolder<String> valueHolder, int nDelay) { this.val = valueHolder; this.nDelay = nDelay; diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java index 088be6c..29ede89 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java @@ -20,7 +20,7 @@ import bjc.utils.gui.layout.VLayout; * @author ben * * @param <E> - * The type of data stored in the list + * The type of data stored in the list */ public class ListParameterPanel<E> extends JPanel { // Version id for serialization @@ -30,14 +30,13 @@ public class ListParameterPanel<E> extends JPanel { * Create a new panel using the specified actions for doing things * * @param add - * The action that provides items + * The action that provides items * @param edit - * The action that edits items + * The action that edits items * @param remove - * The action that removes items + * The action that removes items */ - public ListParameterPanel(Supplier<E> add, - Consumer<E> edit, Consumer<E> remove) { + public ListParameterPanel(Supplier<E> add, Consumer<E> edit, Consumer<E> remove) { this(add, edit, remove, null); } @@ -45,17 +44,15 @@ public class ListParameterPanel<E> extends JPanel { * Create a new panel using the specified actions for doing things * * @param add - * The action that provides items + * The action that provides items * @param edit - * The action that edits items + * The action that edits items * @param remove - * The action that removes items + * The action that removes items * @param defaults - * The default values to put in the list + * The default values to put in the list */ - public ListParameterPanel(Supplier<E> add, - Consumer<E> edit, Consumer<E> remove, - IList<E> defaults) { + public ListParameterPanel(Supplier<E> add, Consumer<E> edit, Consumer<E> remove, IList<E> defaults) { setLayout(new VLayout(2)); JList<E> list; @@ -91,8 +88,7 @@ public class ListParameterPanel<E> extends JPanel { if (add != null) { addParam = new JButton("Add..."); addParam.addActionListener((event) -> { - DefaultListModel< - E> model = (DefaultListModel<E>) list.getModel(); + DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); model.addElement(add.get()); }); @@ -112,8 +108,7 @@ public class ListParameterPanel<E> extends JPanel { if (remove != null) { removeParam = new JButton("Remove..."); removeParam.addActionListener((event) -> { - DefaultListModel< - E> model = (DefaultListModel<E>) list.getModel(); + DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); remove.accept(model.remove(list.getSelectedIndex())); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java index eb900aa..b90e25c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java @@ -8,21 +8,25 @@ import javax.swing.JTextField; /** * A simple component for text input + * * @author ben * */ public class SimpleInputPanel extends JPanel { - private static final long serialVersionUID = -4734279623645236868L; + private static final long serialVersionUID = -4734279623645236868L; /** * The text field containing the input value */ - public final JTextField inputValue; + public final JTextField inputValue; /** * Create a new input panel - * @param label The label for the field - * @param columns The number of columns of text input to take + * + * @param label + * The label for the field + * @param columns + * The number of columns of text input to take */ public SimpleInputPanel(String label, int columns) { setLayout(new BorderLayout()); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java index 48230dd..11b209f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java @@ -24,10 +24,8 @@ import bjc.utils.gui.layout.HLayout; public class SimpleListPanel extends JPanel { private static final long serialVersionUID = 2719963952350133541L; - private static void addItem(DefaultListModel<String> model, - Predicate<String> verifier, - Consumer<String> onFailure, - JTextField addItemField) { + private static void addItem(DefaultListModel<String> model, Predicate<String> verifier, + Consumer<String> onFailure, JTextField addItemField) { String potentialItem = addItemField.getText(); if (verifier == null || verifier.test(potentialItem)) { @@ -43,17 +41,15 @@ public class SimpleListPanel extends JPanel { * Create a new list panel * * @param type - * The type of things in the list + * The type of things in the list * @param model - * The model to put items into + * The model to put items into * @param verifier - * The predicate to use to verify items + * The predicate to use to verify items * @param onFailure - * The function to call when an item doesn't verify + * The function to call when an item doesn't verify */ - public SimpleListPanel(String type, - DefaultListModel<String> model, - Predicate<String> verifier, + public SimpleListPanel(String type, DefaultListModel<String> model, Predicate<String> verifier, Consumer<String> onFailure) { setLayout(new AutosizeLayout()); @@ -77,13 +73,11 @@ public class SimpleListPanel extends JPanel { JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { - addItem(model, verifier, onFailure, - addItemField); + addItem(model, verifier, onFailure, addItemField); }); addItemField.addActionListener((ev) -> { - addItem(model, verifier, onFailure, - addItemField); + addItem(model, verifier, onFailure, addItemField); }); removeItemButton.addActionListener((ev) -> { diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java index 5996b65..e9e94d5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java @@ -9,21 +9,25 @@ import javax.swing.SpinnerModel; /** * A simple spinner control + * * @author ben * */ public class SimpleSpinnerPanel extends JPanel { - private static final long serialVersionUID = -4734279623645236868L; + private static final long serialVersionUID = -4734279623645236868L; /* * The spinner being used */ - public final JSpinner inputValue; + public final JSpinner inputValue; /** * Create a new spinner panel - * @param label The label for the spinner - * @param model The model to attach to the spinner + * + * @param label + * The label for the spinner + * @param model + * The model to attach to the spinner */ public SimpleSpinnerPanel(String label, SpinnerModel model) { setLayout(new BorderLayout()); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java index 9de4d63..53bff32 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java @@ -11,21 +11,20 @@ import javax.swing.JSlider; import bjc.utils.gui.layout.HLayout; /** - * A simple input panel for a slider-controlled value and a manual-input - * field for setting the slider + * A simple input panel for a slider-controlled value and a manual-input field + * for setting the slider * * @author ben * */ public class SliderInputPanel extends JPanel { - private final class NumberFormatter - extends JFormattedTextField.AbstractFormatter { - private static final long serialVersionUID = -4448291795913908270L; + private final class NumberFormatter extends JFormattedTextField.AbstractFormatter { + private static final long serialVersionUID = -4448291795913908270L; - private int minValue; - private int maxValue; + private int minValue; + private int maxValue; - private int initValue; + private int initValue; public NumberFormatter(SliderSettings settings) { minValue = settings.minValue; @@ -40,17 +39,14 @@ public class SliderInputPanel extends JPanel { int val = Integer.parseInt(text); if (val < minValue) { - throw new ParseException( - "Value must be greater than " + minValue, 0); + throw new ParseException("Value must be greater than " + minValue, 0); } else if (val > maxValue) { - throw new ParseException( - "Value must be smaller than " + maxValue, 0); + throw new ParseException("Value must be smaller than " + maxValue, 0); } else { return val; } } catch (NumberFormatException nfex) { - ParseException pex = new ParseException( - "Value must be a valid integer", 0); + ParseException pex = new ParseException("Value must be a valid integer", 0); pex.initCause(nfex); @@ -78,25 +74,25 @@ public class SliderInputPanel extends JPanel { /** * The minimum value of the slider */ - public final int minValue; + public final int minValue; /** * The maximum value of the slider */ - public final int maxValue; + public final int maxValue; /** * The initial value of the slider */ - public final int initValue; + public final int initValue; /** * Create a new slider settings, with the initial value in the * middle * * @param min - * The minimum value of the slider + * The minimum value of the slider * @param max - * The maximum value of the slider + * The maximum value of the slider */ public SliderSettings(int min, int max) { this(min, max, (min + max) / 2); @@ -106,11 +102,11 @@ public class SliderInputPanel extends JPanel { * Create a new set of slider sttings * * @param min - * The minimum slider value + * The minimum slider value * @param max - * The maximum slider value + * The maximum slider value * @param init - * Th initial slider value + * Th initial slider value */ public SliderSettings(int min, int max, int init) { minValue = min; @@ -120,32 +116,31 @@ public class SliderInputPanel extends JPanel { } } - private static final long serialVersionUID = 2956394160569961404L; - private JSlider slider; - private JFormattedTextField field; + private static final long serialVersionUID = 2956394160569961404L; + private JSlider slider; + private JFormattedTextField field; /** * Create a new slider input panel * * @param lab - * The label for the field + * The label for the field * @param settings - * The settings for slider values + * The settings for slider values * @param majorTick - * The setting for where to place big ticks + * The setting for where to place big ticks * @param minorTick - * The setting for where to place small ticks + * The setting for where to place small ticks * @param action - * The action to execute for a given value + * The action to execute for a given value */ - public SliderInputPanel(String lab, SliderSettings settings, - int majorTick, int minorTick, Consumer<Integer> action) { + public SliderInputPanel(String lab, SliderSettings settings, int majorTick, int minorTick, + Consumer<Integer> action) { setLayout(new HLayout(3)); JLabel label = new JLabel(lab); - slider = new JSlider(settings.minValue, settings.maxValue, - settings.initValue); + slider = new JSlider(settings.minValue, settings.maxValue, settings.initValue); field = new JFormattedTextField(new NumberFormatter(settings)); slider.setMajorTickSpacing(majorTick); @@ -186,7 +181,7 @@ public class SliderInputPanel extends JPanel { * Reset the values in this panel to a specified value * * @param value - * The value to reset the fields to + * The value to reset the fields to */ public void resetValues(int value) { slider.setValue(value); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java index 31ceecd..a9efe9b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -12,7 +12,7 @@ public interface IPrecedent { * Create a new object with set precedence * * @param precedence - * The precedence of the object to handle + * The precedence of the object to handle * @return A new object with set precedence */ public static IPrecedent newSimplePrecedent(int precedence) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java index 9418862..2da4f7e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java @@ -16,20 +16,21 @@ import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IMap; /** - * This class parses a rules based config file, and uses it to drive a - * provided set of actions + * This class parses a rules based config file, and uses it to drive a provided + * set of actions * * @author ben * * @param <E> - * The type of the state object to use + * The type of the state object to use * */ public class RuleBasedConfigReader<E> { // Function to execute when starting a rule - // Takes the tokenizer, and a pair of the read token and application state + // Takes the tokenizer, and a pair of the read token and application + // state private BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start; - + // Function to use when continuing a rule // Takes a tokenizer and application state private BiConsumer<FunctionalStringTokenizer, E> continueRule; @@ -46,16 +47,14 @@ public class RuleBasedConfigReader<E> { * Create a new rule-based config reader * * @param start - * The action to fire when starting a rule + * The action to fire when starting a rule * @param continueRule - * The action to fire when continuing a rule + * The action to fire when continuing a rule * @param end - * The action to fire when ending a rule + * The action to fire when ending a rule */ - public RuleBasedConfigReader( - BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, - BiConsumer<FunctionalStringTokenizer, E> continueRule, - Consumer<E> end) { + public RuleBasedConfigReader(BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, + BiConsumer<FunctionalStringTokenizer, E> continueRule, Consumer<E> end) { this.start = start; this.continueRule = continueRule; this.end = end; @@ -67,13 +66,11 @@ public class RuleBasedConfigReader<E> { * Add a pragma to this reader * * @param name - * The name of the pragma to add + * The name of the pragma to add * @param action - * The function to execute when this pragma is read + * The function to execute when this pragma is read */ - public void addPragma( - String name, - BiConsumer<FunctionalStringTokenizer, E> action) { + public void addPragma(String name, BiConsumer<FunctionalStringTokenizer, E> action) { if (name == null) { throw new NullPointerException("Pragma name must not be null"); } else if (action == null) { @@ -116,9 +113,9 @@ public class RuleBasedConfigReader<E> { * Run a stream through this reader * * @param input - * The stream to get input + * The stream to get input * @param initialState - * The initial state of the reader + * The initial state of the reader * @return The final state of the reader */ public E fromStream(InputStream input, E initialState) { @@ -143,15 +140,13 @@ public class RuleBasedConfigReader<E> { return; } else if (line.equals("")) { // End the rule - isRuleOpen.replace( - endRule(state, isRuleOpen.getValue())); + isRuleOpen.replace(endRule(state, isRuleOpen.getValue())); } else if (line.startsWith("\t")) { // Continue the rule continueRule(state, isRuleOpen.getValue(), line); } else { // Open a rule - isRuleOpen.replace( - startRule(state, isRuleOpen.getValue(), line)); + isRuleOpen.replace(startRule(state, isRuleOpen.getValue(), line)); } }); } @@ -165,10 +160,9 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when continuing a rule * * @param continueRule - * The action to execute on continuation of a rule + * The action to execute on continuation of a rule */ - public void setContinueRule( - BiConsumer<FunctionalStringTokenizer, E> continueRule) { + public void setContinueRule(BiConsumer<FunctionalStringTokenizer, E> continueRule) { this.continueRule = continueRule; } @@ -176,7 +170,7 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when ending a rule * * @param end - * The action to execute on ending of a rule + * The action to execute on ending of a rule */ public void setEndRule(Consumer<E> end) { this.end = end; @@ -186,7 +180,7 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when starting a rule * * @param start - * The action to execute on starting of a rule + * The action to execute on starting of a rule */ public void setStartRule(BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) { if (start == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java index eef55a8..6c660c6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java @@ -18,21 +18,19 @@ public class RuleBasedReaderPragmas { * Creates a pragma that takes a single integer argument * * @param <StateType> - * The type of state that goes along with this pragma + * The type of state that goes along with this pragma * @param name - * The name of this pragma, for error message purpose + * The name of this pragma, for error message purpose * @param consumer - * The function to invoke with the parsed integer + * The function to invoke with the parsed integer * @return A pragma that functions as described above. */ - public static <StateType> BiConsumer<FunctionalStringTokenizer, - StateType> buildInteger(String name, - BiConsumer<Integer, StateType> consumer) { + public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildInteger(String name, + BiConsumer<Integer, StateType> consumer) { return (tokenizer, state) -> { // Check our input is correct if (!tokenizer.hasMoreTokens()) { - throw new PragmaFormatException("Pragma " + name - + " requires one integer argument"); + throw new PragmaFormatException("Pragma " + name + " requires one integer argument"); } // Read the argument @@ -44,8 +42,7 @@ public class RuleBasedReaderPragmas { } catch (NumberFormatException nfex) { // Tell the user their argument isn't correct PragmaFormatException pfex = new PragmaFormatException( - "Argument " + token - + " to " + name + " pragma isn't a valid integer. " + "Argument " + token + " to " + name + " pragma isn't a valid integer. " + "This pragma requires a integer argument"); pfex.initCause(nfex); @@ -60,21 +57,20 @@ public class RuleBasedReaderPragmas { * them all into a single string * * @param <StateType> - * The type of state that goes along with this pragma + * The type of state that goes along with this pragma * @param name - * The name of this pragma, for error message purpose + * The name of this pragma, for error message purpose * @param consumer - * The function to invoke with the parsed string + * The function to invoke with the parsed string * @return A pragma that functions as described above. */ - public static <StateType> BiConsumer<FunctionalStringTokenizer, - StateType> buildStringCollapser(String name, - BiConsumer<String, StateType> consumer) { + public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildStringCollapser(String name, + BiConsumer<String, StateType> consumer) { return (tokenizer, state) -> { // Check our input if (!tokenizer.hasMoreTokens()) { - throw new PragmaFormatException("Pragma " + name - + " requires one or more string arguments"); + throw new PragmaFormatException( + "Pragma " + name + " requires one or more string arguments"); } // Build our argument diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java index fe046f4..19c1971 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -17,7 +17,7 @@ import bjc.utils.funcutils.StringUtils; * @author ben * * @param <TokenType> - * The type of tokens being shunted + * The type of tokens being shunted */ public class ShuntingYard<TokenType> { /** @@ -58,9 +58,9 @@ public class ShuntingYard<TokenType> { } private final class TokenShunter implements Consumer<String> { - private IList<TokenType> output; - private Deque<String> stack; - private Function<String, TokenType> transformer; + private IList<TokenType> output; + private Deque<String> stack; + private Function<String, TokenType> transformer; public TokenShunter(IList<TokenType> outpt, Deque<String> stack, Function<String, TokenType> transformer) { @@ -73,19 +73,21 @@ public class ShuntingYard<TokenType> { public void accept(String token) { // Handle operators if (operators.containsKey(token)) { - // Pop operators while there isn't a higher precedence one - while (!stack.isEmpty() - && isHigherPrec(token, stack.peek())) { + // Pop operators while there isn't a higher + // precedence one + while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) { output.add(transformer.apply(stack.pop())); } // Put this operator onto the stack stack.push(token); } else if (StringUtils.containsOnly(token, "\\(")) { - // Handle groups of parenthesis for multiple nesting levels + // Handle groups of parenthesis for multiple + // nesting levels stack.push(token); } else if (StringUtils.containsOnly(token, "\\)")) { - // Handle groups of parenthesis for multiple nesting levels + // Handle groups of parenthesis for multiple + // nesting levels String swappedToken = token.replace(')', '('); // Remove tokens up to a matching parenthesis @@ -111,7 +113,7 @@ public class ShuntingYard<TokenType> { * Create a new shunting yard with a default set of operators * * @param configureBasics - * Whether or not basic math operators should be provided + * Whether or not basic math operators should be provided */ public ShuntingYard(boolean configureBasics) { operators = new FunctionalMap<>(); @@ -129,9 +131,9 @@ public class ShuntingYard<TokenType> { * Add an operator to the list of shuntable operators * * @param operatorToken - * The token representing the operator + * The token representing the operator * @param precedence - * The precedence of the operator to add + * The precedence of the operator to add */ public void addOp(String operator, int precedence) { // Create the precedence marker @@ -144,15 +146,15 @@ public class ShuntingYard<TokenType> { * Add an operator to the list of shuntable operators * * @param operatorToken - * The token representing the operator + * The token representing the operator * @param precedence - * The precedence of the operator + * The precedence of the operator */ public void addOp(String operator, IPrecedent precedence) { // Complain about trying to add an incorrect operator if (operator == null) { throw new NullPointerException("Operator must not be null"); - } else if(precedence == null) { + } else if (precedence == null) { throw new NullPointerException("Precedence must not be null"); } @@ -181,13 +183,12 @@ public class ShuntingYard<TokenType> { * Transform a string of tokens from infix notation to postfix * * @param input - * The string to transform + * The string to transform * @param transformer - * The function to use to transform strings to tokens + * The function to use to transform strings to tokens * @return A list of tokens in postfix notation */ - public IList<TokenType> postfix(IList<String> input, - Function<String, TokenType> transformer) { + public IList<TokenType> postfix(IList<String> input, Function<String, TokenType> transformer) { // Check our input if (input == null) { throw new NullPointerException("Input must not be null"); @@ -216,8 +217,8 @@ public class ShuntingYard<TokenType> { * Remove an operator from the list of shuntable operators * * @param token - * The token representing the operator. If null, remove all - * operators + * The token representing the operator. If null, remove + * all operators */ public void removeOp(String operator) { // Check if we want to remove all operators diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java index 9953c00..1a4a6c4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java @@ -14,8 +14,7 @@ import bjc.utils.data.Tree; final class TokenTransformer<TokenType> implements Consumer<TokenType> { // Handle operators - private final class OperatorHandler implements UnaryOperator< - IPair<Deque<ITree<TokenType>>, ITree<TokenType>>> { + private final class OperatorHandler implements UnaryOperator<IPair<Deque<ITree<TokenType>>, ITree<TokenType>>> { private TokenType element; public OperatorHandler(TokenType element) { @@ -25,24 +24,24 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { @Override public IPair<Deque<ITree<TokenType>>, ITree<TokenType>> apply( IPair<Deque<ITree<TokenType>>, ITree<TokenType>> pair) { - // Replace the current AST with the result of handling an operator + // Replace the current AST with the result of handling + // an operator return pair.bindLeft((queuedASTs) -> { return handleOperator(queuedASTs); }); } - private IPair<Deque<ITree<TokenType>>, - ITree<TokenType>> handleOperator( - Deque<ITree<TokenType>> queuedASTs) { + private IPair<Deque<ITree<TokenType>>, ITree<TokenType>> handleOperator( + Deque<ITree<TokenType>> queuedASTs) { // The AST we're going to hand back ITree<TokenType> newAST; // Handle special operators if (isSpecialOperator.test(element)) { - newAST = handleSpecialOperator.apply(element) - .apply(queuedASTs); + newAST = handleSpecialOperator.apply(element).apply(queuedASTs); } else { - // Error if we don't have enough for a binary operator + // Error if we don't have enough for a binary + // operator if (queuedASTs.size() < 2) { throw new IllegalStateException( "Attempted to parse binary operator without enough operands.\n" @@ -67,25 +66,17 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { } } - private IHolder<IPair<Deque<ITree<TokenType>>, - ITree<TokenType>>> initialState; + private IHolder<IPair<Deque<ITree<TokenType>>, ITree<TokenType>>> initialState; - private Predicate< - TokenType> operatorPredicate; + private Predicate<TokenType> operatorPredicate; - private Predicate< - TokenType> isSpecialOperator; - private Function<TokenType, Function<Deque<ITree<TokenType>>, - ITree<TokenType>>> handleSpecialOperator; + private Predicate<TokenType> isSpecialOperator; + private Function<TokenType, Function<Deque<ITree<TokenType>>, ITree<TokenType>>> handleSpecialOperator; // Create a new transformer - public TokenTransformer( - IHolder<IPair<Deque<ITree<TokenType>>, - ITree<TokenType>>> initialState, - Predicate<TokenType> operatorPredicate, - Predicate<TokenType> isSpecialOperator, - Function<TokenType, Function<Deque<ITree<TokenType>>, - ITree<TokenType>>> handleSpecialOperator) { + public TokenTransformer(IHolder<IPair<Deque<ITree<TokenType>>, ITree<TokenType>>> initialState, + Predicate<TokenType> operatorPredicate, Predicate<TokenType> isSpecialOperator, + Function<TokenType, Function<Deque<ITree<TokenType>>, ITree<TokenType>>> handleSpecialOperator) { this.initialState = initialState; this.operatorPredicate = operatorPredicate; this.isSpecialOperator = isSpecialOperator; @@ -102,7 +93,8 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { // Insert the new tree into the AST initialState.transform((pair) -> { - // Transform the pair, ignoring the current AST in favor of the + // Transform the pair, ignoring the current AST + // in favor of the // one consisting of the current element return pair.bindLeft((queue) -> { queue.push(newAST); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 7f933c0..6f4e384 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -25,20 +25,18 @@ public class TreeConstructor { * Only binary operators are accepted. * * @param <TokenType> - * The elements of the parse tree + * The elements of the parse tree * @param tokens - * The list of tokens to build a tree from + * The list of tokens to build a tree from * @param isOperator - * The predicate to use to determine if something is a - * operator + * The predicate to use to determine if something is a + * operator * @return A AST from the expression */ - public static <TokenType> ITree<TokenType> constructTree( - IList<TokenType> tokens, + public static <TokenType> ITree<TokenType> constructTree(IList<TokenType> tokens, Predicate<TokenType> isOperator) { // Construct a tree with no special operators - return constructTree(tokens, isOperator, (op) -> false, - null); + return constructTree(tokens, isOperator, (op) -> false, null); } /** @@ -48,49 +46,42 @@ public class TreeConstructor { * parameters to handle non-binary operators * * @param <TokenType> - * The elements of the parse tree + * The elements of the parse tree * @param tokens - * The list of tokens to build a tree from + * The list of tokens to build a tree from * @param isOperator - * The predicate to use to determine if something is a - * operator + * The predicate to use to determine if something is a + * operator * @param isSpecialOperator - * The predicate to use to determine if an operator needs - * special handling + * The predicate to use to determine if an operator needs + * special handling * @param handleSpecialOperator - * The function to use to handle special case operators + * The function to use to handle special case operators * @return A AST from the expression * * FIXME The handleSpecialOp function seems like an ugly - * interface. Maybe there's a better way to express how - * that works. + * interface. Maybe there's a better way to express how that + * works. */ - public static <TokenType> ITree<TokenType> constructTree( - IList<TokenType> tokens, - Predicate<TokenType> isOperator, - Predicate<TokenType> isSpecialOperator, - Function<TokenType, Function<Deque<ITree<TokenType>>, - ITree<TokenType>>> handleSpecialOperator) { + public static <TokenType> ITree<TokenType> constructTree(IList<TokenType> tokens, + Predicate<TokenType> isOperator, Predicate<TokenType> isSpecialOperator, + Function<TokenType, Function<Deque<ITree<TokenType>>, ITree<TokenType>>> handleSpecialOperator) { // Make sure our parameters are valid if (tokens == null) { throw new NullPointerException("Tokens must not be null"); } else if (isOperator == null) { - throw new NullPointerException( - "Operator predicate must not be null"); + throw new NullPointerException("Operator predicate must not be null"); } else if (isSpecialOperator == null) { - throw new NullPointerException( - "Special operator determiner must not be null"); + throw new NullPointerException("Special operator determiner must not be null"); } // Here is the state for the tree construction - IHolder<IPair<Deque<ITree<TokenType>>, - ITree<TokenType>>> initialState = new Identity<>( - new Pair<>(new LinkedList<>(), null)); + IHolder<IPair<Deque<ITree<TokenType>>, ITree<TokenType>>> initialState = new Identity<>( + new Pair<>(new LinkedList<>(), null)); // Transform each of the tokens - tokens.forEach( - new TokenTransformer<>(initialState, isOperator, - isSpecialOperator, handleSpecialOperator)); + tokens.forEach(new TokenTransformer<>(initialState, isOperator, isSpecialOperator, + handleSpecialOperator)); // Grab the tree from the state return initialState.unwrap((pair) -> { |
