Tuesday, 16 June 2015

Set focus at contenteditable end text

contenteditable="true" means it is not any input type. it is just a div. but when you click on that div it will acts as text field. so, in this how can we set the focus at end of text? it is not possible with .focus(). by using the following code it is possible.


HTML:
<div contenteditable="true" id="chk">vamsi</div>

SCRIPT:

$(document).ready(function(){
    $('#chk').click(function(){
        placeCaretAtEnd( document.getElementById("chk") );
    });
});

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}



Friday, 3 April 2015

JQuery Tips useful in coding

1.

$('li[data-selected="true"] a')  // Fancy, but slow
$('li.selected a')  // Better
$('#elem')  // Best

jQuery Cloning

jQuery supports cloning - you can use the clone() method to create a clone of any DOM element in your web page. Here is an example:
var cloneObject = $('#divObject').clone();
The $(document).ready function is called during page render, i.e., while the objects are still being downloaded in the web browser. To reduce CPU utilization while a page is being loaded, you can bind your jQuery functions in the $(window).load event. Note that this event is fired after all objects have been downloaded successfully. This would improve the application performance to a considerable extent as the page load time would be minimized. Other common ways to improve jQuery performance are by compressing the scripts and limiting DOM manipulation as much as possible.
Consider the following piece of code that appends a DOM element inside a loop:
for (var ctr=0; ctr<=rows.length; ctr++)
{
$('#tableObject').append('<tr><td>'+rows[ctr]+'</td></tr>');
}
The above code can be replaced by a more efficient piece of code to minimize DOM manipulation and hence improve application performance as shown below:
var str = '';
for (var x=0; x<=rows.length; x++)
{
str += '<tr><td>'+rows[x]+'</td></tr>';
}
$('#tableObject').append(str);

Jquery : Disabling right click

$(document).ready(function(){
      $(document).bind("contextmenu",function(e){
           return false;
      });
});

Wednesday, 25 March 2015

Javascript : Get 3 months back date from current

    function fun(){
        var d = new Date(2015,2,25);
        d.setMonth(d.getMonth() - 3);
        alert((d.getDate()+'/'+(d.getMonth()+1))+'/'+d.getFullYear());
    }

Tuesday, 10 March 2015

Java : deepToString()

java.util.Arrays class has many useful methods to perform the operations on the arrays. deepToString() method is one such method. Arrays.deepToString() method is used to get the string representation of multidimensional arrays. This method returns the deep contents of the specified array. If the specified array contains other arrays as it’s elements then it returns the contents of those arrays also.

Below example shows how to use deepToString() method to print the contents of the multidimensional arrays.


OUTPUT:



If you want to print the contents of one dimensional arrays, then use Arrays.toString() method or normal for loop or enhanced for loop. You can also use Arrays.deepToString() method to print the contents of one dimensional arrays. But, If you want to print the contents of multidimensional arrays, instead of nesting multiple for loops, use Arrays.deepToString() method. It is the easiest method to print the contents of multidimensional arrays.

Friday, 6 March 2015

Random Numbers

If you are a software developer, you may have come across the requirement of generating random numbers in your application. While developing any kind of applications, you often need to generate random numbers. In Java, it is easy to generate random numbers using some in-built methods and classes. In this article, we will see three different ways to generate random numbers in java. Let’s start with the definition of random numbers.

What Is Random Number?

“Randomness” is something which is totally unpredictable and unbiased. Random number is a number picked randomly from the given set of numbers. There will be no relation or dependency between the two successively picked numbers.

Random Number Generator :

An ideal Random Number Generator is the one which generates a series of numbers in the given range where,

Each possible number have equal probability of picking up.
There will be no relation or dependency between the previously generated number and the present one.
How To Generate Random Numbers In Java?

Java provides two ways to generate random numbers. One is using java.util.Random class and another one is using Math.random() method. There is one more method introduced in JAVA 7. It is using ThreadLocalRandom class. We will discuss all three methods in this article.

