Tuesday, September 11, 2018

How scope behaves in JS (let, block scope)


scope refers to the lifecycle of the variable, ie, where in the code its visible and how long

Understand "What is not a block scope"
curly braces doesnt mean block scope,
{
 // its not a block scope, but a global scope
 var a = "mytest"
}
console.log(a) // prints mytest

var a inside block overrides var a in function scope, so not a block scope

function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    var a = "override";
  }
  console.log(a)
  // prints "override" as said the curly braces don't signify block scope.
}


So how to declare block scope variable ?
ImmediatelyInvokedFunctionExpression (IIFE)


(function () {
  var a = "correct block scope";
})()

ie, the above myfun becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    (function () {
      var a = "right block scope";
    })()
  }
  console.log(a) // prints "function scope" .
  // because variable a inside IIFE is in block scope.
}

With ES6 we have "let" keyword, use inplace of "var" keyword. This creates a variable with block level scope. So myFunc becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    let a = "right block scope";
  }
  console.log(a) // prints "function scope" .
}

var a is only visible between the for-loop and not outside the loop

Ex:

var myFuncArray = [];
for (let i = 0; i < 5; i++) {
  myFuncArray.push(function(){
    console.log(i);
  })
}

myFuncArray.forEach((myfun) => {
  myfun(); //prints 0...4
});

for more JS quirks click here...

Thursday, July 07, 2016

Crossing the CORS

Cross Origin Resource Sharing by which you let others to access the api's hosted on your domain. 
Below (nginx) example adds the headers to default.conf file
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With, accept, content-type';
Below are few links that I used for my reference.
Any client side Javascript can make calls to other website which has the above rule set. Be careful while setting  Access-Control-Allow-Origin to '*', as this allows anyone to hit your api/website

Tuesday, May 07, 2013

How to use SQLite Db in the Android Development


SQLite is a self-contained i.e., having all the modules and dependencies with in it & does not depend much on external libraries. This is one of the important reasons why most of the embedded devices use SQLite as temporary storage. Well-known examples are Google, Mozilla Firefox, Apple, Adobe and Android devices. It has zero-configuration with out any separate process for installation or configuration.

Android has 2 main packages, which lets us to use SQLite in the application. android.database and android.database.sqllite has all the necessary api's for create/read/update and delete actions.
Also SQLiteOpenHelper class provides public methods like onCreate, onUpgrade, onOpen methods. onCreate is called whenever the database is created for first time, onOpen when the DB has been opened and onUpgrade when the databased needs to be upgraded.

A database handler class which implements the SQLiteOpenHelper should call the constructor to create helper object to create, open or manage database. Constructor takes database name & database version. See below.

public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

As a first step to implement SQLite, the database handler class should extend SQLiteOpenHelper. In the constructor method call the super() method by passing the context, database name and version.

         public DatabaseHandler(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
         }

Database handler class should also implement the onCreate & onUpgrade methods. onCreate method is called by framework when the DB is created for the first time and onUpgrade method is used whenever DB tables need to be updated.
ex:
         public void onCreate(SQLiteDatabase db) {
                  // Category table create query
                  String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
                  db.execSQL(CREATE_CATEGORIES_TABLE);
         }

// Upgrading database
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                  // Drop older table if existed
                  db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
                  // Create tables again
                  onCreate(db);
         }

For any read/write operation, SQLiteOpenHelper class provides getReadableDatabase() & getWritableDatabase() respectively. These methods returns reference to SQLiteDatabase object which can be used to create, read, update and delete from tables. For ex, below example shows Create/Open database.

         SQLiteDatabase db = this.getReadableDatabase();

         // Create/open a database for read/write operation.
         SQLiteDatabase db = this.getWritableDatabase();

The db object returned from the getReadableDatabase & getWritableDatabase provides create(), insert(), delete(), update() methods.
         Ex: insert takes table name, optional null column and content values that need to be inserted into the table.
         // Inserting Row
                  db.insert(TABLE_LABELS, null, values);

