SyntaxHighlighter JS

2013-02-22

Eliminate JavaScript global variables

Global variables in JavaScript can be overwritten, resulting in bugs. For example,

<html><head>
<script>
var counter = 0;

function increaseCounter() {
    ++counter;
    alert("Counter is " + counter);
}
</script>

<script>
var counter="A";
</script>
</head><body><form>
    <input type="button" value="Increase Counter" onclick="increaseCounter();" />
</form></body></html>

will output "Counter is NaN" when the button is clicked.

Global variables in JavaScript can be eliminated by closures. For example the previous JavaScript can be refactored as,

<html><head>
<script>
var CounterJS = (function() {
    var counter = 0;

    return {
        increaseCounter: function() {
            ++counter;
            alert("Counter is " + counter);
        }
    }    
}());
</script>

<script>
var counter="A";
</script>
</head><body><form>
    <input type="button" value="Increase Counter" onclick="CounterJS.increaseCounter();" />
</form></body></html>

2013-02-21

Initialize Map

Sometimes code is more clear by initializing a Map at its declaration. For example,

Map<String,String> map = new HashMap<String,String>() {{
    put("Key 1", "Value 1");
    put("Key 2", "Value 2");
}};

Behind the Java scenes, this is a combination of an anonymous inner class (the first outer set of brackets) and an instance initializer block (the second inner set of brackets).

Landscape mode in Android emulator

To change to landscape mode in Android emulator, press the left ctrl+F11 buttons. For Mac, use fn+ctrl+F11.

2013-02-20

15 minutes of vim

  • How do I start using vim?
    If you have a text file called MyDoc.txt, enter the following command in the terminal prompt:

    vim MyDoc.txt

  • How do I start inserting text?
    Press the "esc" button and then press the "i" button. Start typing your text.

  • How do I move the cursor around?
    Use the arrow keys.

  • How do I quit vi?
    Press the "esc" button and then type :q

  • How do I quit vi without saving the file?
    Press the "esc" button and then type :q!

  • How do I save a file?
    Press the "esc" button and then type :w

  • How do I undo my changes?
    Press the "esc" button and then press the "u" button.

  • How do I redo my changes?
    Press the "esc" button. Then hold the "control" button down while pressing the "r" button (Ctrl+r).

  • How do I delete text?
    Press the "esc" button and then press the "x" button. Press the "x" button again to delete the next letter.

  • How do I search?
    If you are searching for the text "findme", press the "esc" button and then type /findme

  • How do I find next after search?
    Press the "esc" button and then press the "n" button.

  • How do I replace?
    If you want to replace the text "findme" with "replacedme", first move to the line with the text "findme". Press the "esc" button then type :s/findme/replacedme/

  • How do I replace all?
    Press the "esc" button and type type :1,$s/findme/replacedme/g
    1,$ means "From line 1 to the end of the file" (I remember $ with the mnemonic "cash out last")
    s means substitute
    g means globally
    "From line 1 to the end of file, substitute findme with replacedme globally"

  • Where can I learn more about vim without being overwhelmed?
     Vi Editor Reference Manual 

Programmers' Motivation

Why do some computer programmers and developers become demotivated with and quit high paying jobs? Given that compensation is fair compared to our peers, developers' motivation is driven by three factors (AMP) :
  •  Autonomy
    Developers hate being told what to do, especially if it is an action we consider stupid. We want to feel in control of the decisions affecting our job.

    The solution is not to micromanage. Give developers freedom to make our own decisions. Build a consensus and give developers a voice in the decision making process.

  • Mastery
    Developers fear not being technically relevant because of job security and peer recognition. Developers love learning new skills.

    The solution is to give us opportunities to try new technologies and techniques on the job. Even though it might cause short term pain and slowdown, do not let good developers get stuck in a monotonous routine. "I'm bored" is one of the most devastating and demoralizing phrase we can utter on the job.

  • Purpose
    Developers want our jobs to have meaning and serve a bigger cause. That purpose may be "My software generates $10 million dollars in revenue" or "My code makes people's lives better".  What specific purpose is important to developers depends on our individual personalities.

    The solution is to build a narrative on why we are doing a project. Do not just concentrate on what we are doing and how we are doing it. Give us a grand vision and purpose to our code and our work.
Source:
  1. Drive by Daniel H. Pink
  2. RSA Animate video about Drive

2013-02-18

Gain Mac disk space by deleting sleepimage

If you have a SSD for your MacBook Pro, you know that disk space is a premium. Deleting the file /var/vm/sleepimage can recover as much disk space as you have physical memory (8GB in my case).

In Terminal, type in the commands below. Since these are admin level commands, you may be prompted for the admin password.

sudo pmset -a hibernatemode 0
sudo rm /var/vm/sleepmode

By default, when a newer Mac transition into sleep mode, it stores the memory content onto the file /var/vm/sleepmode. Setting hibernatemode to 0 keeps the sleep memory contents in RAM memory. The  advantage to hibernatemode 0 is that you save disk space and the Mac sleeps and wakes a little faster. The disadvantage is hibernatemode 0 uses a little more power during sleep and if the Mac runs out of power during sleep then all memory content is lost.

Read text file from classpath

Sample Problem:
You need to read a text file, like a properties or XML file. But FileInputStream and FileReader are returning a FileNotFoundException.

Solution:
FileInputStream and FileReader need the absolute physical file path to read a file. Hard coding the absolute file path makes the program not portable to different machines. It is better practice to read the text file on the Java classpath.
  1. Read the text file with ClassLoader.getResource
    Use the Java class loader to read the file. For example, let's assume you need to read the text file application.properties from the class TextTest.java. The config directory is where application.properties is located.

    To read the file, use the code below to get an InputStream from the file.

    URL fileUrl = TextTest.class.getClassLoader().getResource("application.properties");
    System.out.println("Absolute File Path " + fileUrl.getPath());
    InputStream in = fileUrl.openStream();

  2. Set the classpath to the directory with the text file
    Include the path to the text file directory in the java classpath and run the program

    java -cp .:config TextTest

