Sunday, June 26, 2016

Android Development - Access Activity Instances from Other Classes

Each page on Android app is defined by an activity instance or an object. Sometimes, you may want to edit the instance externally, i.e., from other objects or classes. The following code shows how to do access the instance of MainActivity class externally:

...
public class MainActivity extends Activity {
  private static MainActivity instance;
  private static void setInstance (MainActivity instance) {
    MainActivity.instance = instance;
  }
  public static MainActivity getInstance () {
    return instance;
  }
  public void somePublicMethod () {
  ...
  }
  public void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_main);
    setInstance (this);
    ...
  }
  ...
}

As you can see from the code above, static variable instance is to be assigned in the onCreate method. Now, this instance can be accessed externally by calling the public getInstance method, as shown below:

...
public class SomeClass {
  public void someMethod () {
    MainActivity.getInstance().somePublicMethod();
  }
}

This method is called singleton design, as there is only one instance of the Activity class, which we want to access externally.

Thursday, June 23, 2016

Android Development - Schedule a Task at Certain Time

First, you will need to edit the manifest xml file and add the following:

...
<manifest ... >
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    ...
    <application ... >
       <receiver android:name=".AlarmReceiver" />
    </application>
</manifest>

The permission will enable the Android system to wake up at the specified time. The receiver field declares BroadcastReceiver element to be used. Here, I will be using the name AlarmReceiver.

Next, create AlarmReceiver.java file with something similar to below:

...
public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        wl.release();
    }

    public void setAlarm(Context context) {
        AlarmManager alarmManager;
        PendingIntent pi;

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent (context, AlarmReceiver.class);
        pi = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pi);
    }
}

Here, setAlarm method is specifying the scheduled time to be 5 secs after the current time. At that time, onReceive method will be invoked, so you will need to place your tasks there.

Finally, edit your activity java file to add the following code to schedule:

Context context = this.getApplicationContext();
AlarmReceiver alarm = new AlarmReceiver();
alarm.setAlarm(context);

That's it!

Android Development - How to Make Buttons Respond

In the series of Android Development posts, I will go over the very basics of Android programming intended for complete beginners. I won't be able to explain every singe details of the code, so one will need to refer here for general details.

Say you have a button that you would like to respond when a user tabs on it. In the layout xml file in the res folder, you will need to have your button element defined similar to below:

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/send"
        android:onClick="buttonAction" />

The necessary field for assigning any actions to "clicks" on the button is the last field, android:onClick="buttonAction". What it says is that when the user pushes on the button, the program will execute buttonAction function. Of course, we will need to define such function in the activity java file.

...
public class MainActivity extends Activity {
...
    public void buttonAction(View v) {
        // insert code for action
    }
...
}

That's it!

Saturday, June 11, 2016

C/C++ #define Directive Not-So-Obvious Mistake

Consider the following code below:
#include <stdio.h>
#define ABS(x) (x>=0 ? x : -x)
int abs (int x) {
   return x >= 0 ? x : -x;
}
int main () {
   printf ("ABS(1) = %d\n", ABS(1));
   printf ("ABS(-1) = %d\n", ABS(-1));
   printf ("ABS(2-1) = %d\n", ABS(2-1));
   printf ("ABS(1-2) = %d\n", ABS(1-2));
   printf ("abs(1) = %d\n", abs(1));
   printf ("abs(-1) = %d\n", abs(-1));
   printf ("abs(2-1) = %d\n", abs(2-1));
   printf ("abs(1-2) = %d\n", abs(1-2));
   return 0;
}

The code defines the absolute value evaluation procedure using both the C directive and a regular subroutine. In the main function, we are printing out four example values to verify if both methods work correct. What do you think the expected output would be?

Guess the answer first, and copy the code run it.
$ gcc ABS_test.c
$ ./a.out

Does your guess agree with the output? If so, then you must be an experienced C/C++ programmer! If not, do not worry. I did not get it the first time either. Both the C directive ABS(x) and C subroutine abs(x) are defined by the same expression, but one is erroneous while the other is fine. 

It turns out that the ABS(x) directive definition is incorrect and requires an extra parenthesis pair around last x:
#define ABS(x) (x>=0 ? x : -(x))