We can write query in 2 ways, First is raw query like "select * from ", "insert into" etc. and second one is structured query. For this SQLiteDatabase provides 2 methods query() & rawQuery().

query() methods provides structured interface which takes table name, array of columns that needs to be fetched, filter column (for WHERE clause), groupBy, orderBy, having and limit. Example below.

         db.query(TABLE_NAME, String[] columnNames, String[] selection, group by, having, order by);

rawQuery() takes the raw sql just like any sql database. ex
         db.rawQuery("select * from TABLE_NAME", null);

Both query() & rawQuery() returns something called Cursor object. Cursor is not actual result set; rather it is an object that is positioned before the first row of the result set. The handler class should iterate through the cursor object to get through all rows.
ex:
                  Cursor cursor = db.rawQuery(selectQuery, null);
                  // Looping through all rows and adding to list
                  if (cursor.moveToFirst()) {
                           do {
                                    cursor.getString(1);
                           } while (cursor.moveToNext());
                  }
Cursor.get*(), methods are the way to access columns of each rows.

All the above methods insert(), read(), delete() etc. should implement close() method to close db & cursor operations.

                  // closing connection
                  cursor.close();
                  db.close();

Reference materials:

Friday, April 19, 2013

CSS Specificity

Many times wondered in which order the styles are applied to document elements. When you are working on a bigger project or old projects which was written by ex-developers (no offense here) wondered how to over write a particular style or write a style so it has the higher precedence over other style.
We have more ways to add styles to a documents inline Style & external Style both containing

  •  Id (#) selector, 
  • class (.) selector, 
  • attribute selector (input[type=password]),
  • pseudo-classes (:link, :hover:, :visited, :focus, :active) , 
  • pseudo-elements (:before, :after, :first-line, :first-letter, :first-child)


All the above mentioned style have a rating/priority which is used while style the document.
ex: As we know  Id (#) selector has precedence over any other selection since ID is unique in a document and obviously they have the highest rating. Any style (inline or external) given using the ID is considered before class, pseudo elements.
ie, with inline style like below

  1. <style> #test {  text-decoration:"line-through"; }</style> 
  2. <a id="test" style="text-decoration:line-through;">Test</a>

has the higher specificity that any other style given to the above element.
similarly while considering external stylesheet, the first style (1) has the higher specificity that (2).

Example 1- a#test {  text-decoration:"line-through"; }
Example 2-  a[id=test] { text-decoration:"none"; }

How is the specificity calculated.
  1. # (id) selector takes 100 points 
  2. . (class, attribute, pseudo) selectors take 10 points
  3. type selector, pseudo-element selector take 1 points.
Considering the above example (1 & 2) we can easily say that example 1 style is always selected over example 2. Having said that, there is always some thing beyond the above 3. That is the inline style. Irrespective of any thing, the style attribute takes higher precedence/specificity over any thing (ie it has value 1000 points).





Wednesday, June 27, 2012

How to develop an IPhone Location App


You can say the continuation to my prev article on how to use the HTML5 GeoLocation api, but its different this time. It uses Objective C to get the location details rather than using HTML5.

Is building IOS App easy ?

I asked my self this question many times with out knowing how easy it is  before I attended the work shop conducted by Dr.Barbara Hecker.

My 4th App (other than my 3 hello world app) I created this Location Detection app which detects your position and displays latitude & longitude on the iPhone screen.

All you need is  Xcode (I used Xcode Version 4.3.3), IOS 5 SDK, iPhone Simulator and little bit of scripting knowledge :)

For who know how to create an app this should be simple.

Create new project using a Single View Application. This will create a default ViewController Interface & Implementation class (ViewController.h and ViewController.m). Download the code from here

To implement the location interface all you need to know about is LocationManager in IOS. This CLLocationManage is the interface to deliver the location events. The main objective is to deliver event, create instance and attach a delegate (CLLocationManageDelegate) object to it.
For more info on LocationManager refer this link.

In this I used the below properties
1) delegate property for configuring the updates
2) startUpdatingLocation to start the updates 