2013-02-16

Show all files in Mac Finder

Open Terminal and enter commands

    defaults write com.apple.Finder AppleShowAllFiles YES
  killall -KILL Finder

2013-02-06

Android Interview Questions: Level 1

These are basic entry-level Android interview questions suitable to ask over the phone.

  • What is an Activity?
    An activity is a single, focused thing a user can do. Usually an activity is associated with one UI window.

  • What are the lifecycle methods of an Activity?
    onCreate(Bundle): Activity initializer method.
    onStart(): Activity is about to become visible.
    onResume(): Activity visible in foreground. Called after creation and after pausing.
    onPause(): method invoked when user leaves the Activity. Usually partial UI visible.
    onStop(): Activity is no longer visible.
    onRestart()
    onDestroy(): called when Activity removed from memory

  • What do you usually do in the Activity onCreate method?
    1.) First call super.onCreate(Bundle) to execute superclass initializer
    2.) Initialize the UI by calling method setContentView(View) to define the UI layout and findViewById(int) to interact with UI widgets
    3.) Initialize any resources or saved state needed by the Activity

  • What do you usually do in the Activity onPause method?
    1.) First call super.onPause() to execute superclass method
    2.) Stop and release CPU and battery intensive resource used by Activity, e.g. camera, animation, GPS.
    3.) Save user changes. Note: do resource intensive saves like database or cloud writes in onStop() method.

  • When can an Activity be destroyed?
    When the back button is presses, when the screen rotates, when the finish()method is called, when the activity has been stopped for a long time and resource is reclaimed.

  • How do you save state data before an Activity is destroyed?
    Override the onSaveInstanceState(Bundle) method. To restore the activity state data, override onRestoreInstanceState(Bundle).

  • What is a Bundle?
    A Bundle can be used to save and restore instance state information of an Activity in the onSaveInstanceState and onRestoreInstanceState methods.

    private static final String STATE_MSG_KEY = "stateMsgKey";

    @Override
    public void onSaveInstanceState(Bundle saveState) {
        saveState.putString(STATE_MSG_KEY, "message value:);
        super.onSaveInstanceState(saveState);
    }

    @Override
    public void onRestoreInstanceState(Bundle saveState) {
        super.onRestoreInstanceState(saveState);
        String msgVal = saveState.getString(STATE_MSG_KEY);
    }


  • How can you tell if an Activity is new or has been restored?
    In the onCreate(Bundle) method, check to see if the Bundle parameter is null. If Bundle is null, then the Activity a new instance. If Bundle is not null, then the Activity has been restored.
  • How can you permanently save Activity data?
    Use SharedPreferences.

    private static final String PERM_MSG_KEY = "permMsgKey";
    private writeMessage() {
        SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor e = sp.edit();
        e.putString(PERM_MSG_KEY, "message value");
        e.commit();
    }

    private readMessage() {
        SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
        String msgVal = sp.getString(PERM_MSG_KEY, "default value");
    }

  • How do you define the "main" Activity that first gets called when you launch your app?
    In file AndroidManifest.xml, add the MAIN action and LAUNCHER category in the activity intent-filter.

    <activity android:name="com.jirawat.MainActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


  • What is the AndroidManifest.xml file?
    This file contains all the essential information necessary to run an Android app. For example, it lists the minimum Android version required, the Java classes defining the activities, and user permissions necessary to run the app.

  • Where do you define the layout of the app UI?
    In XML files located at directory res/layout

  • Where do externalize text and string resources for the app?
    In the file res/values/strings.xml

  • What is R.java?
    During app compilation, the class R.java is automatically generated by aapt (Android Asset Packaging Tool). You can use the R.java class to access resources defined in the res directory from Java code.

    For example, to access the UI layout defined in the file res/layout/main_layout.xml in Java code, use R.layout.main_layout. To access text defined by the key app_name in res/values/strings.xml, use R.string.app_name.

  • How do you convert a string in string.xml into a Java string?
    String appName = getResources().getString(R.string.app_name);

  • What is an Intent?
    An Intent is an object that provides runtime bindings between separate components. An Intent can be used to start and communicate between two activities or apps.

  • How does an activity start another activity?
    Create an Intent then call the method startActivity with that Intent as a parameter.

    Intent intent = new Intent(this, ReceiveActivity.class);
    intent.putExtra("com.jirawat.MSG_KEY", "message value");
    startActivity(intent);


  • How do you get a result Intent back from another activity?1.) Use startActivityForResult instead of startActivity
    2.) Process result Intent in onActivityResult method

    private static final int REQUEST_CODE=314;

    private void sendActivityIntent() {
        Intent intent = new Intent(this, ReceiveActivity.class);
        intent.putExtra("com.jirawat.MSG_KEY", "message value");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if ( (requestCode == REQUEST_CODE) && (resultCode = RESULT_OK) ) {
            // Process result Intent
        }
    }


  • How do you specify the Android version the app supports?In file AndroidManifest.xml, add the uses-sdk xml element.
    <manifest>    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="11" /></manifest>

  • How do you check Android version in Java code?
    boolean isFroyoOrHigher =
      (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO);


  • What is a Fragment?
    A Fragment is a sub-activity. It is a UI or behavior that can be placed inside another parent Activity. It is used to create dynamic UI for different screen sizes.

  • How do you add fragments?
    Either via the fragment XML segment in the res/layout file or using the FragmentManager in the onCreate method.

    MyFragment f = new MyFragment();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.fragment_container,f);
    ft.commit();