Android - get index #0 , #1 , #2 of a number - java

how to get index #0 , #1 , #2 of a number
for example
long sec = 8541; //get 541;
long sec = 5276; //get 276;
long sec = 463; //get 463;
long sec = 95; //get 95;
and etc..

If I understood correctly you want the 3 first digits (from the right). You can get them by using modulo 1000 :
long sec = 12345;
long res = sec%1000; //res will be 345

Something like this:
int digitAtPositionOne = Integer.parseInt(Integer.toString(sec).substring(0, 1)); //change this accordingly
int digitAtPositionTwo = Integer.parseInt(Integer.toString(sec).substring(0, 2)); //change this accordingly

You can use subString from the wanted index to get only part of the number like this :
int yourNewNumber = Integer.parseInt(Integer.toString(sec).substring(start index, end index));
Note - if you won't fill your end index your new number will start at the start index given until the last index

Related

How to get the remaining in java

I have a java program that will run every 15th and last day of the month, i have sample that has 2 different type of amount.
this type of amount is come from the query and its already sort by sysdate, this is the result of the query:
130
500
while running the program it will automatically deduct from the first amount and the remaining will go to the second amount.
this is first amount 125.
and this is the second amount 100.
how do i do that? it really appreciated your help.
//this is the query to get the 130,500.
String getAdvanceEmployee = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND IS_ADVANCE = '1'";
ResultSet result1 = stmt.executeQuery(getAdvanceEmployee);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output 130,150
//this is the query to get the 125.
String getAdvancePayment = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND ENTRY_TYPE = '1'";
ResultSet result2 = stmt1.executeQuery(getAdvancePayment);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output will 125
//im confused the logic itself
}
}
amount from the query:
130
500
the first amount 125
the second amount 100
actual result is:
125
-125 // this negative comes from the amount of 130 the remaining -5 will go to the next amount which is this
100
-5
-95
//and the remaining last was -405.
you can calculate it this way :
public int calculatAmountOne(int firstAmount , int secondAmount){
//in your case firstAmount = 125 , secondeAmount = 130
int rest = firstAmount - secondeAmount ;
return rest
}
public int calculatAmountTwo(int firstAmount , int secondAmount){
//in your case firstAmount = 100, secondeAmount = -5
int rest = firstAmount + secondeAmount ;
return rest
}
so now that you create the two method to calculate the two different amount you can use them
int restOne = calculatAmountOne(125,130) // restOne = -5 ;
int restTwo = calculatAmountTwo(100,restOne) // restTwo = 95 ;
int lastRemaining = restTwo + 500 // lastRemaining = 595
you should later use number that you get instead of the number i put as example based on your question !

How to randomly click an element in the list (Android)using selenium+Appium?

Below code throws an array illegal out of bound exception
java.util.List <MobileElement> ele = driver.findElements(By.xpath("//*[#id='com.bankappointmentschedulingmobile:id/bankType'][#index=0]"));
System.out.println(ele.size());
Random rnd = new Random();
int rndInt = rnd.nextInt(ele.size());
((org.openqa.selenium.WebElement) ele.get(rndInt)).click();
Elements in the UI automator:
You don't have to use XPath in above case because you have element ID. Also, you are adding a check for index=0, it means it will check elements only with index 0. In the below example, I am finding elements using ID = "bankType" and printing its size. While generating random number I have subtracted "1" because the index will start from 0.
List<WebElement> elementList = driver.findElements(By.id("bankType"));
System.out.println("Total elements : " + elementList.size());
Random rand = new Random();
int index = rand.nextInt(elementList.size()-1); // -1 because index will start from 0
elementList.get(index).click();
Used this approach with appium using ruby, but this one should be good if you have fewer elements and also since, both of my elements had different xpath's.
And(/^I select the choice in cooking style$/) do
style =
['//UIAApplication[1]/UIAWindow[1]/UIACollectionView[1]/UIACollectionCell[1]/UIACollectionView[1]/UIACollectionCell[1]/UIAStaticText[1]]' , '//UIAApplication[1]/UIAWindow[1]/UIACollectionView[1]/UIACollectionCell[1]/UIACollectionView[1]/UIACollectionCell[2]/UIAStaticText[1]']
cookingstyle = style.sample
find_element(xpath: cookingstyle).click
puts cookingstyle
end

GETBULK requests returns OIDs other than specified one

