Sunday, October 13, 2013

jQuery Tutorial - quick & rough

This is a quick, rough tutorial (It can contain mistakes)

I) jQuery selectors & jQuery Cheat Sheet:
-------------------------------------------------------------
Look at the Table here:
http://stevewellens.xtreemhost.com/jQuerySelectorTester.htm

Some points (to be read with the table in above link as reference) -

1. jQuery selectors are placed within single quotes.
E.g.
i.    $('#myid')
ii.   $('[id=myid]')
iii.  $('[id="my id"]')    - Double quotes are needed if there is a whitespace in the value of the attribute

2. Return value of a 'jQuery selector' is usually an array of elements
except when we use shortcuts like # and . shortcuts
E.g. $('#myid')   and  $('.myCSSclass')

3. Most important selector to know:
$('element[attribute="value"]')
E.g.   $('input[id="abc"]')  - select all 'input' tags with "abc" as their ids.
Note - this returns an array of elements; to use only one,
we have to use the 0th index one -
E.g. $('input[id="abc"]')[0].hide()

Since selecting an element based on its 'id' attribute is probably the most commonly used selector,
jQuery has a shortcut for it - using #
E.g.   $('#abc')   or   $('input#abc')
Note - this is not just a shortcut for the syntax; this returns only 1 element
(If there are multiple elements with the same 'id', it returns the 1st one)


II) Most Commonly used jQuery statements:
------------------------------------------------------------
0. Selecting elements using substring-of-their-id/name
$('#abc') - an element with id as 'abc'
$('[id^="abc"]')  - array of elements with id starting with 'abc'
$('[id$="abc"]')  - array of elements with id ending with 'abc'
$('[id*="abc"]')  - array of elements with id containing 'abc'

1. Hide/Show an element
$('#abc').hide()
$('#abc').show()

2. Get html contained within a div
$('#abc').html()

3. Replace html within a div with some other html (contained within a string)
var str_html = " This is going to be the new content";
$('#abc').html(str_html)

4. Change a CSS attribute - use css(attribute_name, attribute_value)
$('#abc').css("color","red")

5. Add/Remove a CSS class  - especially useful when using Bootstrap
$('#abc').addClass("myClass")
$('#abc').removeClass("myClass")

6. Find 'parent', 'siblings'
$('#abc').parent()
$('#abc').siblings()



III) functions in javascript

-----------------------------------
Functions in Javascript can be passed as values to other functions.
This is typically used w.r.t Event Handlers & Callbacks (to ajax calls)

Supposed we want some code to be executed when an event happens;
we wrap that code with the 'function' keyword and curly {} braces, and
pass that as an argument to the event-handler

E.g. 1: Event handlers example
------
Suppose we have a textbox , and we want to show an alert message when a key is pressed inside the textbox:

Option A:
---------
function showMessage() {
alert('key has been pressed');
}

$('#abc').mousedown(showMessage);

Option B: (more commonly used)
---------
$('#abc').mousedown(function() {
alert('key has been pressed');
});

Note:
1. in B, the entire code of the function has been passed like a value
2. in B, the function does not have a name
3. We would typically use Option A if code reuse is going to there,
otherwise we would go with option B.
Option B is more commonly seen in jQuery code.

E.g 2: Callback to Ajax request example:
------
Suppose we have a ajax call that returns json data:
$.getJSON('/get_users_list', function(response) {

});


IV) $(array).each  &  'this' keyword
------------------------------------------------------

jQuery provides a way to iterate over an array - using 'each'
When using 'each', 'this' will refer to the indiviual item of the array

E.g. 1:
-------
var arr = ["abc", "pqr", "xyz"];
$(arr).each(function() {
var item = this;
alert(item);
});

E.g. 2:
-------
Suppose a Ajax request to /getMoviesList returns
{"items":[
{"movieID":"65086","title":"The Woman in Black","poster":"\/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"},
{"movieID":"76726","title":"Chronicle","poster":"\/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"}
]}
and we want to iterate over the above result;

