ROLLBACK undo redo - java

I'm building a database using a BST (binary search tree) and I want the user to be able to roll back the last 5 commands. Any Suggestions? I'm using Java.

Have you considered using Berkey DB? It's free and supported nested transactions (which would allow you to have any number of levels of rollback):
http://download.oracle.com/docs/cd/E17076_02/html/gsg_txn/JAVA/nestedtxn.html
Even if you decide to implement your own DB, it might be useful as a reference.

It sounds like you want the Memento pattern. Essentially, you create an object that has all of the information required to:
From the state of the tree before the operation, repeat the operation. (Redo)
From the state of the tree after the operation, revert the operation. (Undo)
You'd keep the last five of these around. When the user asks for an undo, take the latest, ask it to revert the operation, then indicate somehow (some index variable, for example) where you are in the list of mementos. You should then be able to move through the list in either direction, undoing and redoing as much as you want.

Related

What's the best way to implement an "undo" feature in photo editing application?

Obviously it takes a lot of memory to store an array of a history of changes... that's how I had my application working but it just seems like there's a smarter way to go about doing this.
ArrayList<Photo> photoHistory = new ArrayList<>();
photoHistory.add(originalPhoto);
photoHistory.add(change1);
photoHistory.add(change2);
// bad implementation - lots of memory
Maybe store only an original and a current view model and keep a log of the methods/filters used? Then when a user hits 'undo' it would take the total number of changes made and run through all of them again minus one? This also seems incredibly inefficient.
I guess I'm just looking for advice on how to implement a general 'undo' function of a software application.
Here is a tip from how GIMP implements it:
GIMP's implementation of Undo is rather sophisticated. Many operations require very little Undo memory (e.g., changing visibility of a layer), so you can perform long sequences of them before they drop out of the Undo History. Some operations, such as changing layer visibility, are compressed, so that doing them several times in a row produces only a single point in the Undo History. However, there are other operations that may consume a lot of undo memory. Most filters are implemented by plug-ins, so the GIMP core has no efficient way of knowing what changed. As such, there is no way to implement Undo except by memorizing the entire contents of the affected layer before and after the operation. You might only be able to perform a few such operations before they drop out of the Undo History.
Source
So to do it as optimally as possible, you have to do different things depending on what action is being undone. Showing or hiding a layer can be represented in a neglible amount of space, but filtering the whole image might necessitate storing another copy of the whole image. However, if you only filter part of the image (or draw in a small section of the image) perhaps you only need to store that piece of the image.

Find and delete duplicates in a Lotus Notes database

I am very new to lotus notes. Recently my team mates were facing a problem regarding the Duplicates in Lotus notes as shown below in the CASE A and CASE B.
So we bought a app named scanEZ (Link About scanEX). Using this tool we can remove the first occurrence or the second occurrence. As in the case A and Case B the second items are considered as redundant because they do not have child. So we can remove all the second item as given below and thus removing the duplicates.
But in the Case 3 the order gets changed, the child item comes first and the Parent items comes second so i am unable to use the scanEX app.
Is there any other better way or software or script to accomplish my task. As I am new to this field I have not idea. Kindly help me.
Thanks in advance.
Probably the easiest way to approach this would be to force the view to always display documents with children first. That way the tool you have purchased will behave consistently for you. You would do this by adding a hidden sorted column to the right of the column that that you have circled. The formula in this column would be #DocChildren, and the sort options for the column would be set to 'Descending'. (Note that if you are uncomfortable making changes in this view, you can make a copy of it, make your changes in the copy, and run ScanEZ against the copy as well. You can also do all of this in a local replica of the database, and only replicate it back to the server when you are satisified that you have the right results.)
The other way would be to write your own code in LotusScript or Java, using the Notes classes. There are many different ways that you could write that code,
I agree with Richard's answer. If you want more details on how to go thru the document collection you could isolate the documents into a view that shows only the duplicates. Then write an agent to look at the UNID of the document, date modified and other such data elements to insure that you are getting the last updated document. I would add a field to the document as in FLAG='keep'. Then delete documents that don't have your flag in the document with a second agent. If you take this approach you can often use the same agents in other databases.
Since you are new to Notes keep in mind that Notes is a document database. There are several different conflicts like save conflicts or replication conflicts. Also you need to look at database settings on how duplicates can be handled. I would read up on these topics just so you can explain it to your co-workers/project manager.
Eventually in your heavily travelled databases you might be able to automate this process after you work down the source of the duplicates.
These are clearly not duplicates.
The definition of duplicate is that they are identical and so it does not matter which one is kept and which one is removed. To you, the fact that one has children makes it more important, which means that they are not pure duplicates.
What you have not stated is what you want to do if multiple documents with similar dates/subjects have children (a case D if you will).
To me this appears as three separate problems.
The first problem is to sort out the cases where more than one
document in a set has children.
Then sort out the cases where only one document in a set has children.
Then sort out the cases where none of the documents in a set has children.
The approach in each case will be different. The article from Ytira only really covers the last of these cases.