I'm using snmp4j to get a auto increment OID. The main OID looks like 1.3.6.1.4.1.22420.2.6.3.1.12.1 and auto increment number is appended to it:
1.3.6.1.4.1.22420.2.6.3.1.12.1.158271
1.3.6.1.4.1.22420.2.6.3.1.12.1.158272
1.3.6.1.4.1.22420.2.6.3.1.12.1.158273
1.3.6.1.4.1.22420.2.6.3.1.12.1.158274
1.3.6.1.4.1.22420.2.6.3.1.12.1.158275
1.3.6.1.4.1.22420.2.6.3.1.12.1.158276
First of all if we want to get the OID with maximum number the correct way is to use GETBULK method. Am I right? When I send a GETBULK request like below, the result is weird:
PDU p = new PDU();
p.add(new VariableBinding(new OID("1.3.6.1.4.1.22420.2.6.3.1.12.1")));
p.setType(PDU.GETBULK);
p.setMaxRepetitions(200);
ResponseEvent re = snmp.send(p, target);
for (VariableBinding v : re.getResponse().getVariableBindings()) {
System.out.println(v);
}
Here is the result:
1.3.6.1.4.1.22420.2.6.3.1.12.1.158273 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158274 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158275 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158276 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158277 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158278 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158279 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158280 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.1.158281 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158273 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158274 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158275 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158276 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158277 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158278 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158279 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158280 = 0
1.3.6.1.4.1.22420.2.6.3.1.12.2.158281 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158273 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158274 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158275 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158276 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158277 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158278 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158279 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158280 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.1.158287 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158273 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158274 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158275 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158276 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158277 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158278 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158279 = 0
1.3.6.1.4.1.22420.2.6.3.1.13.2.158280 = 0
The problem is it contains other OIDs such 1.3.6.1.4.1.22420.2.6.3.1.13.2 as well. Am I doing something wrong? Isn't there any robust and efficient mechanism to do this? I'm doing this for large number of network switches and the response contains many VariableBindings which I don't use.
One way to look at this is like telling the device to perform 'N' get-next operations on the provided OID and return the results.
In this scenario, when the device reaches the last row for that particular column, it moves to the next column in that table (or the next OID after the table if we are on the last column).
In short, the answer is that you are not doing anything wrong.
The GETBULK operation has the same effect of executing many times of GETNEXT.
And GETNEXT means it will always try to get the next in the lexicographical ordering of the known object names.that's to say it will return 1.3.6.1.4.1.22420.2.6.3.1.12.1 's successors ( taking the whole MIB as a tree.) until it didn't get any succssors.
For your question:
Try the following codes:
for (VariableBinding v : re.getResponse().getVariableBindings()) {
if (!v.getOid().startsWith(startOID))
{
// the startOID = new OID("1.3.6.1.4.1.22420.2.6.3.1.12.1");
//end here, sub tree ends.
break;
}
}

Aggregating objects by timestamp per day for a timespan of week