This is because the C directive is simply literal, replacing whatever expression in the parenthesis of ABS(...) into the definition. Below is actual code that is being compiled by the compiler:
ABS(1) ---> 1 >= 0 ? 1 : -1
ABS(-1) ---> -1 >= 0 ? -1 : --1
ABS(2-1) ---> 2-1 >= 0 ? 2-1 : -2-1
ABS(1-2) ---> 1-2 >= 0 ? 1-2 : -2-1

So, it should now be clear to you why the last expression's output was -3! By the way, the subroutine abs(x) is fine because the compiler will evaluate the value of whatever in the parenthesis of abs(...) before actually calling the function.

Friday, June 3, 2016

How to Setup SSH Login Email Alert for Mac OS X

This tutorial will discuss how to setup email alert for ssh login to your Mac OS X system. In particular, this has been tested on El Capitan only, but I am pretty sure that it should work with other versions as well. This is based on this post with slight modification.

First, create /etc/ssh/sshrc file with the following content
#!/bin/bash
ADDRESS="your_email@example.com"
IP=`echo $SSH_CONNECTION | cut -d " " -f 1`
DATE=`date`
echo "User $USER just logged in from $IP at $DATE" | mail -s "ssh login alert" "$ADDRESS"

Make sure to enter your own email address above to receive the alert mails. Set the owner of the file as root and set the execution flag.
$ sudo chown root /etc/ssh/sshrc && sudo chmod u+x /etc/ssh/sshrc

By the way, make sure there is no ~/.ssh/rc file, because the above script file won't be executed if ~/.ssh/rc file exists. To see more details on this, read sshd manual and search for sshrc
$ man sshd
/sshrc

This should do it. Make sure to check your spam folder for the alert mails.

Friday, May 27, 2016

How to Setup L2TP VPN Server on Mac OS X El Capitan (non-server version)

In this post, I will go over how to setup L2TP VPN server on your Mac OS X El Capitan (non-server version). It will be based on the excellent post from Jon but with slight modifications.

Before you start doing this, make sure the following ports are not blocked by your router or ISP.
UDP 500 for ISAKMP/IKE
UDP 1701 for L2TP
UDP 4500 for IPsec NAT Traversal

Usually, you should be able to configure your router to enable these ports for designated IP address. Therefore, you would probably need to assign static IP address for your to-be-server machine first, based on the physical address, and then open up the ports necessary.

Now, let us dive into the setup. First, create /Library/Preferences/SystemConfiguration/com.apple.RemoteAccessServers.plist file with the following content
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>ActiveServers</key>
  <array>
    <string>com.apple.ppp.l2tp</string>
  </array>
  <key>Servers</key>
  <dict>
    <key>com.apple.ppp.l2tp</key>
    <dict>
      <key>DNS</key>
      <dict>
        <key>OfferedSearchDomains</key>
        <array/>
        <key>OfferedServerAddresses</key>
        <array>
          <string>168.126.63.1</string>
          <string>8.8.4.4</string>
        </array>
      </dict>
      <key>IPv4</key>
      <dict>
        <key>ConfigMethod</key>
        <string>Manual</string>
        <key>DestAddressRanges</key>
        <array>
          <string>192.168.0.201</string>
          <string>192.168.0.255</string>
        </array>
      </dict>
      <key>Interface</key>
      <dict>
        <key>SubType</key>
        <string>L2TP</string>
        <key>Type</key>
        <string>PPP</string>
      </dict>
      <key>L2TP</key>
      <dict>
        <key>IPSecSharedSecret</key>
        <string>com.apple.ppp.l2tp</string>
        <key>IPSecSharedSecretEncryption</key>
        <string>Keychain</string>
        <key>Transport</key>
        <string>IPSec</string>
      </dict>
      <key>PPP</key>
      <dict>
        <key>AuthenticatorACLPlugins</key>
        <array>
          <string>DSACL</string>
        </array>
        <key>AuthenticatorPlugins</key>
        <array>
          <string>DSAuth</string>
        </array>
        <key>AuthenticatorProtocol</key>
        <array>
          <string>PAP</string>
        </array>
        <key>LCPEchoEnabled</key>
        <integer>1</integer>
        <key>LCPEchoFailure</key>
        <integer>5</integer>
        <key>LCPEchoInterval</key>
        <integer>60</integer>
        <key>Logfile</key>
        <string>/var/log/ppp/vpnd.log</string>
        <key>VerboseLogging</key>
        <integer>1</integer>
      </dict>
      <key>Server</key>
      <dict>
        <key>Logfile</key>
        <string>/var/log/ppp/vpnd.log</string>
        <key>MaximumSessions</key>
        <integer>128</integer>
        <key>VerboseLogging</key>
        <integer>1</integer>
      </dict>
    </dict>
  </dict>