Generating Random Numbers Using java.util.Random Class :

Using java.util.Random class, you can generate random integers, doubles, floats, longs and booleans. Below is the program which generates random integers, doubles and booleans using java.util.Random class.


Output :
Random Integers : 238886529
Random Integers : 1463682739
Random Integers : -1247541726
Random Integers : 34314299
Random Integers : 1658793122
—————————–
Random Doubles : 0.7443798462870127
Random Doubles : 0.8382139571324086
Random Doubles : 0.9680505961503302
Random Doubles : 0.5623901155047567
Random Doubles : 0.37285000690287773
—————————–
Random booleans : false
Random booleans : true
Random booleans : false
Random booleans : false
Random booleans : false

Note : Integers generated are in the range of -231 and 231-1. Generated doubles are in the range from 0.0 to 1.0.

Generating Random Numbers Using Math.random() :


Output :
Random Doubles : 0.7783847001873636
Random Doubles : 0.3895881606319488
Random Doubles : 0.4798586710671108
Random Doubles : 0.6203717760219122
Random Doubles : 0.7460629328768049

Generating Random Numbers Using ThreadLocalRandom Class :

java.util.concurrent.ThreadLocalRandom class is introduced in Java 7. Below program shows how to generate random integers, doubles and booleans using ThreadLocalRandom class.


Output :
Random Integers : -1626309835
Random Integers : 332111237
Random Integers : -1585909207
Random Integers : 1070972416
Random Integers : -1874591696
—————————–
Random Doubles : 0.7840295282815645
Random Doubles : 0.36849802111866514
Random Doubles : 0.6551894273753474
Random Doubles : 0.5993075213578543
Random Doubles : 0.7289343843664791
—————————–
Random booleans : true
Random booleans : false
Random booleans : false
Random booleans : true
Random booleans : true

Generating Random Numbers In The Given Range :

Below is the java program which generates random integers in the range from 0 to 50 using all three methods – Random class, Math.random() and ThreadLocalRandom class.


Output : 

Random integers between 0 and 50 using Random class : 16 12 30 26 17 
Random integers between 0 and 50 using Math.random() : 12 43 42 32 45 
Random integers between 0 and 50 using ThreadLocalRandom 12 40 16 17 3 




How to change localhost domain name

Step 1: 1st open notepad with "Run-AsAdministrator".

Step 2: Open the .file from the following location

              C:\Windows\System32\drivers\etc\hosts.file

Step 3: Coustomize the 127.0.0.1 with your Domain Name, Please follow the following pic for better clarification.


Before Modification:

After Modification:


- By Sai Ram Rajulapati

Tuesday, 3 March 2015

HashTable

Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.


Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>();

here the key is an integer and value is string datatype.

Ex: hashtable.put(1, "Apple");

similarly,

Hashtable<String, String> hashtable = new Hashtable<String, String>();

Ex: hashtable.put("IN", "INDIA");

here the key and value both are strings.

functions:

hashtable.clear();

it clears the all data with in hashtable.

hashtable.isEmpty();

it returns a boolean value, based on the hashtable is empty or not.

hashtable.size();

it returns how many records are available in hashtable.

hashtable.containsKey("key");

it returns a boolean value. it checks the key is existed or not in hashtable.

hashtable.containsValue("value");

it returns a boolean value. it checks the value is existed or not in hashtable.

hashtable.get("key");

it returns the value based on given key.

hashtable.remove("key");

it removes the record based on given key. it returns the deleted key value.

hashtable.put("key", "value");

it returns the previous value of given key.

hashtable.putAll(treeMap);

it sets all treeMap values to hashtable.

Set<String> set = hashtable.keySet()

it returns the set of keys in hashtable.

Enumeration<String> enumeration = hashtable.keys();

it returns the set of keys in hashtable.