Make sure you import CoreLocation library (Target > Build Phases > Add CoreLocation under Link binary with libraries. It took me quite a while to figure it out properly. If you get "undefined symbols for architecture i386 _OBJC_CLASS_$_CLLocationManager" don't be panic)

Cut to chase, below is the sample implementation details.

//  ViewController.h
#import
#import
@interface ViewController : UIViewController

<CLLocationManagerDelegate
{
    IBOutlet UITextField *latitudeText;
    IBOutlet UITextField *longitudeText;
    CLLocationManager *locMgr;
}

@property (retain,nonatomic) IBOutlet UITextField *latitudeText;
@property (retain,nonatomic) IBOutlet UITextField *longitudeText;

@property (weak, nonatomic) IBOutlet UIButton *locationDetect;

@end

Using the story board I added 2 text fields (for latitude & longitude) and control+click on the textFields and drag it to interface class. This will create property for each text fields like below

@property (retain,nonatomicIBOutlet UITextField *latitudeText;

Also I created button, which on click will get the location.

Below is my implementation class

//  ViewController.m
#import "ViewController.h"
@implementation ViewController

@synthesize latitudeText,longitudeText,locationDetect; 
CLLocationManager *locMgr;

......
- (void)viewDidLoad
{
    [super viewDidLoad];
    locMgr = [[CLLocationManager alloc]init];
    [locMgr startUpdatingLocation];
}

......

- (IBAction)locationDetect:(id)sender {
    NSString *latitudeTextData = [[NSString
                                   alloc]initWithFormat:@"%g",locMgr.location.coordinate.latitude];
    NSString *longitudeTextData =[[NSString alloc]
                                  initWithFormat:@"%g",locMgr.location.coordinate.longitude];
    self.latitudeText.text = latitudeTextData;
    self.longitudeText.text = longitudeTextData;
}

@end

In this I created a LocationManager object and started the location update process by using the startUpdatingLocation method.  Then capture the values from the location manager and update the text field.

Isn't quite simple ;)







Wednesday, April 18, 2012

GeoLocation API HTML5

Finding the user location with HTML5 GeoLocation API is quite simple. I have been experimenting Geo api, just sharing what I learned. Follow the reference given below for more understanding.

Geolocation can be obtained from navigator object like navigator.geolocation.

First step check whether your browser supports geolocation. If not fall back to native javascript.

if(navigator.geolocation)
else alert("your browser doesn't support geolocation")

geolocation object has 3 methods

  • getCurrentPosition
  • watchPosition
  • clearWatch


getCurrentPosition & watchPosition looks similar and takes same arguments.

ex:

navigator.geolocation.getCurrentPosition(success, error, {map of geolocation options});

success = function(position) {
position.coords.latitude ;
position.coords.longitude  ;
position.coords.accuracy;
};

failure = function(error) {
// 3 types of error

1: 'Permission denied',
2: 'Position is not available',
3: 'Request timeout'

};

Failure return error code  of 1,2,3.


The third argument for both getCurrentPosition and watchPosition is the geolocation options which is optional.
 1) enableHightAccuracy - takes boolean true/false, enables the device to get more accurate latitude & longitude positions
2) timeout - time allowed for the device to get the data. keep it zero will let the browser to never timeout (in milliseconds). Setting to 2000 will wait for 2000 milliseconds before it quits with REQUEST TIME OUT error code 3.
3) maximumAge - lets the browser to use the cached data. if set to zero will always look up new position for each request.

I have made a small demo which is still in work in progress.

Reference:
Geolocation API Specification
HTML5 By Bruce Lawson and Remy Sharp

Friday, April 06, 2012

Boolean Attribute vs Boolean Value

If you are writing some thing using HTML5 then you need to understand their Boolean Attributes which is not same as what you think as true or false.Thanks to the Boolean father George Boole

Boolean attribute doesn't need any value set as true or false,  require=required.
Then how to use Boolean Attribute in your HTML ?
just add this attribute and do not assign any value. What .. Yes, its up to you if you want to assign you can.