What is a good Java data structure to store RPG Game items?

I'm building a RPG dungeon game in Java and I'm stuck on creating a data structure.
I have a lot of Thing objects that I can copy to populate a dungeon with. For instance, there is a bread Thing object, and a sword Thing object, a chain mail Thing object, and monster Thing(s), etc. I want to store them in a central Library and then be able to retrieve an object using certain queries. I want to store them using the following fields:
int minLevel
int maxLevel
double probability
int[] types
So a rusty sword would have a minLevel of 1, a maxLevel of 3, a probability of rarity(3%),and [type.SWORD,type.WEAPON,type.ITEM,TYPE.EQUIP]. A better sword would have minLevel 2, maxLevel 10, rarity (1%).
Then I want to retrieve a random type.SWORD from the library and say I'm at level 3. I should get a rusty sword more often than the better sword based on their probabilities. If I retrieved a type.SWORD from the library requesting level 10, I would only get back the better sword.
I hope this makes sense.
EDIT
At the initialization stage, all the basic objects will be created. Things like the available weapons, armor, foods, potions, wands, all the basic possible Things that have a unique graphic tile in the game. Then when I want to place an object somewhere, I just make a copy of one of the available Things, adjust it's stats a little, and plunk it down in the world. The actual items are all subclass of the root Thing class, such as class Creature,Item,Equip(extends Item),Weapon(extends Equip),Armor(extends Equip),Food(extends Item), etc. But I want to tag them different in the Library database, I want to use extra tags, such as type.RARE, type.ARTIFACT, type.CURSED, so I want extra tags besides the class.
The game use LIBGDX to be available on Android and as an Applet. I use the free Rltile set, which has thousands of good tiles. I will use Pubnub or Google App Engine to provide multiplayer support.
i can think of three answers:
write your own Library that stores these things in Maps with custom methods.
so you might have a Map<Type,List<Object>> that stores lists of things by type
and then a method that takes a type, retrieves the list from the map, and selects
something by probability (that's easy to do - you just some up the probabilities,
generate a random number between 0 and the sum, and then walk through the list,
subtracting the item's probability from your random value until it's negative - you
return the item that made it negative[*]). you can also filter the list first by
level, for example.
if you have a real mix of different things, and don't want to base this on types,
then another option (slower, but more flexible) is to place everything in a list
and then filter by your needs. a nice way to do that is with guava - see
Iterables.filter and Predicate at https://code.google.com/p/guava-libraries/.
you could provide an interface that takes a predicate and returns a random
selection from whatever is left after filtering. predicates are easy to construct
"inline" with anonymous classes - see examples at
https://code.google.com/p/guava-libraries/wiki/FunctionalExplained#Functions_and_Predicates
stick all this in a database. maybe i am too enterprisey, and games people would
never do this, but it seems to me that a small, embedded database like sqlite or
H2 would be perfect for this. you can then select things with SQL queries (this
is already a long answer so i won't give more details here).
change your design. what you describe is not very OO. instead of having types,
your Things could implement interfaces. so the Weapon interface would have a
getMinLevel() method, for example. and then, with a design like this, use a
database with ORM (hibernate).
what you're doing is kind of ambitious and i suspect is more about learning than anything else (no criticism intended - this is how i learn stuff, by making things, so just assuming you are like me). so choose whichever you feel most comfortable with.
[*] this assumes that you always want to return something. if the probabilities are normalized and you want to be able to return nothing, select the initial value from 0-1 (or 0-100 if using percentages). and, if nothing turns the value negative when you run through the list, return nothing.
The easiest approach is to put all your objects in a single large arraylist, and use repeated sampling to select an object.
The procedure to select a random item is very simple:
Select a random number from 0 up to the size of the ArrayList
Get the object at that index from the library
If the object fails to meet any criteria you specify (e.g. "is a of type.SWORD or type.MACE?") go back to start
If the object is outside the minimum or maximum level, go back to start
If the object has a rarity of less than 100%, create a random number from 0-100%. If the random number exceeds the object's rarity, loop back to start. Most objects should have a rarity of say 10-100%, if you want extremely common objects then you can add them multiple times to the library.
This procedure will produce an object that meets the criteria sooner or later (if it exists) and will do so according to the rarity percentage.
The one slight trickness is that it will loop infinitely if no such object exists. Suppose there is no weapon in the library at level 17 for example? To get around this, I would propose widening the minLevel and maxLevel after every 100 tries to ensure that eventually one is found. Ensure you always have a level 1 object of each type available.
For safety, you might also want a bailout after say 100,000 tries (but remember to throw an exception - this is a problem if you are asking for things that don't exist in the library!).
P.S. I implemented a similar library system in a roguelike game called Tyrant that I created many years ago. Source is here if you are interersted:
https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/engine/Lib.java

Pre-populating input in Java console

I'm making a console-based Java/Groovy application that does a lot of find/replaces in text files. If, say, the program knows you replaced foo with bar last time, it should by default know you probably want to replace the next foo with bar as well. My idea was to pre-populate the input field of the What would you like to rename this to? prompt so that you don't have to retype it unnecessarily, but I can't find an easy way to do this in Java.
Is this possible, and if so, would it be a recommended practice?
Why don't you just assume that an empty imput is equal to the last input inserted? It would be quite easier to manage that pre-filling a stdin..
in any case if you plan to have a recent list I would suggest you to have a special character combination to tell last one or the previous and so on.
There are a lot of useful approaches to this problem. You can remember only the last value the user replaced, or you can mantain a cache with the last n replacements, in case the user requests a similar replacement. Or you can ignore the previous input and force the user to provide a replacement every time you need. The right approach depends on the frequency of the replacement operations, if the user replaces the same value very often, etc. You have to choose the right solution depending on your problem domain and on the kind of interaction you want to provide to the user.
Implementing these solutions is simple. The most intuitive is saving the replacement cache in a simple text file, loading it during startup and saving the cache at the shutdown. The replacement cache can also be serialized to the file, insted of being written as plain text.

Java TreeNode: How to prevent getChildCount from doing expensive operation?

I'm writing a Java Tree in which tree nodes could have children that take a long time to compute (in this case, it's a file system, where there may be network timeouts that prevent getting a list of files from an attached drive).
The problem I'm finding is this:
getChildCount() is called before the user specifically requests opening a particular branch of the tree. I believe this is done so the JTree knows whether to show a + icon next to the node.
An accurate count of children from getChildCount() would need to perform the potentially expensive operation
If I fake the value of getChildCount(), the tree only allocates space for that many child nodes before asking for an enumeration of the children. (If I return '1', I'll only see 1 child listed, despite that there are more)
The enumeration of the children can be expensive and time-consuming, I'm okay with that. But I'm not okay with getChildCount() needing to know the exact number of children.
Any way I can work around this?
Added: The other problem is that if one of the nodes represents a floppy drive (how archaic!), the drive will be polled before the user asks for its files; if there's no disk in the drive, this results in a system error.
Update: Unfortunately, implementing the TreeWillExpand listener isn't the solution. That can allow you to veto an expansion, but the number of nodes shown is still restricted by the value returned by TreeNode.getChildCount().
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data
scroll a little down, there is the exact tutorial on how to create lazy loading nodes for the jtree, complete with examples and documentation
I'm not sure if it's entirely applicable, but I recently worked around problems with a slow tree by pre-computing the answers to methods that would normally require going through the list of children. I only recompute them when children are added or removed or updated. In my case, some of the methods would have had to go recursively down the tree to figure out things like 'how many bytes are stored' for each node.
If you need a lot of access to a particular feature of your data structure that is expensive to compute, it may make sense to pre-compute it.
In the case of TreeNodes, this means that your TreeNodes would have to store their Child count. To explain it a bit more in detail: when you create a node n0 this node has a childcount (cc) of 0. When you add a node n1 as a child of this one, you n1.cc + cc++.
The tricky bit is the remove operation. You have to keep backlinks to parents and go up the hierarchy to subtract the cc of your current node.
In case you just want to have the a hasChildren feature for your nodes or override getChildCount, a boolean might be enough and would not force you to go up the whole hierarchy in case of removal. Or you could remove the backlinks and just say that you lose precision on remove operations. The TreeNode interface actually doesn't force you to provide a remove operation, but you probably want one anyway.
Well, that's the deal. In order to come up with precomputed precise values, you will have to keep backlinks of some sorts. If you don't you'd better call your method hasHadChildren or the more amusing isVirgin.
There are a few parts to the solution:
Like Lorenzo Boccaccia said, use the TreeWillExpandListener
Also, need to call nodesWereInserted on the tree, so the proper number of nodes will be displayed. See this code
I have determined that if you don't know the child count, TreeNode.getChildCount() needs to return at least 1 (it can't return 0)

Categories