Enjoy and Happy Coding....

what is purpose of treeMap and hashSet

treeMap is sets the data in ascending order.
hashSet didn't allow any duplicates.

Tuesday, 24 February 2015

How to shut down through Java Program


                                                                                                                            - By Sai Ram Rajulapati

Sunday, 25 January 2015

Java : TreeSet

TreeSet is another popular implementation of Set interface along with HashSet and LinkedHashSet. All these implementations of Set interface are required in different scenarios. If you don’t want any order of elements, then you can use HashSet. If you want insertion order of elements to be maintained, then use LinkedHashSet. If you want elements to be ordered according to some Comparator, then use TreeSet. The common thing of these three implementations is that they don’t allow duplicate elements.

In this article, I have tried to explain two examples of Java TreeSet. One example doesn’t use Comparator and another example uses Comparator to order the elements. You can go through some basic properties of TreeSet class here.

Java TreeSet Example With No Comparator :

You already know that if you don’t pass any comparator while creating a TreeSet, elements will be placed in their natural ascending order. In this example, we create a TreeSet of Integers without supplying any Comparator like this,



Java TreeSet Example With Comparator :

In this example, we create one TreeSet by supplying a customized Comparator. In this example, we will try to create a TreeSet of Student objects ordered in the descending order of the percentage of marks they have obtained. That means, student with highest marks will be placed at the top.

Let’s create ‘Student’ class with three fields – id, name and perc_Of_Marks_Obtained.








Monday, 19 January 2015

JQuery : Key Press Validations

// Allow only alphabet keys in textfiled

$(document).ready(function () {
    $("#inputTextBox").keypress(function (event) {
        var inputValue = event.which;
        //if digits or not a space then don't let keypress work.
        if ((inputValue > 64 && inputValue < 91) // uppercase
        ||
        (inputValue > 96 && inputValue < 123) // lowercase
        ||
        inputValue == 32) { // space
            return;
        }
        event.preventDefault();
    });
});

// Allow only numerics in text field

$(document).ready(function () {
    $("#inputTextBox").keypress(function (event) {
       var charCode = (event.which) ? event.which : event.keyCode
         if(charCode==8)//back space
            return true;
         if (charCode < 48 || charCode > 57)//0-9
         {
            //alert("Please Enter Only Numbers.");
            return false;
         }
           
         return true;
    });
});

Wednesday, 7 January 2015

Grails : How to send a mail


Step 1 : create account in https://mandrillapp.com/login/

Mandrill is a scalable and affordable email infrastructure service, with all the marketing-friendly analytics tools you’ve come to expect from MailChimp.

step 2 : goto settings > smtp & API info

Step 3 : select API key. it generates one api key

step 4 : Add compile ":mail:1.0.7" in BuildConfig.groovy at plugins

step 5 : In config.groovy, place below mail settings

grails {
mail {
 host = "smtp.mandrillapp.com"
 port = 587
 username = "your@mail.com"
 password = "apikey"
 props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"587"]
 
}
}

In above code, mandrill username & api key

Step 6 : In your controller inject mail services like shown in below

def mailService

def yourAction(){

mailService.sendMail {
multipart true
//to "sender1@mail.com","sender2@mail.com"
//to "sender@mail.com"
from "support@mail.com"
subject "Subject"
body 'body content'
//attachBytes "test.zip", " application/x-compressed", new File('D:/delete/test.zip').bytes
attachBytes 'new year.jpg','image/jpg', new File('D:/delete/new year.jpg').readBytes()
html  g.render( template: '/admission/mailTemplate')
//attachBytes 'Penguins.jpg','image/jpg', new File('D:/delete/Penguins.jpg').readBytes()
//attachBytes 'Penguins.jpg','image/jpg', new File('D:/delete/Penguins.jpg').readBytes()
 
  }
}

Step 7 : clean your project

Step 8 : run the application

Step 9 : call yourAction and then mail will be send.

