HashMap intermediateIdMap = new HashMap(d_idMap.size());
int linkCounter = 0;
for (Iterator it = d_idMap.entrySet().iterator(); it.hasNext(); )
{
Map.Entry me = ((Map.Entry) it.next());
long oldId = (Long) me.getKey();
MapObject mo = d_mc.findMapObject(oldId);
if (mo != null && !isMetaDataType(mo)
&& (IdSpace.isTransient(mo.id()) || d_updateAllIds
|| isNegativeIdUpdate(mo.id())))
{
int transientId = d_idGenerator.getNewId();
I need to get the first transientId when its executed for the very first time and the Id it sets and also the last Id i.e MIN_TRANSIENT and MAX_TRANSIENT
I tried changing the Data Structure to LinkedHashMap which would have given me the 1st and Last element easily but i guess seniors dont want me to change the ds, do you guys help me find an another way
public synchronized int getNewId()
{
// Contract.precondition("Within range", d_currentId <= d_range);
// CMSDL-3988 - recycle/reset the currentId once max reached
if(d_currentId>d_range)
d_currentId=MIN_TRANSIENT;
return d_currentId++;
}
If you need changes for a reason, you should be allowed to do them.
Otherwise, you need some structure around your code such as
boolean firstValueSeen = false;
int firstValue = -1;
for (…) {
…
int transientId = d_idGenerator.getNewId();
firstValueSeen = true;
firstValue = transientId
Related
I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?
CODE
public HashMap<String, Integer> getDataPoint() {
//My function code
HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
int janCounter = 0;
int febCounter = 0;
int marCounter = 0;
int aprCounter = 0;
int mayCounter = 0;
int juneCounter = 0;
int julyCounter = 0;
int augCounter = 0;
int septCounter = 0;
int octCounter = 0;
int novCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
OpenCsvReader reader = new OpenCsvReader();
ArrayList <STPost> STArray = reader.loadST("file_path");
Iterator STitr = STArray.iterator();
while (STitr.hasNext()) {
STPost St = (STPost) STitr.next();
Date retrievedate = St.getTime();
String strDate = sdf.format(retrievedate);
if(strDate.equals("Jan")) {
janCounter++;
}
else if (strDate.equals("Feb")) {
febCounter++;
}
else if (strDate.equals("Mar")) {
marCounter++;
}
else if (strDate.equals("Apr")) {
aprCounter++;
}
else if (strDate.equals("May")) {
mayCounter++;
}
else if (strDate.equals("June")) {
juneCounter++;
}
else if (strDate.equals("July")) {
julyCounter++;
}
else if (strDate.equals("Aug")) {
augCounter++;
}
else if (strDate.equals("Sept")) {
septCounter++;
}
else if (strDate.equals("Oct")) {
octCounter++;
}
else if (strDate.equals("Nov")) {
novCounter++;
}
else if (strDate.equals("Dec")) {
decCounter++;
}
numberOfPost.put("January", janCounter);
numberOfPost.put("Feburary", febCounter);
numberOfPost.put("March", marCounter);
numberOfPost.put("April", aprCounter);
numberOfPost.put("May", mayCounter);
numberOfPost.put("June", juneCounter);
numberOfPost.put("July", julyCounter);
numberOfPost.put("August", augCounter);
numberOfPost.put("September", septCounter);
numberOfPost.put("October", octCounter);
numberOfPost.put("November", novCounter);
numberOfPost.put("December", decCounter);
}
return numberOfPost
}
You can create an array of months and check if value exists there using indexOf method.
String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
Integer idx = months.indexOf(strDate);
Thereafter you can use SimpleDateFormat("MMMM") pattern to put and get it into your map.
if(idx > -1) {
String longDate = new SimpleDateFormat("MMMM").format(retrievedate);
Integer current = numberOfPost.get(longDate);
if (current == null) {
current = 1;
} else {
current += 1;
}
numberOfPost.put(longDate, current);
}
Thereafter, you can use map iterator to display content of map.
You already have a good start. Using a the hash map will make the code much tidier.
You can replace all those if statements and put statements with the code below:
if (!numberOfPosts.containsKey(strDate)) {
numberOfPosts.put(strDate, 0);
}
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1);
The if statement will create a dictionary entry if there is not one with the key of strDate. The value of the entry is set to 0.
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1)
The line above increments by 1 the dictionary entry with the key of strDate.
I'm working on this program that emulates restriction enzymes and DNA splicing. I'm using DnaSequenceNode[s] as linked list nodes.
I have a problem with one of the function in my code, cutSplice() is supposed to create a new DnaStrand that is a clone of the current DnaStrand, but with every instance of enzyme replaced by splicee.
For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not shown):
first -> "TT" -> "TTAAGG" -> "CC" -> null
My function works. However, my method cutSplice() takes more than 80 seconds to splice 200 DNAs. I'm supposed to bring that 80 seconds to 2 seconds.
This is all my code for the class : LinkedDnaStrand.java
And here's the code for the method cutSplice()
public DnaStrand cutSplice(String enzyme, String splicee) {
DnaStrand newStrand = null;
String original_Dna = this.toString();
String new_Dna = original_Dna.replaceAll(enzyme, splicee);
String[] splicee_split = new_Dna.split(splicee); // splits the new DNA string DnaStrand
newStrand = null;
int i = 0;
if (original_Dna.startsWith(enzyme)) {
newStrand = new LinkedDnaStrand(splicee);
} else {
newStrand = new LinkedDnaStrand(splicee_split[0]);
newStrand.append(splicee);
}
for (i = 1; i < splicee_split.length - 1; i++) {
String node = splicee_split[i];
newStrand.append(node);
newStrand.append(splicee);
}
newStrand.append(splicee_split[splicee_split.length - 1]);
if (original_Dna.endsWith(enzyme)) {
newStrand.append(splicee);
}
return newStrand;
}
Does anybody see anything that could make a critical difference on the time this function takes to process 200 DNAs sample?
Well, it is comfortable to use the string methods, but you are losing time in converting to the string, back to sequence, and (as pointed out in the previous comments) with the regex based string functions.
It will certainly consume less time to operate on the linked list directly, although this will require you to implement the replacement algorithm yourself:
#Override
public LinkedDnaStrand cutSplice(String enzyme, String splicee)
{
LinkedDnaStrand strand = new LinkedDnaStrand();
DnaSequenceNode end = null;
DnaSequenceNode begin = top;
int pos = 0;
DnaSequenceNode tmpStart, tmpEnd;
for (DnaSequenceNode current = top; current != null; current = current.next)
{
if(current.value != enzyme.charAt(pos))
{
tmpStart = tmpEnd = new DnaSequenceNode(begin.value);
for (DnaSequenceNode n = begin.next; n != current.next; n = n.next)
{
DnaSequenceNode c = new DnaSequenceNode(n.value);
tmpEnd.next = c;
c.previous = tmpEnd;
tmpEnd = c;
}
}
else if(++pos == enzyme.length())
{
tmpStart = tmpEnd = new DnaSequenceNode(splicee.charAt(0));
for (int i = 1; i < splicee.length(); ++i)
{
DnaSequenceNode c = new DnaSequenceNode(splicee.charAt(i));
tmpEnd.next = c;
c.previous = tmpEnd;
tmpEnd = c;
}
}
else
{
continue;
}
if(end == null)
{
strand.top = end = tmpStart;
}
else
{
end.next = tmpStart;
tmpStart.previous = end;
}
end = tmpEnd;
begin = current.next;
pos = 0;
}
return strand;
}
I do not claim that there is not any opportunity to further optimize, but this should be a lot faster as the original version. I tested it successfully with the example you gave, if you yet find a bug, feel free to fix it yourself...
Note 1: I did explicitely create a new sequence from the string (instead of using the constructor) to get the end of the sequence without having to iterate over it again.
Note 2: I assumed existing a constructor DnaSequenceNode(char value) and DnaSequenceNode having a member public char value. You might have to adjust the code appropriately if any of these assumptions fails.
I am doing FIFO LRU and Optimal. I have a problem for Optimal ( replace it with the one that we will not use in the longest time, so the furthest one). I got it to replace my fram number with the one that i dont use in the longest. But the problem is that when the number that i want to replace it with doesn't even exist HOW DO I STOP MY IF statesman? And im not sure which "if" to stop? i tried this:
public int toss( int pr )
{
// if we get the same number just return -1
for (int s=numberOfFrames-1; s>=0; s--)
{
// if we get the same number dont kick anything
if ( pr == fram[s])
{
return -1;
}
}
// find which frame to replace
int look2 = 0; // this is the co for the number you want to replace with.
// next time it is used.
int co = 0; // this is index to pra.
int r = -1;
for ( int d=numberOfFrames-1; d>=0; d--)
{
lookFor(d,r);
}
if (r == -1)
{
//item not found, handle however you want, one suggestion is:
return -1; //have the caller handle this correctly
}
else
{
int q = fram[r]; // remember 2 which is page we are getting raid off
fram[r] = pra[co]; // fram one we want to get raid off and replace it with the pr
return q; // return the one we kicked
}
}
int co = 0;
int look2 = 0;
public int lookFor(int d, int r)
{
for( int f=co; f>=0; f++) // f looping for pra
{
co = tossCallCount++;
System.out.println("here");
if( fram[d] == pra[f])
{
System.out.println("by"+pra[f]);
if(look2<=f)
{
System.out.println("hi"+fram[d]);
r = d;
look2 = f;
break;
}
}
}
return d;
}
}
If you break out of your loop at the place you have the System.exit(0), you will only ever look at pra[co] (because f=co, rather than looping through with pra[f]). You likely want to put the break inside of the if, so when you find the match, you stop this loop. But this will just exit you from the inner for loop, and you probably want to stop looping entirely. See Breaking out of nested loops in Java for more information on breaking multiple loops.
int r = -1;
for ( int d=numberOfFrames-1; d>=0; d--) {
for( int f=co; f>=0; f++) {
if( fram[d] == pra[f]) {
if(look2<=f) {
r = d;
look2 = f;
break;
}
}
}
}
if (r == -1) {
//item not found, handle however you want, one suggestion is:
return -1; //have the caller handle this correctly
} else {
int q = fram[r]; // remember 2 which is page we are getting raid off
fram[r] = pra[co]; // fram one we want to get raid off and replace it with the pr
return q; // return the one we kicked
}
I am stuck.
The following function is supposed to return currVm, an integer. But if I make a return I will break the loop and next time when this function is called,the same process will begin again.
What shall I do, so that I continue from where I left off ? I tried making static variables but I that didn't help me.
#Override
public int getNextAvailableVm() {
Set<String> dataCenters = confMap.keySet();
for (String dataCenter : dataCenters) {
LinkedList<DepConfAttr> list = confMap.get(dataCenter);
Collections.sort(list, new MemoryComparator());
int size = list.size() - 1;
int count = 0;
while(size >= 0) {
DepConfAttr dca = (DepConfAttr)list.get(count);
int currVm = dca.getVmCount();
int c = 0;
while(c <= currVm) {
allocatedVm(currVm);
c++;
return currVm;
}
count++;
size--;
}
}
return 0;
}
The for-each loop assigns a new data center that acts as a key for the confMap.The list that I get as a value, is sorted.Then a loop is run till it escapes its size.Inside this while loop, another while loop is run from where a function named allocatedVm of the inherited class is called. A parameter named currVm is passed to it.
This is the variable that I need to return. What shall I do to return this variable ? I have to start from I left off. I mean the next call should appear to be the next step, whatever it was, while executing the loop.
Add List<Integer> object to your class, and change your method as follows:
private Iterator<Integer> availableVms = null;
#Override
public int getNextAvailableVm() {
if (availableVms != null) {
if (availableVms.hasNext()) {
return availableVms.next();
}
return 0;
}
List<Integer> tmp = new ArrayList<Integer>();
Set<String> dataCenters = confMap.keySet();
for (String dataCenter : dataCenters) {
LinkedList<DepConfAttr> list = confMap.get(dataCenter);
Collections.sort(list, new MemoryComparator());
int size = list.size() - 1;
int count = 0;
while(size >= 0) {
DepConfAttr dca = (DepConfAttr)list.get(count);
int currVm = dca.getVmCount();
int c = 0;
while(c <= currVm) {
allocatedVm(currVm);
c++;
tmp.add(currVm);
}
count++;
size--;
}
}
availableVms = tmp.iterator();
return availableVms.hasNext() ? availableVms.next() : 0;
}
The idea is to pre-generate the entire list, and store its iterator for future use. Before entering the method you check if the availableVms iterator has been prepared. If it has been prepared, grab the next item off of it if it's available; otherwise, return zero.
If the list has not been prepared yet, run your algorithm, and add the results to a temporary list tmp. Once the list is ready, grab its iterator, and use it for subsequent invocations.
I am reading a text file abc .txt which is tab delimited as shown below
gfh hgh thf
--- --- ---
fgh sji irj
rhf dhh fhf
kji idj ddt
and I am able to read it successfully (for all the columns in the table I have developed a separate pojo along with getters and setters), the advantage is that I can get the value of complete row through its getters.
Now I have to make sure that no column in the table should be null and if any column value is null, then I should throw a new exception, for example ..
gfh hgh thf
--- --- ---
fgh sji irj //row 1
rhf dhh fhf
kji idj ddt
fgq fio //As seen in this row that second column value is null
Now the approach that I am following is that getting the value row wise in a string as shown below
String n = f.getgfh()+f.gethgh()+f.getthf(); //it will contain the contents of the row 1
make a separate method and will pass this string
private boolean validaterow(String f)
{
}
in this method here I am taking the complete row in a string and inside this method I want to break this string in tokens and then further evaluate those tokens for empty or null , if there are then I will return false
Try this,
private boolean validateRow(String f)
{
if(f.getgfh() != null && !f.getgfh().trim().isEmpty() &&
f.gethgh() != null && !f.gethgh().trim().isEmpty() &&
f.getthf() != null && !f.getthf().trim().isEmpty())
{
return true;
}
else
{
return false;
}
}
You can set a null check like in getters
public String gethgh()
{
return (String) ((null == hgh) ? new UserDefinedException() : hgh);
}
here UserDefinedException must be declared as a class
I consider this should work
Why do you pass it to a method?
Use
String row1,row2,row3;
row1=f.getgfh();
row2=f.gethgh();
row3=f.getthf();
You can check for your condition at the time of concatenation.
if(row1==null)
'throw your message
else
row1=""
if(row2==null)
'throw your message
else
row2=""
if(row3==null)
'throw your message
else
row3=""
At last,
String n = row1+row2+row3;
Look at apache string utils library. It might have what you need
Split each line on tab like string.split("\t") and check each token using isEmpty() method of string class.
use StringIsNullOrEmtpy to check if row is valid for every entry of the row
private boolean ValidateRow()
{
return !(StringIsNullOrEmpty((f.getgfh())) ||
StringIsNullOrEmpty((f.gethgh())) ||
StringIsNullOrEmpty((f.getthf()))
);
}
private bool StringIsNullOrEmtpy(string input)
{
return input.isEmpty() || input == null;
}
Let's assume that you have a method getNextValueAndPosPair() which returns the next value of your tsv (tab separate values) file and the position of the last space found after the value read (i.g. a Tab or a Newline).
Then you can validate your input row by chechking that it contains exactly three distinct values separated by a Tab.
Below the implementation:
// A simple general pair class.
class Pair<A, B> {
Pair(A first, A second) {
this.first = first;
this.second = second;
}
public A first() { return first; }
public A second() { return second; }
private final A first;
private final B second;
}
// Returns true if this rows contains 4 distinct values, false otherwise.
private boolean validaterow(String f) {
int pos = 0;
for (int i = 0; i < 3; i++) {
Pair<String, Integer> valueAndPos = getNextValueAndPosPair(f, pos);
String value = valueAndPos.first();
int pos = valueAndPos.second();
if (value.isEmpty()) {
System.err.println("The " + i + "-th value is null.");
return false;
}
pos += 1;
}
return true;
}
// Returns a Pair holding the next tsv value in the row and the position of the delimiter space
private Pair<String, Integer> getNextValueAndPosPair(String f, int start) {
int length = 0;
for (int i = start; i < f.length && !Character.isSpaceChar(f.charAt(i)); i++) length++;
int end = start + length;
String value = f.substring(start, end);
Pair<String, Integer> valueAndPos = new Pair<>(value, end);
return valueAndPos;
}