Observe that "items" is an array , so essentially we want to iterate over "items" array

$.getJSON('/getMoviesList', function(response) {
var users_array = response.items;
$(users_array).each(function() {
var movie_record = this;
alert(movie_record.movieID);
alert(movie_record.title);
});
});

See http://stackoverflow.com/questions/9450083/using-each-within-getjson for related code


V) $(document).ready event
-------------------------------------
Suppose we want some code to be executed when the page finishes loading,
we could -
1. wrap that code with 'function' keyword & curly {} braces, and
2. specify that code as part of $(document).ready event-handler.

E.g. 1. Suppose we want to show an alert message when page finishes loading
$(document).ready(function() {
alert("page has finished loading");
});

E.g. 2. Suppose we want to attach an event-handler to a button's click event,
we have 2 options -
Option A:
---------
we have to make sure to place the code (that attaches the event-handler to the button) after the button tag itself

<button id="btn1">Button 1</button>
$('#btn1').click(function() {
alert("button 1 has been clicked");
});
Note - the Javascript code that acts on the button, has to appear after the button's html

Option B:
---------
we could place the javascript code within $(document).ready's event-handler;
then, the code will run after the entire page loads, which should mean that the button has been created also
(so that there would be no danger of trying to access the button before it gets created)

$(document).ready(function() {
$('#btn1').click(function() {
alert("button 1 has been clicked");
});
});

IMPORTANT - We can have as many $(document).ready event-handlers we want;
this is probably the main difference between window.onload & $(document).ready event-handlers.



VI) Finding elements within elements
-------------------------------------------------

1. > and space operators in specifying hierarchy

> operator : search only immediate children
E.g
$('#abc > div')  - returns all div elements that are immediate children of #abc

space operator: search children, grand-children, great-grand-children, and so on
E.g.
$('#abc  td') - returns all td elements that can occur anywhere within #abc


2. find() method
Another syntax we can use instead of the space operator above is via find() method
$('#abc td')
$('#abc').find('td')


VII) jQuery chaining
----------------------------
Most function calls do some operation on the selected html-elements, and then return the array of selected html-elements,
so that chaining-of-methods is possible.
E.g.    $('#abc').show().css("border-color","red");
Exceptions - functions like .html() and .text() return strings, so chaining is not possible with these methods


VIII) jQuery and dynamically added elements
-------------------------------------------------------------

This is one of the most common hard-to-find problem when using jQuery.
If we have code to attach event-handlers within $(document).ready event, we have to remember that $(document).ready event
only fires once (and all its event-handlers are executed only once) as soon as the page finishes loading.
After that, if we have javascript code that creates new html elements, then , by default , those new elements will not
get event-handlers specified in $(document).ready event;
In order to solve this problem, jQuery has given the .on() method;
.on() method allows us to specify event-handlers for elements that can be created in the future also

This usually comes into the picture when we are using .html() method to create new elements, or when we want
to attach event-handlers to 3rd part widgets that keep manipulating their html a lot

Documentation - http://api.jquery.com/on/


IX) $.ajax(), $.getJSON(), and 'async' attribute
---------------------------------------------------------------
$.ajax() - method to make Ajax calls
$.getJSON() - shortcut form of $.ajax() wherein we get JSON data as result
async - when using $.ajax(), we can specify   async: false  (default value is true)
- this means that we want the ajax call to Not-be asynchronous, i.e we want a synchronous operation
- this is not that commonly used, but if we have more than 1 ajax call within the same function,
we have to keep this in mind
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.getJSON/


X) General Javascript headaches
---------------------------------------------
1. When page is loading, if there is a javascript error on a particular line of code, subsequent lines of code are
not executed.
2. Cross-domain Ajax requests from the browser are not allowed


XI) Tools to use:
----------------------
1. jsFiddle, jsbin.com
2. Chrome Developer Tools
- Inserting Breakpoints is a mess (this is better in Firefox, but interface for Firebug has changed recently, and is sometimes unreliable)

