Raising a number to a power in Java

Writing by on Wednesday, 23 of April , 2014 at 4:10 pm

In Java, use the Math.pow(a, b) to raise the value of ‘a’ to the power of ‘b’.
In Microsoft Excel and some other tools the Caret (^) symbol is used for this operation.
Note that in Java, the caret (^) symbol implies XOR of the two numbers.

Here’s the difference between the two.

2 raised to 4 = 2*2*2*2 = 16 (2 to the power of 4)
2 XOR 4 = 010 XOR 100 = 110 = 6 (Binary representation of 2 = 010 ; and 4 = 100)

Here’s a simple Java code snippet to try out.

public static void main(String[] args) {
	System.out.println("Math.pow(2, 4) = " + Math.pow(2, 4)); // returns 16
	System.out.println("2 ^ 4 = " + (2 ^ 4) ); // returns 6 (010 XOR 100 = 110)
}

And here’s a SQL flavor.

mysql> select power(2, 4);
+-------------+
| power(2, 4) |
+-------------+
|          16 |
+-------------+
1 row in set (0.00 sec)

And a Divide & Conquer algorithm in Java.

public double power(double a, long b) {
	// Base Cases
	if (a == 0) return 0;
	if (b == 0) return 1;
	
	// Divide & Conquer
	// 2*2*2*2 = (2*2) * (2*2) = ((2)*(2)) * ((2)*(2))
	double p = power(a, b/2);
	
	// Handle Negative Exponents
	double x = (b >= 0) ? a : 1/a;

	// Handle Odd & Even b's 
	// 2*2*2*2*2 = 2 * (2*2) * (2*2) = a * p * p
	return (b%2 != 0) ? x*p*p : p*p; 	
}

Leave a comment

Category: Excel,Java,SQL DB

Read a File into a String using a single statement

Writing by on Monday, 18 of November , 2013 at 6:08 am

I’ve found that java.util.Scanner class instead of the java.io classes to work well for most of my text file reading and parsing needs.

String content = new Scanner(new File("/path/to/file.txt")).useDelimiter("\\Z").next();
System.out.println(content);

For more info read up natch3z or coderwall.

Leave a comment

Category: Java

Use Ant buildfile or a script to build your Eclipse project

Writing by on Tuesday, 5 of March , 2013 at 6:44 am

Let’s say you have a buildfile build.xml that builds your project and deploys to say Tomcat. Wouldn’t it be great to have Eclipse do that for your when you build the project within eclipse? Eclipse has this concept called Builders as part of your project properties that let’s you do just that.

  • Right Click the Project -> Properties -> Builders
  • Select New
  • Select Ant Builder
  • In the Main tab
  • Buildfile -> Browse Workspace… and select the Buildfile
  • Base Directory -> Browse Workspace… and select the Base Directory
  • In the Refreshtab
  • Check Refresh resources upon completion (recommended in most cases)
  • Select The project containing the resource or the option that suits you
  • In the Targetstab, select the desired targets from the buildfile

When you build (Ctrl+B) in eclipse, the specified ant target will be run for you and in my case, my application will be deployed to Tomcat.
If you want to run a script, you can do so by selecting Program instead of Ant Builder.

Here’s a screenshot of my Ant Builder.
EclipseAntBuilder

Did you know you could also debug your Ant Script within Eclipse.
Another great post on IBM Developer Works.

Leave a comment

Category: Eclipse,Java

Correlating Linux top output with java stack trace from a thread dump

Writing by on Thursday, 21 of February , 2013 at 12:23 am

Using the top -H command to show you the thread ids, and from the thread dump, you can correlate the thread that’s taking CPU time.

For example the stack trace will show you the ID in hex format and the top will show you the thread PID in decimal format.

Notice that nid=0x6c21 (top -H) is the same as 27681 (from the thread dump).

Here’s a thread dump snippet

“http-bio-/127.0.0.1-9090-exec-7” daemon prio=10 tid=0x000000004c433800 nid=0x6c21 runnable [0x00000000644b9000]
INFO | jvm 1 | 2013/02/20 11:51:57 | java.lang.Thread.State: RUNNABLE
INFO | jvm 1 | 2013/02/20 11:51:57 | at java.util.HashMap.put(HashMap.java:374)

Here’s the output of top -H

[root@myserver bin]# top -H

top – 15:56:17 up 5 days, 5:16, 8 users, load average: 2.16, 2.25, 3.28
Tasks: 1038 total, 3 running, 1035 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.8%us, 0.1%sy, 0.0%ni, 87.1%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 37043972k total, 35569196k used, 1474776k free, 45720k buffers
Swap: 12586916k total, 228k used, 12586688k free, 18998952k cached
3.00 00:04:50
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
27409 shivdev 25 0 11.6g 10g 16m R 99.9 30.7 1305:02 java
27681 shivdev 25 0 11.6g 10g 16m R 99.9 30.7 1304:37 java

Leave a comment

Category: Java,Linux

Eclipse Debugger Hits Unmarked Breakpoint on Exceptions

Writing by on Sunday, 27 of January , 2013 at 7:58 pm

By default, eclipse will suspend the execution on uncaught exceptions and take you directly to the code that you may not really intend to debug. To avoid that set your prefrences:

Window -> Preferences -> Java -> Debug
Uncheck Suspend execution on uncaught exceptions

Leave a comment

Category: Eclipse,Java

JIRA XMLRPC Sample Java Code