Thank U.. Happy Coding..

How to protect our folder with different passwords

Java : ListIterator and JDBC PreparedStatement

Tuesday, 6 January 2015

Index of release/org/springframework/spring/4.1.4.RELEASE

Java : HashSet


Java HashSet is very powerful Collection type when you want a collection of unique objects. HashSet doesn’t allow duplicate elements. HashSet also gives constant time performance for insertion, removal and retrieval operations. It is also important to note that HashSet doesn’t maintain any order. So, It is recommended to use HashSet if you want a collection of unique elements and order of elements is not so important. If you want your elements to be ordered in some way, you can use LinkedHashSet or TreeSet.

In this Java article, we will see one real time example of HashSet.

Let’s create one HashSet of Student records where each Student record contains three fields – name, rollNo and department. In these, rollNo will be unique for all students.

Let’s create Student class with three fields – name, rollNo and department.



You can notice that hashCode() and equals() methods are overrided in the above class so that two Students objects will be compared solely based on rollNo. That means, two Student objects having same rollNo will be considered as duplicates irrespective of other fields.

Create one HashSet object containing elements of Student type.










How to provide security to your folder with password


Step 1 : create one folder
Step 2 : create one text document with any name ( Ex: secure.txt )
Step 3 : Copy the given code and paste it in your file

@ECHO OFF
title Folder Private
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Private goto MDLOCKER
:CONFIRM
echo Are you sure you want to lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Private "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo Enter password to unlock folder
set/p "pass=>"
if NOT %pass%== ENTER YOUR PASSWORD HERE goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Private
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Private
echo Private created successfully
goto End
:End


Step 4 : in above code, enter your password at "ENTER YOUR PASSWORD HERE"
Step 5 : 'Save As' this with .bat extension ( Ex: secure.bat )
Step 6 : remove that original file
Step 7 : Now the file like given below img 1

img 1

Step 8 : If u double click on this, it shows 'private' folder


Step 9 : in this folder,copy your documents ( Ex: data.txt )


step 10: double click on secure.bat then type 'Y' press 'Enter'. the folder disappear.


step 11: again double click on it shows like this


step 12: enter your password as you are given and press 'Enter'
step 13: it shows private folder. your documents are existed in it.


Advantages:

- It is hides the documents
- these type of securities used in offline war deployment

Disadvantages:

- It can be decode easily with logical effort
- It is not provided 100% security

Java Script : How to sort Javascript arraylist of objects


//How to sort Javascript arraylist of objects
The table like as shown in the figure.

 <script>
$(function(){
        // Intialized table id with datatable jquey
var table = $('#receiptsList').dataTable();

// ArrayList
var feeList = [];

$(table.fnGetNodes()).each(function(i){
var record = new Object();
record.receiptNo = $('button',table.fnGetData(i)[0]).text();
record.admissionNo = table.fnGetData(i)[1];
record.name = table.fnGetData(i)[2];
record.paidDate = table.fnGetData(i)[3];
record.paidAmount = table.fnGetData(i)[4];
record.paidType = table.fnGetData(i)[5];
record.userName = table.fnGetData(i)[6];

// Object added to arrayList
feeList.push(record);
});

// Sorting is called
         feeList.sort(SortByField);

});

function SortByField(a, b){
 var aName = a.receiptNo;
 var bName = b.receiptNo;
 return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

</script>

Finally arraylist sorted receiptNo wise.

Grails : How to set default value in domain class


// How to set default value in domain class

package com.gb.vamsi

import com.gb.vamsi.common.BaseEntity

class User extends BaseEntity{

String firstName
String lastName
Long accountId
String displayName
String jobRole
String photoUrl
Date lastLogin
boolean chatStatus

static constraints = {
photoUrl nullable:true
lastLogin nullable:true
}

static mapping = {
chatStatus defaultValue:true
}
}

// Here chatStatus by default true