Lets see the below example.
< input type=text name="user" disabled / >

You can use disabled=disabled or disabled=true.  Both has same meaning or just keep it simple and use "disabled" as I said the very existence of them makes meaning KISS principle

List of HTML5 Boolean Attributes

Thursday, February 17, 2011

How to create custom permission using Spring ACL 3.0.5

How to create custom permission using Spring ACL


Create a MyOwnPermission class which extends BasePermission
Add new Permission like

public static final Permission ROLE_ACCEPT = new MyOwnPermission(1 << 5, 'C'); // 32

The mask & char code should not be same as the one from BasePermission, here I am using 32 as mask Spring 3.05 no more lets you to register your MyOwnPermission like below. 

public final class MyOwnPermission extends BasePermission { 
   static { 
       BasePermission.registerPermissionsFor(MyOwnPermission.class) 
   } 


As per Luke Taylor (Senior Member, Acegi Security System TeamSpring Team) 
"You can inject a PermissionFactory into the BasicLookupStrategy and it will be used to generate the Permission objects. The DefaultPermissionFactory can be used to register additional permissions."

I did the below. I inject my MyOwnPermission class to one of MyOwn LookupStrategy implementation class. 

public class MyOwnLookupStrategy implements LookupStrategy  { 
     private PermissionFactory pf = new MyOwnPermissionFactory(); 
...
}

and the MyOwnPermissionFactory will be like 

public class MyOwnPermissionFactory extends DefaultPermissionFactory {
   public MyOwnPermissionFactory() { 

      super(); 
      registerPublicPermissions(MyOwnPermission.class); 
   } 
}  

Refer Jira:SEC-813  & Jira:SEC-1022

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/domain-acls.html

For more info see thread  Springsource Forum:93416


Tuesday, November 09, 2010

innodb vs myisam

Apparently MyISAM is faster than InnoDB
The only advantage InnoDB has over MyISAM is that it supports row locking, while MyISAM only supports table locking.

Therefore, if lots of reads and writes are constantly being done to a very large table, it eliminates the constant database errors that using a MyISAM table would cause from the overload.

InnoDB would therefore be a tad more reliable when you don't mind taking a small performance hit in exchange for not suffering from table locking issues.

one other thing I found is
while using Hibernate commit statements, myISAM works even with out commit statement, but InnoDB requires commit for every transaction. its advantaeous providing rollback support.

more here

Monday, October 11, 2010

Remove duplicates from an Array

String[] array = {"A", "X", "G", "X", "A"};

Set set = new HashSet(Arrays.asList(array));
String[] array2 = (String[])(set.toArray(new String[set.size()]));

A set is a collection object that cannot have a duplicate values, hence converting the array to a set removes the duplicate values.

java.lang.UnsupportedOperationException on java.util.AbstractList

java.lang.UnsupportedOperationException: null
at java.util.AbstractList.remove(AbstractList.java:144) ~[na:1.6.0_04]
at java.util.AbstractList$Itr.remove(AbstractList.java:360) ~[na:1.6.0_04]
at java.util.AbstractCollection.remove(AbstractCollection.java:252) ~[na:1.6.0_04]

Arrays.asList(Object[]) returns type Arrays$ArrayList is of (extends) type AbstractList.

Arrays$ArrayList does not override remove(int) so the method is called on the superclass AbstractList

new LinkedList(Arrays.asList(String[] something));

Use any List implementation that supports a modifyable result. In the above, LinkedList works because, instantiates a new modifiable list using the immutible list created from Arrays.aslist(...).

Saturday, October 09, 2010

Kapalabhati Pranayam.

This is my first non technical post. But is this really non-tech, no its a technical for body... none of us really cared about what our mind/body needs..
Spending 20 mins for our-self is not a big deal. You can do it early morning or before lunch or before dinner. We do spend lot of our time in social networking activities. Can we not steal some time (not more that 20 mins) and give our mind/body what it needs ?

*tip:
Morning after Kapalabhati take a glass of lemon juice in warm water. GFH :)

