Miscellaneous Ruby Commands

Ruby break Statement:

Syntax:

break

Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i > 2 then
      break
   end
   puts "Value of local variable is #{i}"
end

This will produce the following result:

Value of local variable is 0
Value of local variable is 1
Value of local variable is 2

Ruby next Statement:

Syntax:

next

Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      next
   end
   puts "Value of local variable is #{i}"
end

This will produce the following result:

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5

Ruby redo Statement:

Syntax:

redo

Restarts this iteration of the most internal loop, without checking loop condition. Restartsyield or call if called within a block.

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      puts "Value of local variable is #{i}"
      redo
   end
end

This will produce the following result and will go in an infinite loop:

Value of local variable is 0
Value of local variable is 0
............................

How to format Date in Java – SimpleDateFormat Example

SimpleDateFormat in Java is used to format Date in Java. You can format date on any String format based upon various attribute available in SimpleDateFormat class e.g. mm, dd, YYetc. You can also put timezone information in formatted Date using Z attribute of DateFormat class. SimpleDateFormat is sub class of DateFormat and provide format() and parse()method to convert Date to and from String in Java. Worth noting is that SimpleDateFormat is not thread-safe and should not be shared with others. Avoid using static SimpleDateFormat inJava classes. If you want to share SimpleDateFormat or want to make it thread-safe, you can use ThreadLocal variable in Java to avoid sharing SimpleDateFormat among multiple threads.parse() method of SimpleDateFormat throws ParseException if String input is not a valid date or can not be parsed into mentioned format.

How to format Date in Java

In order to format dates using SimpleDateFormat, we first needs to define a String date format e.g. “dd-MM-yyyy”will print dates in that format e.g. 01-11-2012. You can defined format based upon identifiers supported bySimpleDateFormat class. e.g. d means day of month, y means year and M means Month of year. Javadoc ofSimpleDateFormat has complete list of supported Date and Time patterns . Once you create a DateFormat, you can just call format() method which accept java.util.Date and returns String, which is formatted Date. In this way you can alsoconvert Date to String in Java. SimpleDateFormat formats date in same pattern which is provided to it while creating instance ofSimpleDateFormat. You can also include time information e.g. hour, minutes and seconds while formatting dates by using HH, mm and SS time pattern. DateFormat class also supports inclusion of timezone in formatted date String by z and Z. If you use z you can show timezone information as abbreviation e.g. PST, IST etc. If you use Z you provide timezone, relative to GMT e.g.+0530. In next section we will see couple of SimpleDateFormat example in Java to get hands on on date formatting.

SimpleDateFormat Example in Java

Here is complete code example of How to format Date in Java using SimpleDateFormat. In this example we will see simple date formatting without time information e.g. dd-MM-yyyy, Date formatting with time information with patterns like dd-MM-yyyy:HH:mm:SS and Dates with timezone information in it e.g. dd-MM-yyyy:HH:mm:SS z or dd-MM-yyyy:HH:mm:SS Z.

import java.text.SimpleDateFormat;
import java.util.Date;

/**
*
* Java program to show how to format date in Java using SimpleDateFormat
* Examples. Java allows to include date, time and timezone information
* while formatting dates in Java.
*
* @author http://java67.blogspot.com
*/
public class DateFormatExample {

public static void main(String args[]) {

// This is how to get today’s date in Java
Date today = new Date();

//If you print Date, you will get un formatted output
System.out.println(“Today is : ” + today);

//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(“dd-MM-yyyy”);
String date = DATE_FORMAT.format(today);
System.out.println(“Today in dd-MM-yyyy format : ” + date);

//Another Example of formatting Date in Java using SimpleDateFormat
DATE_FORMAT = new SimpleDateFormat(“dd/MM/yy”);
date = DATE_FORMAT.format(today);
System.out.println(“Today in dd/MM/yy pattern : ” + date);

//formatting Date with time information
DATE_FORMAT = new SimpleDateFormat(“dd-MM-yy:HH:mm:SS”);
date = DATE_FORMAT.format(today);
System.out.println(“Today in dd-MM-yy:HH:mm:SS : ” + date);

//SimpleDateFormat example – Date with timezone information
DATE_FORMAT = new SimpleDateFormat(“dd-MM-yy:HH:mm:SS Z”);
date = DATE_FORMAT.format(today);
System.out.println(“Today in dd-MM-yy:HH:mm:SSZ : ” + date);

}

}