Thursday, October 3, 2013

Rails - Specifying Order in which .js files (in "assets" folder) should be loaded

http://stackoverflow.com/questions/11285941/rails-specify-load-order-of-javascript-files

E.g. To use g.raphael :

Suppose our raphael files are as follows in the "assets" folder -
/assets/raphael/g.dot-min.js
/assets/raphael/g.pie-min.js
/assets/raphael/g.raphael-min.js
/assets/raphael/raphael.js

When the files are loaded, they are loaded in the above order (i.e. order seems to be based on name of the file)
If we want to make rails load raphael.js & g.raphael-min.js first then we have to specify that in application.js file

In application.js:
specify
//= require raphael/raphael
//= require raphael/g.raphael-min
//= require_tree .

Note that both the raphael entries have to be above require_tree entry (and raphael has to be before g.raphael-min).
(It almost seems like require_tree entry should be the last entry in application.js file - have to verify this)

Tuesday, October 1, 2013

Ruby - blocks, callbacks

BLOCKS:

http://stackoverflow.com/questions/814739/whats-this-block-in-ruby-and-how-does-it-get-passes-in-a-method-here
BLOCKS are a fairly basic part of ruby. They're delimited by either:
 do |arg0,arg1| ... end or
 { |arg0,arg1,arg2| ... }.
They allow you to specify a CALLBACK to pass to a METHOD.
This CALLBACK can be invoked in two ways - either by capturing it by specifying a final ARGUMENT prefixed with &, or by using the yield keyword 
CALLBACKS:

Idiomatic & Non-idiomatic ways of having CALLBACKS in RUBY:
http://stackoverflow.com/questions/1677861/how-to-implement-a-callback-in-ruby
The idiomatic approach would be to pass a BLOCK instead of a REFERENCE to a METHOD. One advantage a BLOCK has over a freestanding METHOD is CONTEXT - a BLOCK is a CLOSURE, so it can refer to variables from the SCOPE in which it was declared. This cuts down on the number of PARAMETERS do_stuff needs to pass to the --CALLBACK.

Monday, September 30, 2013

Recipe for a Rockstar Team

Following blogpost talks about the myth of a rockstar-programmer, and the reality of a rockstar-team.

http://www.hanselman.com/blog/TheMythOfTheRockstarProgrammer.aspx
In fact, it's diversity of thought and experience in a team that makes a Rockstar Team - that's what you really want. Put thoughtful and experience architects with enthusiastic and positive engineers who are learning and you'll get something.  If you insist on calling someone a rockstar, they are likely the team's teacher and mentor.
Jon Galloway says: 
Pairing "step back and think" devs with "crank a lot of pretty good code out" devs is a recipe for a good team.

Sunday, September 8, 2013

50 Useful Plugins for Bootstrap

Cloud & Azure Glossary

Responsive Design - Waste of Time ?

http://simpleprogrammer.com/2013/09/03/responsive-design-waste-time/
...
It seems to me, that if you have to have your site display differently on a mobile device you are better off just forgetting about trying to reuse the HTML markup and CSS, and instead focus on reusing the backend code for both the mobile and desktop versions of your site; that is where you’ll actually get the biggest bang for your buck.
... I’d much rather maintain two front end codebases that are simple than one monstrous complicated front end codebase. 


Sunday, September 1, 2013

Do you fix bugs before writing new code?

           From: "The Joel Test: 12 Steps to Better Code " 
          - http://www.joelonsoftware.com/articles/fog0000000043.html