I have problem with aggregating data based on their timestamp per day for a timespan of one week. There is a SQLite database, which has a table which I save the number of walking steps in (timestamp column is UTC and created_At is local time, but I don't use the created_at column anyway).
What I want to do is get the total data which happened in 7 days ago until the midnight of a day before. So I have this jodatime expression to find start and end for timestamps
long start = new DateTime().withMillisOfDay(0).minusDays(7).getMillis();
long end = new DateTime().withTimeAtStartOfDay().getMillis();
//start milli:1405029600000 DateTime: 2014-07-11 00:00:00
//end milli:1405634400000 DateTime: 2014-07-18 00:00:00
Then I execute this sql command:
SELECT * FROM pa_data WHERE timestamp BETWEEN 1405029600000 AND 1405634400000
And I am pretty sure that it returns the correct rows ( I have compared the android database result with SQLite Database Browser on my pc, both return same number of rows). For this, I tried to use this nested iteration:
the Object I am trying to create is:
public class PhysicalActivityPerDay {
private List<PhysicalActivity> mList;
public PhysicalActivityPerDay(List<PhysicalActivity> list) {
mList = new ArrayList<PhysicalActivity>(list);
}
//methods....
}
Now the problem is, I want to have a data object that can hold the rows for each day.
List<PhysicalActivity> all = getPhysicalActivitiesBetween(start, end);
List<PhysicalActivityPerDay> perDays = new ArrayList<PhysicalActivityPerDay>();
List<PhysicalActivity> tempList;
PhysicalActivityPerDay tempPerDay;
for (int i = 0; i < 7; i++) {
long begin = start;
long stop = (begin + 86400000); //add 24 hours
tempList = new ArrayList<PhysicalActivity>();
for (int j = 0; j < all.size(); j++) {
PhysicalActivity p = all.get(j);
DateTime when = new DateTime(p.getTimestamp());
if (when.isAfter(start) && when.isBefore(stop)) {
tempList.add(p);
all.remove(j); //remove the matching object from the list
}
}
tempPerDay = new PhysicalActivityPerDay(tempList);
perDays.add(tempPerDay);
start += 86400000; //add 24 hours or 1 day for next iteration
}
return perDays;
But the result is totally unexpected. There are many rows which don't match the if statements above. I did a debug and here is what happens:
Log.w(TAG, "There are totally " + all.size() + " physical activities for day for 7 days");
//There are totally 6559 physical activities for day for 7 days
But, when I check the all list (total rows returned by DB) although I am removing matched objects from it, if I query its size after the nested iteration, it surprisingly still contains many objects in it, telling me that the iteration was not successful!
//Remaining: 3278 records after iterations from 6559
What I am doing wrong? please help me findout!
Not sure if that's the only problem :
You are looping over the all List, and removing items.
When you call all.remove(j), the item that used to be at position j+1 moves to poisition j. Which means your for loop would skip that item.
One way to solve this is to increment j only if you don't remove an item from the list.
for (int j = 0; j < all.size();) {
PhysicalActivity p = all.get(j);
DateTime when = new DateTime(p.getTimestamp());
if (when.isAfter(start) && when.isBefore(stop)) {
tempList.add(p);
all.remove(j); //remove the matching object from the list
} else {
j++;
}
}
Actually, I'm not entirely sure if the loop would work after this fix. It depends whether all.size() is evaluated in each iteration. If it isn't, it would expect the list to have the initial number of elements, even though you are removing items. In that case you can expect to get an exception the first time you try to access an index beyond the last index of the array.
If you get an exception, you can replace the loop with a while loop :
Iterator<PhysicalActivity> iter = all.iterator();
while (iter.hasNext ()) {
PhysicalActivity p = iter.next();
...
if (...) {
iter.remove();
}
}
Refer to the definition of List.remove() :
public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
How about letting SQL perform your aggregation for you
SELECT strftime('%W-%Y',dt) as weekYear, count(1) as occurencePerWeek
FROM SOMETABLE c GROUP BY weekYear;
http://sqlfiddle.com/#!5/e63c3/1

Java Optimizing arithmetic and Assignment Operators for large input

I have a piece of code that must run extremely fast in terms of clock speed. The algorithm is already in O(N). It takes 2seconds, it needs to take 1s. For most A.length inputs ~ 100,000 it takes .3s unless a particular line of code is invoked an extreme number of times. (For an esoteric programming challenge)
It uses a calculation of the arithmetic series that 1,2,..N -> 1,3,4,10,15..
that can be represented by n*(n+1)/2
I loop through this equation hundreds of thousands of times.
I do not have access to the input, nor can I display it. The only information I am able to get returned is the time it took to run.
particularly the equation is:
s+=(n+c)-((n*(n+1))/2);
s and c can have values range from 0 to 1Billion
n can range 0 to 100,000
What is the most efficient way to write this statement in terms of clock speed?
I have heard division takes more time then multiplication, but beyond that I could not determine whether writing this in one line or multiple assignment lines was more efficient.
Dividing and multiplying versus multiplying and then dividing?
Also would creating custom integers types significantly help?
Edit as per request, full code with small input case (sorry if it's ugly, I've just kept stripping it down):
public static void main(String[] args) {
int A[]={3,4,8,5,1,4,6,8,7,2,2,4};//output 44
int K=6;
//long start = System.currentTimeMillis();;
//for(int i=0;i<100000;i++){
System.out.println(mezmeriz4r(A,K));
//}
//long end = System.currentTimeMillis();;
// System.out.println((end - start) + " ms");
}
public static int mezmeriz4r(int[]A,int K){
int s=0;
int ml=s;
int mxl=s;
int sz=1;
int t=s;
int c=sz;
int lol=50000;
int end=A.length;
for(int i=sz;i<end;i++){
if(A[i]>A[mxl]){
mxl=i;
}else if(A[i]<A[ml]){
ml=i;
}
if(Math.abs(A[ml]-A[mxl])<=K){
sz++;
if(sz>=lol)return 1000000000;
if(sz>1){
c+=sz;
}
}else{
if(A[ml]!=A[i]){
t=i-ml;
s+=(t+c)-((t*(t+1))/(short)2);
i=ml;
ml++;
mxl=ml;
}else{
t=i-mxl;
s+=(t+c)-((t*(t+1))/(short)2);
i=mxl;
mxl++;
ml=mxl;
}
c=1;
sz=0;
}
}
if(s>1000000000)return 1000000000;
return s+c;
}
Returned from Challenge:
Detected time complexity:
O(N)
test time result
example
example test 0.290 s. OK
single
single element 0.290 s. OK
double
two elements 0.290 s. OK
small_functional
small functional tests 0.280 s. OK
small_random
small random sequences length = ~100 0.300 s. OK
small_random2
small random sequences length = ~100 0.300 s. OK
medium_random
chaotic medium sequences length = ~3,000 0.290 s. OK
large_range
large range test, length = ~100,000 2.200 s. TIMEOUT ERROR
running time: >2.20 sec., time limit: 1.02 sec.
large_random
random large sequences length = ~100,000 0.310 s. OK
large_answer
test with large answer 0.320 s. OK
large_extreme
all maximal value = ~100,000 0.340 s. OK
With a little algebra, you can simply the expression (n+c)-((n*(n+1))/2) to c-((n*(n-1))/2) to remove an addition operation. Then you can replace the division by 2 with a bit-shift to the right by 1, which is faster than division. Try replacing
s+=(n+c)-((n*(n+1))/2);
with
s+=c-((n*(n-1))>>1);
I dont have access to validate all inputs. and time range. but this one runs O(N) for sure. and have improved. run and let me know your feedback.i will provide details if necessary
public static int solution(int[]A,int K){
int minIndex=0;
int maxIndex=0;
int end=A.length;
int slize = end;
int startIndex = 0;
int diff = 0;
int minMaxIndexDiff = 0;
for(int currIndex=1;currIndex<end;currIndex++){
if(A[currIndex]>A[maxIndex]){
maxIndex=currIndex;
}else if(A[currIndex]<A[minIndex]){
minIndex=currIndex;
}
if( (A[maxIndex]-A[minIndex]) >K){
minMaxIndexDiff= currIndex- startIndex;
if (minMaxIndexDiff > 1){
slize+= ((minMaxIndexDiff*(minMaxIndexDiff-1)) >> 1);
if (diff > 0 ) {
slize = slize + (diff * minMaxIndexDiff);
}
}
if (minIndex == currIndex){
diff = currIndex - (maxIndex + 1);
}else{
diff = currIndex - (minIndex + 1);
}
if (slize > 1000000000) {
return 1000000000;
}
minIndex = currIndex;
maxIndex = currIndex;
startIndex = currIndex;
}
}
if ( (startIndex +1) == end){
return slize;
}
if (slize > 1000000000) {
return 1000000000;
}
minMaxIndexDiff= end- startIndex;
if (minMaxIndexDiff > 1){
slize+= ((minMaxIndexDiff*(minMaxIndexDiff-1)) >> 1);
if (diff > 0 ) {
slize = slize + (diff * minMaxIndexDiff);
}
}
return slize;
}
Get rid of the System.out.println() in the for loop :) you will be amazed how much faster your calculation will be
Nested assignments, i. e. instead of
t=i-ml;
s+=(t+c)-((t*(t+1))/(short)2);
i=ml;
ml++;
mxl=ml;
something like
s+=((t=i-ml)+c);
s-=((t*(t+1))/(short)2);
i=ml;
mxl=++ml;
sometimes occurs in OpenJDK sources. It mainly results in replacing *load bytecode instructions with *dups. According to my experiments, it really gives a very little speedup, but it is ultra hadrcore, I don't recommend to write such code manually.
I would try the following and profile the code after each change to check if there is any gain in speed.
replace:
if(Math.abs(A[ml]-A[mxl])<=K)
by
int diff = A[ml]-A[mxl];
if(diff<=K && diff>=-K)
replace
/2
by
>>1
replace
ml++;
mxl=ml;
by
mxl=++ml;
Maybe avoid array access of the same element (internal boundary checks of java may take some time)
So staore at least A[i] in a local varianble.
I would create a C version first and see, how fast it can go with "direct access to the metal". Chances are, you are trying to optimize calculation which is already optimized to the limit.
I would try to elimnate this line if(Math.abs(A[ml]-A[mxl])<=
by a faster self calculated abs version, which is inlined, not a method call!
The cast to (short) does not help,
but try the right shift operator X >>1 instead x / 2
removing the System.out.println() can speed up by factor of 1000.
But be carefull otherwise your whole algorithm can be removed by the VM becasue you dont use it.
Old code:
for(int i=0;i<100000;i++){
System.out.println(mezmeriz4r(A,K));
}
New code:
int dummy = 0;
for(int i=0;i<100000;i++){
dummy = mezmeriz4r(A,K);
}
//Use dummy otherwise optimisation can remove mezmeriz4r
System.out.print("finished: " + dummy);

Categories