Output:
Today is : Fri Nov 02 16:11:27 IST 2012
Today in dd-MM-yyyy format : 02-11-2012
Today in dd/MM/yy pattern : 02/11/12
Today in dd-MM-yy:HH:mm:SS : 02-11-12:16:11:316
Today in dd-MM-yy:HH:mm:SSZ : 02-11-12:16:11:316 +0530

That’s all on these SimpleDateFormat Example in Java. We have seen How to format date with time and timezone information in Java. Though using SimpleDateFormat is most easy way to format Date in Java but it also has its own set of problems. It’s notthread-safe and should be used carefully. Avoid using DateFormat as static variable, don’t share SimpleDateFormat betweenmultiple threads, result is unpredictable if it’s shared among multiple threads.

Courtesy : http://java67.blogspot.in/2013/01/how-to-format-date-in-java-simpledateformat-example.html

JQuery After() And InsertAfter() Example

For example,

<div class="someRandomClass">Yo Yo!</div>
<div class="someRandomClass">Yo Sup!</div>

1. $(‘selector’).after(‘new content’);

$('.someRandomClass')
.after("<div class='someOtherRandomClass'>Fight Club!</div>");

2. $(‘new content’).insertAfter(‘selector’);

$("<div class='someOtherRandomClass'>Fight Club!</div>")
.insertAfter('.someRandomClass');

Result

Both methods above are doing the same task, but with different syntax, the new contents after after() or insertAfter() will become

<div class="someRandomClass">
   Yo Yo!
</div>
<div class='someOtherRandomClass'>Fight Club!</div>
 
<div class="someRandomClass">
   Yo Sup!
</div>
<div class='someOtherRandomClass'>Fight Club!</div>

Python: csv.DictReader

csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect=’excel’, *args,**kwds)

Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order. These elements become the keys of the resulting dictionary. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. If the row read has more fields than the fieldnames sequence, the remaining data is added as a sequence keyed by the value of restkey. If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional restval parameter. Any other optional or keyword arguments are passed to the underlyingreader instance.

A short usage example:

>>> import csv
>>> with open('names.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...

So if you have a csv with First Name & Last name as the headers in the first row , the command row[‘first_name’] would give the field under that keyword(First Name) row by row. This was very very useful for my implementation.

Python: With command

Given below is an example of opening a file, manipulating the file, then closing it:

with open('output.txt', 'w') as f:
    f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Shell Scripting – Grep

Grep searches the named input FILEs (or standard input if no files are named, or the file name is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

More info can be seen at http://www.tutorialspoint.com/unix_commands/grep.htm

Eg : grep “STRING %pathtofile% | cut -d -f2

        Search for a string in a file  , the “pipe” connects the stdout of one command to the stdin of another , cut with dlimiter ” and select the second term (-f2)

Python – Accessing Command Line Arguments

Python provides a getopt module that helps you parse command-line options and arguments.

$ python test.py arg1 arg2 arg3

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purpose:

  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example:

Consider the following script test.py:

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

Now run above script as follows:

$ python test.py arg1 arg2 arg3

This will produce following result:

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

NOTE: As mentioned above, first argument is always script name and it is also being counted in number of arguments.

Courtesy : http://www.tutorialspoint.com/python/python_command_line_arguments.htm

Additional notes from VJ : –

If there are arguments that are provided along with the python file, then within the python file this argument can be accessed like this : –

sys.argv[1]  -> for 2nd argument
sys.argv[2] -> for 3rd argument

Note: sys.argv[0] is the python script name as mentioned above

Regards,
VJ