Saturday, 4 June 2016

Simple PL/SQL code to throw NO_DATA_FOUND exception

Background

Good database question for beginners.Write a simple PL/SQL code snippet to throw NO_DATA_FOUND exception. You cannot raise this exception. Maybe try to understand how the candidate answers this. Simple code is as follows - 

DECLARE
   nowt VARCHAR(10);
BEGIN
   SELECT * INTO nowt FROM DUAL WHERE 1=0;
END;
/

and it should throw the exception - 

Error starting at line 8 in command:
DECLARE
   nowt VARCHAR(10);
BEGIN
   SELECT * INTO nowt FROM DUAL WHERE 1=0;
END;
Error report:
ORA-01403: no data found
ORA-06512: at line 4
01403. 00000 -  "no data found"
*Cause:    
*Action: 


Related Links

Simple program to create deadlock between two threads and it's fix

Background

This is one of the very basic Java multithreading question - to write a simple java program to demonstrate a deadlock. So in this post I will provide code to demonstrate that - 


Java code to create deadlock between two threads

Code is as follows - 

/**
 * 
 * @author athakur
 * Simple deadlock program
 */
public class Deadlock {
    
    public static void main(String args[]) {
        
        final Object resourceOne = "res1";
        final Object resourceTwo = "res2";
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                
                synchronized(resourceOne) {
                    System.out.println(Thread.currentThread().getName() + " accquired resource 1");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized(resourceTwo) {
                        System.out.println(Thread.currentThread().getName() + " accquired resource 2");
                    }
                }
            }
        }).start();
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                synchronized(resourceTwo) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " accquired resource 2");
                    synchronized(resourceOne) {
                        System.out.println(Thread.currentThread().getName() + " accquired resource 1");
                    }
                }
            }
        }).start();
        
    }

}


Copy above code in Deadloc.java file, compile and run it. You should see following output in console - 
Thread-0 accquired resource 1
Thread-1 accquired resource 2

And the program should hang.

Explanation

Thread 1 acquires lock over resource 1 and goes to sleep for 2 seconds. After sleep it would try to acquire lock on resource 2. When thread 1 was sleeping, thread 2 acquired lock over resource 2 and went to sleep for 2 seconds. After 2 seconds thread 2 would try to acquired lock on resource 1. Now it does not matter which thread wakes up. It will not be able to get lock on inner resource as other thread has acquired it and waiting for other to release. This will led to deadlock.

How to resolve this deadlock?

You can use Reentrant locks introduced in Java 1.5 to check if lock is available before locking it or you can do a timed lock (If lock is not available in x time move on). 

Another way to resolve this is to always have a fixed order to acquire lock. So both T1 and T2 threads will always lock resource 1 before trying to acquire lock on resource 2. This breaks the cycle that can lead to deadlock.

There is more more stupid way to prevent deadlock. When you are spawning new threads from main thread call join from main thread on all new threads before calling start() on next thread. Stupid? I know. It is same as single threaded application as you are executing threads sequentially. 

Couple of tips that may come handy -
  • don't use multiple threads (like Swing does, for example, by mandating that everything is done in the EDT)
  • don't hold several locks at once. If you do, always acquire the locks in the same order
  • don't execute foreign code while holding a lock
  • use interruptible locks



Related Links

Sunday, 29 May 2016

Greasemonkey script to block Game of Thrones spoilers

Background

Greasemonkey is a Firefox plugin that runs user scripts just like tampermonkey in chrome. In this post we will see a simple script that will blacklist certain words appearing in Game of thrones which will potentially be spoilers.


Greasemonkey script to block Game of Thrones spoilers

Script is as follows -


// ==UserScript==
// @name           Spoiler Killer
// @include        http://*.facebook.com/*
// @include        https://*.facebook.com/*
// @require        http://code.jquery.com/jquery-1.7.1.min.js
// @require        https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant          none
// @version 1
// @namespace http://opensourceforgeeks.blogspot.in/
// @description Blacken facebook posts possibly containing Game of Thrones spoilers.
// copied from https://gist.github.com/vshivam/94d18c5d652217a449a5b785cbda1073
// ==/UserScript==

(function(){
    var terms = ['spoiler', 'game of thrones', 'hodor', 'jon snow', 'khaleesi', 'stark', 'dothraki'];
    function actionFunction(node){
        var content = node.html();
        content = content.toLowerCase();
        $.each(terms, function(index, term){
            if(content.indexOf(term) > -1){
                var overlay = $('<div />' ).css({
                     position: "absolute",
                     width: "100%",
                     height: "100%",
                     left: 0,
                     top: 0,
                     zIndex: 1000000,
                     background: "#000000",
                 });
                (function(overlay, node){
                    overlay.appendTo(node.css("position", "relative"));
                    $(node).on("mouseenter", function(){
                        overlay.hide();
                    });
                    $(node).on("mouseleave", function(){
                        overlay.show();
                    });
                })(overlay, node);
            }
        });
    }
    waitForKeyElements("div.userContentWrapper", actionFunction);
})();


NOTE : This script is copied over from https://gist.github.com/vshivam/94d18c5d652217a449a5b785cbda1073.  It's original version can be found at https://gist.github.com/vshivam/9080a0b5ece35689163ed12955c131a9 (simply replaces text)

Script essentially blackens the posts that contain spoiler words. Feel free to add/remove words as you choose suitable. Make sure that the script is running on the site you intend it to be. You can test that from  Greasemonkey icon near URL bar. See following screenshot for details -




Related Links


Pushing existing local project to Github

Background

We have seen before how to clone a remote repository to local, work on it, modify files, commit and push to remote repository. But most of the time what happens we have a project on local (a new one) and want to save it on github. In this post we will see how to do that.



Pushing existing local project to Github

You will need to initialize a new repository on Github first. Simple create an empty repository.




Now to add your local repo you can execute following commands -
  1. mkdir MyTestRepo
  2. cd MyTestRepo/
  3. touch test.txt
  4. git init
  5. git add .
  6. git commit -m "First commit"
  7. git remote add origin https://github.com/aniket91/MyTestRepo.git
  8. git push -f origin master

Output is as follows -


You can then see this commit on remote.

After creating a new repo on github you will see following options -



Related Links

Saturday, 28 May 2016

Installing Git in Ubuntu

Background

Sometime back I had written a post about git (it's installation and usage in windows). This post simple covers it's Linux counterpart. How to install git in Ubuntu.

 Installing git on Ubuntu

To install git execute following command -
  • git apt-get install git-core

 Post installation you can run following command to verify installation -

  •  git --version


 And you are all good to go!

To set up git config you can use following command -
  •  git config --global user.name "aniket91"
  •  git config --global user.email "you@example.com"
To view the config  you can do
  •  git config --list
or view the config file
  •  cat ~/.gitconfig



Try cloning a repository
  • git clone https://github.com/aniket91/DataStructures.git

My Git Repositories


Avoid Merge Commits

Whenever you have unpushed commits on your local and you try to do a git pull after those commits it will create a merge commit .
To avoid it follow one of the below mentioned methods,

  1. run git pull --rebase 
  2. To avoid running it with the rebase flag and to make the above the default behavior when pulling changes, git config --global branch.autosetuprebase always 
  3. In SourceTree under tools->options/preferences under the Git tab select "Use rebase instead of merge by default for tracked branches"

Related Links

t> UA-39527780-1 back to top