5. Do you fix bugs before writing new code? 
The very first version of Microsoft Word for Windows was considered a "death march" project. It took forever. It kept slipping. The whole team was working ridiculous hours, the project was delayed again, and again, and again, and the stress was incredible. When the dang thing finally shipped, years late, Microsoft sent the whole team off to Cancun for a vacation, then sat down for some serious soul-searching.
What they realized was that the project managers had been so insistent on keeping to the "schedule" that programmers simply rushed through the coding process, writing extremely bad code, because the bug fixing phase was not a part of the formal schedule. There was no attempt to keep the bug-count down. Quite the opposite. The story goes that one programmer, who had to write the code to calculate the height of a line of text, simply wrote "return 12;" and waited for the bug report to come in about how his function is not always correct. The schedule was merely a checklist of features waiting to be turned into bugs. In the post-mortem, this was referred to as "infinite defects methodology".
To correct the problem, Microsoft universally adopted something called a "zero defects methodology". Many of the programmers in the company giggled, since it sounded like management thought they could reduce the bug count by executive fiat. Actually, "zero defects" meant that at any given time, the highest priority is to eliminate bugs before writing any new code. Here's why.
          ....
That's one reason to fix bugs right away: because it takes less time. There's another reason, which relates to the fact that it's easier to predict how long it will take to write new code than to fix an existing bug.
          ....
