Category Archives: Code

Tutorial: Using a Button To Switch Pages in a ViewPager [Android Studio]

OK, so Android Studio (like its ancient forefather Eclipse) supports the ViewPager navigation type, which allows you to set up multi-page navigation without any work. However, I’ve noticed that many people don’t quite seem to get the hang of swiping and give up on trying to switch pages. It’s best to provide an alternate form of navigation for them – in the form of the ubiquitous button, linked to a function that switches the active page. As an example, I’m going to make a function that makes the ViewPager jump to the second page.

  1. In the little fragment_main_dummy.xml file hidden away in src/main/java/res/layout (or whatever the name of the file – in which you want the button to be – is), add a new Button component (using the Design view if you like that). Switch to Code view and locate the Button component.before
  2. At the end of the Button component, before the ending /> press Enter and add this line of code:
    android:onClick="jumpToPage"

    after

  3. Save the file. Now, the last part of this can be done in two ways:
    1. First method: Put your cursor somewhere on the android:onClick line and press Alt-Enter (Option-Enter on Macs). Select “Create onClick event handler”.
      onclick
      Select MainActivity when asked which activity you want to create the onClick handler in.choose_activity
      It makes a nice function called jumpToPage in your main Activity class.
      fun
      Place your cursor just after the opening brace and press enter. Add this line to the function body:
    2. mViewPager.setCurrentItem(1);

      Save the file.

    3. Second method: Switch to your MainActivity.java file. At the end of the onCreateOptionsMenu function, type this in (or copy-paste if you’re lazy):
      public void jumpToPage(View view) {
          mViewPager.setCurrentItem(1);
      }
      

      Save the file.

  4. This is what you should have in MainActivity.java now:
    jmpfun

You’re done!

[In response to a friend’s request, who asked for the pictures :D]

Find The First 1000-digit Fibonacci Number [Project Euler Problem 25]

We all know how the Fibonacci numbers are defined: the nth Fibonacci number is equal to the sum of the two before it, with initial conditions F1 = F2 = 1. Translated into my mathematical language, that is:

Fn = Fn – 1 + Fn – 2

This is an example of a recurrence relation.

Using the theory of generating functions we can turn this recurrence relation into a “closed-form” or explicit formula:Image

[This book taught me generating functions – it’s awesome! You can buy it from that link and earn me a coffee :D]

Here, that odd-looking symbol φ (shame on you) is the magical Golden Ratio (read up on it!), equal to:

Image

Oh, another thing. The number of digits in a number is equal to the ceiling of its logarithm in base 10Here’s why.

Manipulating these leads us to an expression for the index of the first Fibonacci number with d digits:

Fn = (d − 1 + log10(5) /2) / log10(φ)

And with that, here’s the two lines of code! (Code!) (OMG code!)

from math import log10, sqrt, ceil
print(int(ceil((999 + log10(5)/2.0) /
          log10((1 + sqrt(5))/2.0))))

And that’s how I became the 70181st person to solve this problem!

[image credit: Wikimedia]

NASA Space Apps Challenge 2013: A Bit of A Solution to “Wish You Were Here”

I can Can’t post now, here’s my Python code as a solution to this:

import urllib2, os, re

file_name = ""
data = dict()

def get_xml(url="http://cab.inta-csic.es/rems/rems_weather.xml", del_xml=False):
	global file_name
	file_name = url.split('/')[-1]
	u = urllib2.urlopen(url)
	f = open(file_name, 'wb')
	meta = u.info()
	file_size = int(meta.getheaders("Content-Length")[0])

	file_size_dl = 0
	block_sz = 8192
	while True:
	    buffer = u.read(block_sz)
	    if not buffer:
	        break
		file_size_dl += len(buffer)
	    f.write(buffer)
	f.close()

	#Build the data dictionary
	global data
	data = dict(
		(x, y) for x, y in (
			re.findall(
				r'<(\w+)>(.*)</\w+>', xml()
				)
			)
		)
	if del_xml:
		delete_xml_file()

def xml():
	return open(xmlpath()).read()

def xmlpath():
	return os.getcwd() + "/" + file_name

def get_data(id):
	try:
		return data[id]
	except Exception, e:
		raise KeyError, "No such key!"

def get_data_dict():
	return data

def delete_xml_file():
	os.remove(xmlpath())

def weather_report(delete_xml=False):
	get_xml(del_xml=delete_xml)
	gd=get_data
	print	("Mars weather report provided by " + gd('title'))

	print	(
				"It's {} today!"
				.format	(
							gd('atmo_opacity').lower()
						)
			)

	print	(
				"The sun rises at {} and sets at {} today."
				.format	(
							gd('sunrise'), gd('sunset')
						)
			)

	print	(
				"The pressure on Mars today is {0} mb, which is {1:.2f}% of that on earth."
				.format	(
							gd('pressure'), (float(gd('pressure'))/10.18)
						)
			)

	print	(
				"The wind is blowing at a speed of {} km/h today, in direction {}."
				.format	(
							gd('wind_speed'), gd('wind_direction')
						)
			)

	print	(
				"Temperatures range from {} to {} degrees Celsius."
				.format	(
							gd('min_temp'), gd('max_temp')
						)
			)

	print	("It's {} on Mars."
				.format	(
							gd('season').lower()
						)
			)

print(weather_report(delete_xml=True))

Multiples of 3 or 5 below 1000 [Project Euler Problem 1]

This is the first Project Euler problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Pretty simple, right? The dumb brute-force method would be:

public class M35 {
    public static void main(String[] args) {
        long time = System.nanoTime();

        int val = 0;
        for (int i = 0; i < 1000; i++){
            if(i%3==0 || i%5 == 0){val+=i;}
        }
        time = System.nanoTime() - time;

        System.out.println(time/1.0e9);
    }
}

It returns:

233168
2.6782E-5

Less than 0.0002 seconds? Neat, right? But what about an intelligent solution?
Try and recall how Gauss stumped his teacher in primary school when asked to sum the range 1 to 100 mentally. He understood that the range 1 to 100 consists of:
(1+100) + (2+99) + (3+98) … + (50+51) = 50 x 101 = 5050.

Now, in our case, we need the sum of all multiples of either three or five – but what about 15? 30? They’ll get counted twice, right?

In our case, what we need to do is,

(sum of multiples of 3) + (sum of multiples of 5) – (sum of multiples of 15)

=> (3 + 6 + 9 + … +999) + (5 + 10 + 15 + … + 995) – (15 + 30 + 45 + … + 990)

=> 3 x (1 + 2 + 3 + … + 333) + 5 x (1 + 2 + 3 + … + 199 ) – 15 x (1 + 2 + 3 + … + 66)

I’ll leave you to find out how these series can be summed.

After all, Project Euler tells us not to give out spoilers :D

PS. Hint, hint, arithmetic progression sums.