</dict>
</plist>
Make modifications in line 19-20 and 29-30. Lines 19-20 will be your DNS addresses whereas lines 29-30 will be the start and end client addresses to be assigned by the server. Make sure that these addresses do not overlap with your router's assignment. 

Next, change the owner of the file by
$ sudo chown root:wheel /Library/Preferences/SystemConfiguration/com.apple.RemoteAccessServers.plist

and change the access control by
$ sudo chmod 644 /Library/Preferences/SystemConfiguration/com.apple.RemoteAccessServers.plist

Now you will need to provide the L2TP secret phrase. Run the following command where you replace SHARED-SECRET-PHRASE with your own.
$ sudo security add-generic-password -a com.apple.ppp.l2tp -s com.apple.net.racoon -T /usr/sbin/racoon -p "SHARED-SECRET-PHRASE" /Library/Keychains/System.keychain

Create /Library/LaunchDaemons/com.apple.ppp.l2tp.plist with the following content
 <?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN”
“http://www.apple.com/DTDs/PropertyList-1.0.dtd“>
<plist version=”1.0″>
    <dict>
        <key>Label</key>
        <string>com.apple.ppp.l2tp</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/sbin/vpnd</string>
            <string>-x</string>
            <string>-i</string>
            <string>com.apple.ppp.l2tp</string>
        </array>
        <key>OnDemand</key>
        <false/>
    </dict>
</plist>

Finally, you need to load the launchd config and start the daemon after reboot:
$ sudo launchctl load -w /Library/LaunchDaemons/com.apple.ppp.l2tp.plist

If you want to disable VPN service and not start the daemon after reboot, run
$ sudo launchctl unload -w /Library/LaunchDaemons/com.apple.ppp.l2tp.plist

Now, you  should be able to connect to your VPN server! To login, use your Mac OS X's username and password.

Thursday, May 26, 2016

How to Install OPENCV on Mac OS X with libstdc++ for CUDA

Installing opencv on Mac OS X has been painful for me because the older version of CUDA toolkit does not support libc++, while the default compilation option for OS X's clang is to use libc++ instead of libstdc++. Due to this issue, I kept getting errors like
undefined symbols for architecture x86_64: "cv::imread(std::string const&, int)" referenced from ...

So, in this post, I will cover how to install opencv on Mac OS X using libstdc++ and successfully run CUDA programs.

The easiest way is to use homebrew to install opencv. If you already do not have homebrew installed on your Mac OS X system, please refer here.

First, we will need to edit the default make option. To do so, run the command
$ brew tap homebrew/science
$ brew edit opencv

You may want to replace option "32-bit" with option "64-bit" in line 15, although I am not sure if this makes any difference.

Next, add a line with -DCMAKE_CXX_FLAGS:STRING=-stdlib=libstdc++ into line 76, after which it should read something like below:
      args = std_cmake_args + %W[
        -DCMAKE_OSX_DEPLOYMENT_TARGET=
        -DBUILD_ZLIB=OFF
        -DBUILD_TIFF=OFF
        -DBUILD_PNG=OFF
        -DBUILD_OPENEXR=OFF
        -DBUILD_JASPER=OFF
        -DBUILD_JPEG=OFF
        -DCMAKE_CXX_FLAGS:STRING=-stdlib=libstdc++
        -DJPEG_INCLUDE_DIR=#{jpeg.opt_include}
        -DJPEG_LIBRARY=#{jpeg.opt_lib}/libjpeg.#{dylib}
      ]

By the way, this formula file can also be edited by the following command
$ vim /usr/local/Library/Taps/homebrew/homebrew-science/opencv.rb

To restore the file back to the original, you may run
$ cd /usr/local/Library/Taps/homebrew/homebrew-science
$ git checkout -- opencv.rb