What this means is that if you have a schedule with a lot of bugs remaining to be fixed, the schedule is unreliable. But if you've fixed all the known bugs, and all that's left is new code, then your schedule will be stunningly more accurate. 
Another great thing about keeping the bug count at zero is that you can respond much faster to competition. Some programmers think of this as keeping the product ready to ship at all times. Then if your competitor introduces a killer new feature that is stealing your customers, you can implement just that feature and ship on the spot, without having to fix a large number of accumulated bugs. 
 Link to full article: 
          The Joel Test: 12 Steps to Better Code :
          (Please see  #5 -  Do you fix bugs before writing new code?)

Comments in Code

http://ayende.com/blog/163297/the-importance-of-comments
The "why" is usually part of the context, which is what I sometimes need to explain with comments.

Sprite Animation example

Popularity of different frameworks - ASP.Net, ASP.Net MVC, J2EE, Ruby on Rails etc

Friday, August 30, 2013

Effect of Indexes (on a database table's Size)

sp_spaceused
-----------------
sp_spaceused in Sql Server can be used to find a table's size.
Comparing a table's size before & after creating an index can be done using it.

Thursday, August 29, 2013

Google - search by specifying Time

Append the following to the URL -

&tbs=qdr:h   -- past Hour
&tbs=qdr:d   -- past Day
&tbs=qdr:m  -- past Month
&tbs=qdr:y   -- past Year

Sunday, August 25, 2013

Rails - disable sql logging (to not show in "rails server" terminal)

"rails server" log, to become useful, should not have sql lines showing up in between "rendered", "redirected", "Start GET", "Processing by" lines (which are very important at the time of development).

http://stackoverflow.com/questions/7759321/disable-rails-3-1-sql-logging
To turn it off:
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
To turn it back on:
ActiveRecord::Base.logger = old_logger
(We can do the above in "rails console")

Friday, August 23, 2013

tail & grep

1. search for 1 word

http://stackoverflow.com/questions/7161821/how-to-grep-a-continuous-stream
Turn on grep's line buffering mode.
tail -f file | grep --line-buffered   my_pattern

tail -f /home/saiponduru/dev/pyr/pyr-greenzone/log/development.log | grep --line-buffered Rendered

2. search for multiple words

http://www.cyberciti.biz/faq/searching-multiple-words-string-using-grep/
$ grep 'warning\|error\|critical' /var/log/messagesTo just match words, add -w swith:
$ grep -w 'warning\|error\|critical' /var/log/messagesegrep command can skip the above syntax and use the following syntax:
$ egrep -w 'warning|error|critical' /var/log/messages
I recommend that you pass the -i (ignore case) and --color option as follows:
$ egrep -wi --color 'warning|error|critical' /var/log/messages

tail -f /home/saiponduru/dev/pyr/pyr-greenzone/log/development.log | egrep -wi --line-buffered 'rendered|account'
OR
From pyr-greenzone directory -
tail -f ./log/development.log | egrep -wi 'rendered|account'


Thursday, August 22, 2013

Rails - pass additional parameters while using redirect_to

http://stackoverflow.com/questions/5599698/rails-passing-parameters-in-a-redirect-to-is-session-the-only-way
redirect_to(new_user_path(:notice => 'Please register as a new user', :uid => 'ABCD'))
The params you want to pass are arguments to the new_user_path method, not the redirect_tomethod.

Thursday, August 15, 2013

1 PC -> Multiple PCs

New concepts - Mob Programming, No Estimates

Mob Programming:
http://codebetter.com/marcushammarberg/2013/08/06/mob-programming/
http://mobprogramming.org/

No Estimates:
https://twitter.com/search?q=%23noestimates
http://zuill.us/WoodyZuill/category/estimating/

Mob Programming & No Estimates:
http://mobprogramming.org/how-does-the-mob-get-away-with-no-estimates/


TeamViewer for Mob Programming
- can be used for paired programming (i.e. 2 persons).
- in Meeting mode, we can give control to meeting-participants. This works in the free version also, so TeamViewer can be used for 'mob programming'.

Windows Phone App Studio

http://www.kunal-chowdhury.com/2013/08/windows-phone-app-studio.html
http://www.kunal-chowdhury.com/2013/08/how-to-build-rss-feed-reader-using.html
Microsoft has recently launched a tool called “App Studio” which will allow you to build a Windows Phone app without any programming skill. 
....
Windows Phone App Studio lets you easily build apps for immediate publishing, testing and sharing with clients, co-workers, and friends. When you're ready to add advanced programming features or UI changes, the Windows Phone App Studio also generates source code for you to download. 
 

Javascript Design Patterns

(Have to read this)
http://www.codeproject.com/Articles/636699/JavaScript-Design-Patterns

Talks about :

  • Simulated Classes
  • Module Pattern
  • Revealing Module Pattern
  • Lazy functions

Thursday, August 8, 2013

git - see commits in a branch (that are not in another branch .e.g. master)

To see commits that are there in mybranch but not in master:
git  log  master..mybranch  --oneline

To see commits that are there in master, but not in mybranch:
git  log  mybranch..master  --oneline

git - copy a file from another branch

http://stackoverflow.com/questions/2364147/how-to-get-just-one-file-from-another-branch
git checkout master               # first get back to master
git checkout experiment -- app.js # then copy the version of app.js 
                                  # from branch "experiment"
Basically, if we are copying a file, say file1.js from FROM-B branch to TO-B, then:

git  checkout  TO-B
git  checkout  FROM-B  --  file1.js

git - diff files between 2 branches

To diff a single file in 2 branches:
git diff mybranch master -- myfile.cs
To diff all files in 2 branches:
    git diff mybranch master 

Learn HTML using a game

Sunday, August 4, 2013

HTML, CSS related: Show Div on 'hover' with only CSS

I have seen empty <a> followed by div elements sometimes (like below):
<a>Menu Item</a>
<div>
   some stuff
</div>

The reason for the empty <a> elements is probably the below: 
http://stackoverflow.com/questions/5210033/show-div-on-hover-with-only-css
Assuming HTML4, with this markup:
<a>Hover over me!</a>
<div>Stuff shown on hover</div>
You can do something like this:
div {
    display: none;
}

a:hover + div {
    display: block;
}
This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.
HTML5 allows anchor elements to wrap almost anything, so in that case the div element can be made a child of the anchor. Otherwise the principle is the same - use the :hover pseudo-class to change thedisplay property of another element.

jsfiddle example:

Sunday, July 28, 2013

jquery - .prop() vs .attr()

http://api.jquery.com/prop/
http://stackoverflow.com/questions/5874652/prop-vs-attr/5884994#5884994
A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values fromattributes with the same or similar names (value gets its initial value from the "value" attribute; hrefgets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNodeproperty gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.


Ruby - how to access properties using 'string' version of property-names

(2012 question/answer)
http://stackoverflow.com/questions/12136262/ruby-get-set-an-objects-property-using-a-string-symbol
car.color
car.send("color=", value)
(2009 question/answer)
http://stackoverflow.com/questions/903763/how-to-convert-from-a-string-to-object-attribute-name
irb> example_customer.name
#=> "Evagation Governessy"
irb> field = 'name'
#=> "name"
irb> example_customer.instance_variable_get(field)
NameError: `name` is not allowed as an instance variable name
from (irb):8:in `instance_variable_get`
from (irb):8
irb> example_customer.instance_variable_get('@'+field)
#=> nil
irb> example_customer.send(field)
#=> "Evagation Governessy"
irb> example_customer.send(field+'=', "Evagation Governessy Jr.")
#=> "Evagation Governessy Jr."
irb> example_customer.send(field)
#=> "Evagation Governessy Jr."
irb> example_customer.name
#=> "Evagation Governessy Jr."
So you can see how #send(field) accesses the record information, and trying to access the attributes doesn't. Also, we can use #send(field+'=') to change record information. 

Ruby - strings - difference between using single quotes & double quotes


https://rubymonk.com/learning/books/1-ruby-primer/chapters/5-strings/lessons/31-string-basics
A String literal created with single quotes does not support interpolation.
The essential difference between using single or double quotes is that double quotes allow for escape sequences while single quotes do not. What you saw above is one such example. “\n” is interpreted as a new line and appears as a new line when rendered to the user, whereas '\n' displays the actual escape sequence to the user.
Example of interpolation:
a = 1
b = 4
puts "The number #{a} is less than #{b}" 

Thursday, July 25, 2013

Captcha related

Have to read this -
http://15daysofjquery.com/safer-contact-forms-without-captchas

Then this:
http://stackoverflow.com/questions/8472/practical-non-image-based-captcha-approaches

Have to see if we can use Raphael.js to draw captchas (Not sure if we can provide the same kind of functionality as reCaptcha or not i.e. audio etc)

Tuesday, July 23, 2013

Rails - newer property syntax

When using the newer property syntax, there should not be a space between the property-name and colon (:)

i.e.
class: 'icon-picture'     --> correct
class : 'icon-picture'    --> incorrect 

Observe the space before the colon (:) in the incorrect line

Rails - passing html5 'data' attributes to link_to

In the example in the previous post, notice the syntax that is used to specify key & value for data-toggle

2 ways:
(from http://stackoverflow.com/questions/2134702/ruby-1-9-hash-with-a-dash-in-a-key )

(I)"data-toggle" => 'modal'
<%= link_to " Change Image", "#modalDiv1", { class: 'icon-picture', "data-toggle" => 'modal' } %>

i.e.
1. use double quotes (i.e. string instead of symbol)
2. use hash-rocket syntax (=>) instead of colon (:) syntax

It seems we cannot use the new colon syntax with keys that contain a hyphen (-) as in data-toggle

(II)data: { toggle: 'modal' } 
<%= link_to " Change Image", "#modalDiv1", { class: 'icon-picture', data: { toggle:'modal'} }%>

i.e.
1. Specify a 'data' hash for 'data' attributes:

Rails - Bootstrap Modal Dialog (pre-loaded & ajax)

Thursday, July 18, 2013

Rails - class_name

When trying to establish relationship between 2 models, we have to specify :class_name if 'module' is different

/app/models/abc/address.rb
module ABC
class Address < ActiveRecord::Base
belongs_to :user
                attr_accessible :user_id, :address1, :address2, :city, :country, :state, :zip, :is_primary_address
         end
end

/app/models/user.rb
class User < ActiveRecord::Base
       has_many :addresses, :class_name => ABC::Address
       ...
       ...
end

Sublime Text - Color Schemes (with White background)

Eiffel
Mac Classic
Dawn

Followers

Blog Archive