Kapalabhati can be done by siting in Padmasana or Sitting on chair in erect posture.

http://www.beautyandgroomingtips.com/2006/12/kapalabhati-pranayam.html

Wednesday, August 18, 2010

java.net.BindException: Address already in use: JVM_Bind:8080

This occurs when 8080 port is already used by other application. Check the server.xml in tomcat and change the port as shown below.



this should solve the java.net.BindException: Address already in use: JVM_Bind :80

happy deployment :)

Get table count in MySQL

I was looking for this and got idea from Roland Bouman forum http://forums.mysql.com/read.php?100,48568,48737#msg-48737. Thanks Naveen for (the second query) letting me know this.
1)
select count(*) as number_of_tables from information_schema.tables
where table_schema = 'my_database_schema' and table_type = 'BASE TABLE'
2)
select TABLE_SCHEMA, TABLE_TYPE, ENGINE, count(1)
FROM information_schema.tables GROUP BY TABLE_SCHEMA, TABLE_TYPE, ENGINE;

Wednesday, March 24, 2010

HTML5 Application Framework

SproutCore is an HTML5 application framework for building responsive, desktop-caliber apps in any modern web browser, without plugins.

yea dil mange more >>


yea dil mange demo>>



Thursday, March 18, 2010

ResourceBundle Message Implementation in Spring

Add below in context.xml

beans:bean id="msource" class="org.springframework.context.support.ResourceBundleMessageSource"
beans:property name="basename" value="classpath:mymessages.properties"


-----------------------------------

mymessages.properties
my.user.already.exist={0} already exist!
my.update={0} updated successfully!
my.delete={0} deleted successfully!


---------------------------------------------
Last step just do an autowire in the controller class

@Autowired
@Qualifier("msource")
private MessageSource mymess;

and in the functions use it like below
mymess.getMessage("my.user.already.exist", new Object[] { "Username chandra"}, null)

the Object[] can take multiple params based on the message u want to display
ex:Username {0} cannot be deleted because {1}

--- :)

Saturday, March 13, 2010

How to use base64 to add a basic authentication to an HTTP request.

Use the "Authorization", "basic "+encodedpassword like below.
import org.apache.commons.codec.binary.Base64;

String userpasswd = username+":"+password;
String encodedString = new String(Base64.encodeBase64(userpasswd.getBytes()));
....
and in ur httpconnection object add the below
conn.setRequestProperty("Authorization","Basic "+encodedString);

...

URL url = new URL("https://fyi.com");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization"....


if (conn instanceof HttpsURLConnection)
((HttpsURLConnection) conn).setHostnameVerifier(DNV);
conn.connect();

how to use "Content-Disposition" for file download via http(s)/ftp server

Content-Disposition Header Field
This is an optional field. Never thought this could save my ass.
It has a wonderful param "filename" thru which we can out the content of the file to be downloaded. If you don't use it, the file will download with the servlet name.
Ex: /fyi/myservlet.do
While downloading the file, the dialog prompts to save file with myservlet.do which is really odd & when ur downloading a zip file the name says "save file myservlet.do"

If you dont understand any (:-) thing above see the below code.

response.setHeader("Content-Disposition", "attachment; filename="+ filename);

URL url = new URL("https://fyi/downloadfile/filename.zip");
conn = (HttpsURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
response.setContentType(conn.getContentType());
response.setContentLength(conn.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ filename);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while ((size = in.read(buf)) >= 0) {
out.write(buf, 0, size);
}
in.close();
out.close();
}

try urself.

to know more about content-disp..

Wednesday, February 17, 2010

Spring - Finding the last user name in controller

HttpSession ss = request.getSession();
ss.getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)

AuthenticationProcessingFilter is depricated use UsernamePasswordAuthenticationFilter instead

Click here for more details

This will be useful, when u want to redirect to different page from your Authentication Providers using form-login tag in http security.

form-login login-page="/login.do" default-target-url="/something.do" authentication-failure-url="/loginfailure.do"

http://rubyconfindia.org

I'm supporting RubyConf India 2010