Writing by on Friday, 18 of January , 2013 at 5:53 pm

If you’re on an older version of JIRA with XMLRPC being the only option (since REST is not available), Atlassian’s XMLRPC APIs are pretty simple to use. For my use case, I wanted a listing of total issues in my filters with individual breakdowns as illustrated below. JIRA Filter (Total Count) : assignee_1(count) assignee_2(count) …

Tennis Project Open Jiras (4) : rfederer(1) rnadal(1) nole(1) andym(1)
NFL Project Open Items (0) :
Tennis Project FRs Ready for Verification (36) : andym(1) rfederer(17) nole(7) rnadal(11)
NFL Project FRs Fixed in Branch (25) : tbrady(5) manning(7) asmith(12) dbrees(1)

So I wrote some code for which I needed the following.

Then simply use the inefficient code below to get what you need.

package com.shivdev.jira;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import com.shivdev.util.XTrustProvider;

public class JiraXMLRPC4Blog {
	// Our business logic would iterate over these filters and display the total counts and individual breakdowns 
	// To get the Filter IDs, navigate the filter from JIRA and copy the requestId  
	// https://jira.hostname.com:8443/secure/IssueNavigator.jspa?mode=hide&requestId=13611
	static String [][] FILTERS = new String[][] {
			{"13584", "Tennis Project Open Jiras"}, 
			{"13661", "NFL Project Open Items"},
			{"13611", "Tennis Project FRs Ready for Verification"}, 
			{"13583", "NFL Project FRs Fixed in Branch"}, 
	};
	
	// This hostname verification step can be omitted if your not on HTTPS
	static {
		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				// Make sure that hostname is valid
				return true;
			}
		});
	}

	// Constants
	public static final String JIRA_URI = "https://jira.hostname.com:8443"; // JIRA hostname
	public static final String RPC_PATH = "/rpc/xmlrpc"; // JIRA path to xmlrpc
	public static final String METHOD = "getIssuesFromFilter"; // JIRA xmlrpc method
	
	public static void main(String[] args) {
		if (args.length == 2) {
			String user = args[0];
			String passwd = args[1];
			JiraXMLRPC4Blog.printIssueDetails(user, passwd);
		} else {
			System.err.print("Provide username and password as arguments.");
		}
	}
	
	// Business Logic - Inefficiently callJIRARPC - Just for Demo purpose
	// Ideally 1 login multiple RPCs and 1 logout should have been enough  
	public static void printIssueDetails(String user, String passwd) {
		
		// Go over all the filters
		for (int filterIdx = 0; filterIdx < FILTERS.length; filterIdx++) {
			String filterID = FILTERS[filterIdx][0];
			String filterName = FILTERS[filterIdx][1];
			
			Vector<String> params = new Vector<String>(0);
			params.add(filterID); 
			
			// Construct assignees and counts for each filter
			Map<String, Integer> assignees = new HashMap<String, Integer> ();
			Object issues[] = JiraXMLRPC.callJiraRPC(user, passwd, METHOD, params);
			if (issues != null) {
				for (int i = 0; i < issues.length; i++) {
					Map<String, Object> issue = (Map) issues[i];
					// summary, status, votes, assignee, customFieldValues, fixVersions, type, id, reporter, project, created, updated, description, priority, components, affectsVersions, key

					String assignee = (issue.get("assignee")).toString();
					Integer bugCount = assignees.get(assignee);
					assignees.put(assignee, bugCount == null ? 1 : bugCount + 1);
				}
			}
			
			// Print details
			StringBuffer buf = new StringBuffer();
			buf.append(filterName + " (" + issues.length + ") : ");
			for (String assignee : assignees.keySet()) {
				buf.append(assignee + "(" + assignees.get(assignee) + ") ");
			}
			log(buf.toString());
		}
	}
	
	// Actual Sample Code for making XMLRPC calls 
	public static Object[] callJiraRPC(String user, String passwd, String method, Vector methodParams) {
		try {
			XTrustProvider.install();
	
			XmlRpcClient rpcClient;
			XmlRpcClientConfigImpl config;
	
			config = new XmlRpcClientConfigImpl();
			config.setServerURL(new URL(JIRA_URI + RPC_PATH));
			rpcClient = new XmlRpcClient();
			rpcClient.setConfig(config);
			
			// login
			Vector<String> loginParams = new Vector<String>(2);
			loginParams.add(user);
			loginParams.add(passwd);
			String loginToken = (String) rpcClient.execute("jira1.login", loginParams);
			log("Logged in.");
			
			// Create the Authentication Token to be passed with every JiraXMLRPC call
			Vector<String> loginTokenVector = new Vector<String>(1);
			loginTokenVector.add(loginToken);
			
			// Create a list of loginToken + methodParams
			int size = 1 + ((methodParams != null) ? methodParams.size() : 0);  
			Vector paramsVector = new Vector(size);
			paramsVector.addAll(loginTokenVector);
			paramsVector.addAll(methodParams);
						
			// Make the RPC call
			Object[] result = (Object[]) rpcClient.execute( "jira1." + method, paramsVector);
			log(method + " sucess.");
			
			// Log out
			Boolean bool = (Boolean) rpcClient.execute("jira1.logout", loginTokenVector);
			log("Logged out.");
			
			// Return the result
			return result;
			
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	// Custom Logging Code
	public static void log(String msg) {
		System.out.println(msg);
	}
	
}

Leave a comment

Category: Java

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.