To restore all formula files in the folder to the default, you may run
$ git reset --hard HEAD

Now, you may proceed to install opencv, but make sure to compile it from source
$ brew install --build-from-source opencv

Please note that it will take quite some time to build the library, so please be patient. After complete, you may want to verify whether it has been compiled with libstdc++
$ otools -L /usr/local/Cellar/opencv/2.4.12_2/lib/libopencv_imgproc.dylib
libopencv_imgproc.dylib:
/usr/local/opt/opencv/lib/libopencv_imgproc.2.4.dylib (compatibility version 2.4.0, current version 2.4.12)
/usr/local/Cellar/opencv/2.4.12_2/lib/libopencv_core.2.4.dylib (compatibility version 2.4.0, current version 2.4.12)
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 104.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)

As you can see, opencv has been compiled against libstdc++ instead of libc++. Now, you will be able to run your CUDA programs. Note, however, that you will need to ask g++ to link against libstdc++ as well. That is, for example, compile with the option as shown below:
$ g++ your_program.cxx -stdlib=libstdc++

How to Run CUDA on Mac

I have a mid-2010 mac mini, which is equipped with NVIDIA's GeForce 320m integrated graphics chip. Although the official list of CUDA-supported devices does not include GeForce 320m, this chip indeed supports CUDA.

To install CUDA driver and toolkit, download the toolkit for Mac OS X platform from NVIDIA's website. Note that I tried installing toolkit v7.5, but it did not work. The older version v6.0 worked fine, so you probably want to download it instead. After download, simply install it on the system. You will notice that, however, it runs very well until you reboot your system.

In order to fix this issue, you will need to do the following:

1. If you are running El Capitan, disable OS X's System Integrity Protection (SIP). See the instructions here.

2. The following instruction was provided by canemacchina from here. I am reproducing it below.

Create /System/Library/LaunchDaemons/com.nvidia.cuda.launchd.plist file with the content

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>com.nvidia.cuda.launchd</string>
        <key>ProgramArguments</key>
        <array>
                <string>/sbin/kextload</string>
                <string>/System/Library/Extensions/CUDA.kext</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
<key>UserName</key>
        <string>root</string>
</dict>
</plist>

Next, set the owner of the file
$ sudo chown 0:0 /System/Library/LaunchDaemons/com.nvidia.cuda.launchd.plist

Finally enable the daemons
$ sudo launchctl load -w /System/Library/LaunchDaemons/com.nvidia.cuda.launchd.plist

That's it. Now you will be able to run CUDA on your old Mac.

How to Mount Mac OS X's HFS+ Partition in Ubuntu 14.04 LTS

To mount HFS+ partition, one first needs to install the necessary package:
$ sudo apt-get install hfsprogs

Next, create the mounting directory
$ sudo mkdir /media/mntpoint

Next, mount the partition
$ sudo mount -t hfsplus -o force,rw /dev/sdXY /media/mntpoint
where sdXY can be something like sda1, sda2, sda3, sdb1, sdb2, sdb3, etc.

To unmount, run the command
$ sudo umount /media/mntpoint

If you are not sure whether the exfat partition you are looking for is /dev/sda1 or /dev/sda2, then you could also run
$ sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL

Thursday, May 19, 2016

Transition from C to C++: Struct vs. Class

Here, I will write about some of the changes that a C programmer should be aware of when transitioning into C++.

Some key differences between class and struct:
  1. In C, struct holds a chunk of data. In C++, class also holds a chunk of data but in addition it also defines some methods related to it.
  2. All the fields in struct is visible to anyone, while the fields are private by default in class.
  3. In C, you need the keyword struct as the identifier, whereas in C++ you do not need the keyword class.
  4. In C++, you also have a static field. However, it needs to be declared globally; Otherwise you will get a linker error.
The following code summarizes the differences:

// C++
class Class {
int data1; // private by default
char data2; // private by default
public:
   static int length; // static variable
class Class* method1() {...}; // public method that returns pointer to Class object.
Class* method2() {...}; // class identifier is not necessary
};

int Class::length; // must declare it globally

// C
struct Struct {
int data1; // public by default
char data2; // public by default
};
struct Struct* func1() {...} // a function that returns a pointer to struct Struct. struct identifier is necessary