Tuesday, December 24, 2013

Ruby: split vs regex, Benchmark

http://stackoverflow.com/questions/7533479/ruby-string-search-which-is-faster-split-or-regex

require 'benchmark'
Benchmark.bm do |x|
    x.report { 50000.times { a = 'a@b.c'.split('@')[0] } }
    x.report { 50000.times { a = 'a@b.c'[/[^@]+/] } }
end

Sunday, December 22, 2013

Rails: routes

If we want to 'namespace' our routes, but do not want the 'named routes' to have namespace's name in the prefix:


namespace :admin, as: '' do
   get '/post/new' => 'posts#new', as: 'new_admin_post'
end

To learn Orchard CMS

Monday, December 9, 2013

Ruby: each_with_index


X.each_with_index do |item, index|
  puts "current_index: #{index}
end

Monday, December 2, 2013

Rails: Reordering Columns

Sometimes it is necessary to reorder columns so that data is presented, by default, in a more meaningful way e.g. the 'key' columns probably should appear in the beginning, followed by other columns that do not allow a Null value, followed by columns that can take in Null values (basically, are not that important)

http://stackoverflow.com/questions/18899011/rails-4-migration-how-to-reorder-columns

Sunday, December 1, 2013

Rails: scope in models

scope :my_books, lambda {|user_id| {:conditions => ["user_id = ?", user_id] }}

Have to read about scope and conditions - how to specify And , Or ?

Wednesday, November 27, 2013

Google: Small Teams

http://davideckoff.com/2008/09/google-at-10-interview-with-marissa-mayer-small-teams-and-leapfrogging-part-4.html

When I joined Google, there were 9 engineers and we organized in 3 teams of 3. And we knew we were going to add 9 engineers by year end, so there’d be 18 of us. And Larry and Sergey said, “You know what? By year end, we don’t want to have 3 teams of 6, we want to have 6 teams of 3. Let’s keep the core team at the size 3. Because if we have twice as many engineers, we don’t want to be doing all the same things twice as well, we want to be doing twice as many things.”

iDoneThis, Buffer

iDoneThis.com - share & store info about work being done
bufferapp.com - scheduled posts to Social Media websites like Facebook, Twitter

iDoneThis 'dones' from command line - https://github.com/influitive/idonethis

Teams can even integrate with Github so that commits can be added to 'dones'.

Monday, November 25, 2013

Free Online Courses for ASP.Net MVC

To learn MVC, it looks like there are 2 main options for videos -
1. http://www.microsoftvirtualacademy.com/
2. Pluralsight videos - http://www.asp.net/mvc/videos - This has Pluralsight's videos (for MVC4, MVC 3, MVC 2 ).

Saturday, November 23, 2013

Rails on Windows Azure

Suggestions for Meetings

http://www.linkedin.com/today/post/article/20130819190438-36052017-cut-your-meeting-time-by-90

Storing some points from Comments here:

...I can attest to the importance of meeting to delve deep, hear disparate views, observe and be influenced by others - this is a social process. To think you can do that in one meeting only prior to deciding a key strategic direction is dangerous...

Meetings need to be clearly managed, for, where the group is in a complex-decision-cycle. And when it's time to decide, and the rigor and conversation has been there, then decide and move quickly.

I believe the best decisions come from collaboration. My experience has been that only happens when people are encouraged to participate in the process. This takes time.

over the years I’ve learned to appreciate that, sometimes, we need to attend meetings where nothing gets decided. Sometimes meeting just for deciding and committing makes you blind and deaf to what is really going on in your company and this can lead to disaster later on. So make sure you spend at least 10% of your time, doing unproductive meetings, just to make sure you know where you stand in the big picture.

I have great experiences when thinking alone over alternatives does not give full range of options, while having "group thinking" you can come up with some brilliant ideas which one would never think off alone (simply because of limited knowledge and lack of experience). The key thing in such cases is that people have to come prepared with some initial thoughts.

there are three functional purposes for having a business meeting: 
To inform and bring people up to speed 
To seek input from people 
To ask for approval 

 The general relationships meeting is almost the most important of the lot; Repeat after me: relationships lead to results

Bozhidar Ivanov
I believe that if, for example, you would like to enforce teamwork, tolerance towards different opinions, calibration between your teammembers and, last but not least, educate and develop your team, the time spent on meetings is not wasted.
I am far from believing that the time I spent with my team, even on 1 on 1 meetings, should be considered as a "loss"

Liran Tal
there are some introverts amongst us. We really like to listen

Mike Manley
Unfortunately sometimes the only way to get some people to focus on something that requires their contribution is to pin them down to a meeting. Otherwise it sits at the bottom of their list and you spend far too much time chasing.

David Pointon
 there are 4 types of meetings, 1. Decide, 2. Consult/Collaborate, 3. Inform, and 4. Relate

The point is to be clear on the core purpose of each meeting. 

 As an example, It is perfectly OK to have a productive, well structured Consult/ Collaborate meeting if people are aware of when and how their inputs will be converted into Decisions. Indeed, as more staff and stakeholders actively seek engagement, this is a crucial step in moving towards Decisions.

In a Decide-only meetings culture, much of the opportunity to engage would be pushed underground, leaving people unclear about when and how they can get involved.

Robin Merritt
Some meeting concepts I have learned over time that has helped me:Have an agenda but share it before the meeting (seems simple but it doesn't always happen), include others in the meetings, when you can, to "own" a topic, try standing in a meeting - they go by faster!, don't invite the entire team to every meeting but just the ones that can decide and commit, and some meetings are just for morale and relationship building so chose the attendees wisely because not everyone wants to join those meetings at work.

Ingo Susing
sometimes meetings have the (implied) objective of creating social capital and strengthening relationships, arguably a critical ingredient to create an environment of trust which is fundamental to effective teams

Sarah Greene
In the knowledge economy, sharing what you know as a subject matter expert is considered currency, and a form of power. So to some extent this model requires people to cede some of their personal power for the good of the whole.

Ragavan Dhandapany
One more thing which i find useful is to have 'your own agenda' before participating in the meeting. Before you start wondering about 'personal agendas' what I really mean, is to go through some meeting materials before hand and list down those things that you definitely want to express or discuss. Often, people just walk into a meeting room, just because it is in their calendar...

Pat Elliott
there will always be a need to have "Update", "Inform" and "Educate" meetings to ensure progress on initiatives are shared with everyone, to inform employees of major business decisions/actions/strategies and to educate individuals on many topics.

Roy W. Haas, Ph.D.
I was once on a large project that was reorganized because of time and cost over-runs. The new project manager had a status meeting every morning at 8am. If you were there at 8:01, you didn't get any donuts, no matter your management rank. The only things we did were "decide" and "commit" by going around the room. The project got back on track quickly and was a success.


Dmitry Belenko
This only works if you don't ever need to figure out HOW to do something, or WHAT to build, or ask for an expert opinion, or give expert opinion, etc. In other words, this doesn't work for anything creative, because without constant communication with the rest of the team you will simply build something far removed from what people actually want. As much as I dislike "communication overhead", there's a lot of value in it. 

The right way to tackle the communication overhead is how Google tackles it: keep the team sizes small.

Carl Thompson
We have a motto "if you can't handle it in three emails, meet on it".

Ashraf Saeed
“Why do we need to meet to accomplish this?” This question make sense to me

Michael M. Obradovitch II, Esq., REA
Another quick "acid" test of how well your meeting is progressing: Make a mental note of the number of Questions to the number of Answers and Reactions. If there are too many questions: People are generally unprepared for the meeting and you're wasting valuable time - cut meeting short and have people "retool". If there are too many Answers and Reactions: Emotions are taking over better adjourn. If the ratio of Questions to Answers and Reactions is close to 1:1 the group is working through the issues and the agenda -- let it ride.

Barbara Lennartz
Another issue for me is: Come to the meeting prepared. How can things be decided if the person who needs the decision and wants the decision comes with little preparation. That's what often makes the meeting end in discussions and postponing decisions.

Murray Lynn
But I have also seen them get to the point in their meetings where they decide and commit without being able to execute effectively.Part of having everyone on the same page is having everyone know they role and how their role compliments and impacts other roles on the team. 

This does not require a long drawn out discussion. It can be a simple as a football huddle, quick and to the point. This little step before execution can make a world of difference.

John Koudela III
I suggest that the supposed content of the meeting be documented, shared for comments, agenda made, prep sheets sent out with rules of engagement

And then at the meeting have each person acknowledge they are prepared for the meeting. If they haven't or just got to the materials a little before - they can leave. Only those prepared for the meeting should attend. Every meeting should have a facilitator. The meeting should have a time limit. One person should take down key points of the meeting and later distribute them so members of the meeting can add it to their own notes.

Sunday, November 17, 2013

Firebase, Parse

http://www.quora.com/Firebase/How-does-Firebase-differ-from-Parse#
Both Parse and Firebase allow for building server-less apps. 

Firebase is a real-time cloud data service. It is designed for building real-time, collaborative applications. Data in Firebase is standard JSON, and developers can access it using a client library or the REST API. When accessed through a client library, changes to data are synchronized in real-time to clients within milliseconds. Firebase provides a highly flexible expression-based security API that allows fine-grained control over data access by clients. 

Parse is a complete technology stack for building mobile apps. It provides a REST data api, push notifications, a Cloud Code JavaScript runtime environment, and social services. Parse has a variety of SDKs for all major mobile platforms as well as a Javascript SDK. Parse provides an access-control-list based security API, which it augments with its Cloud Code service to control data access by clients.

AngularJS

Wednesday, November 13, 2013

Google Analytics - getting an 'access token' using a 'refresh token'


I was getting a 'invalid_grant' error, when I was trying to get a new access_token using a refresh_token.

In our case the problem was (probably) the following:

There are limits on the number of refresh-tokens that are given by google. 
I think, using our client_id, we had made too many requests for new refresh-tokens. So we probably crossed our limit. 
I reset my client-id, and then tried again, getting a 200 OK response with an access token in the payload.



Monday, November 11, 2013

Rails console - reload!

If in "rails console", and we make changes to a 'model', to see those changes in 'rails console", we have to type the following command in "rails console" :

Rails: ActiveRecord - includes vs joins

Rails: When using 'uniqueness' constraint for validations

http://ruby.11.x6.nabble.com/validates-uniqueness-of-only-if-present-td2704659.html

nil == nil
returns true in Ruby

So, if we are using 'uniqueness' constraint, it is important to remember to also use
:allow_blank => true
if we are expecting 'nil' values for that column

E.g.
validates_uniqueness_of  :c_id, :allow_blank => true

Saturday, November 9, 2013

netmarketshare.com, statcounter.com

(1) http://www.netmarketshare.com/ -   Market Share Statistics for Internet Technologies

We can export the charts into PDF (or other formats)

E.g. http://www.netmarketshare.com/downloads/guest635196661403480000.pdf
Looking at the above chart & table, it seems as if
IE's share has been increasing in the last 1 year, and also Safari's share.
Chrome and Firefox's shares have decreased in the last 1 year.
(But before drawing conclusions, we probably have to look at data from other websites also like the below statcounter.com..)

(2) http://gs.statcounter.com

http://gs.statcounter.com/#os-ww-monthly-201210-201310

Wednesday, November 6, 2013

Monday, November 4, 2013

Rails: To see less log messages


To see less messages in the "rails s" console window:
http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
config.log_level = :warn
or 
config.log_level = :error 

Sunday, November 3, 2013

URL Encoding in Rails

Example use case - This is needed when making REST Api calls from Rails (for e.g. calling Google's Analytics API from a controller action)

http://stackoverflow.com/questions/2353742/url-encode-equivalent-in-ruby-on-rails
ERB::Util.url_encode
http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB/Util.html 

Sunday, October 27, 2013

git: Creating an empty branch

 git checkout --orphan NEWBRANCH

Tuesday, October 22, 2013

git - how to resolve 'merge' related conflicts


1. Current version's changes are shown on top (alongwith HEAD text)
    Version being merged is shown at the bottom.

2. We need to resolve the code conflicts and then do a
    git   add  
    git   commit

Have to look at these links also -
http://githowto.com/resolving_conflicts
http://stackoverflow.com/questions/161813/how-do-i-fix-merge-conflicts-in-git
https://help.github.com/articles/resolving-a-merge-conflict-from-the-command-line
And I look at the file in our text editor, we see that git stuck the current version (HEAD, branch B) and the version being merged (branch A) together so we can resolve the conflict.
rawr
<<<<<<< HEAD
changed in branch B
=======
changed in branch A
>>>>>>> branch-a
Now I'll edit the file to make it look the way I want. This can be anything, I am not limited to using the version from one of the branches. In this case I put in a whole new version of the line that reflects what happened.
rawr
changed in both branches
I'm happy with this version, so we stage it and commit. I don't use the -m flag this time, so git opens our text editor pre-filled with a commit message describing the merge conflict. I go ahead and commit with that message.

Sunday, October 20, 2013

Escaping double quotes within inline javascript

When we need to escape double quotes while specifying javascript for a event handler:

http://stackoverflow.com/questions/1081573/escaping-double-quotes-in-javascript-onclick-event-handler
It needs to be HTML-escaped, not Javascript-escaped. Change \" to ".

Saturday, October 19, 2013

Before Upgrading RAM (Intel Processor)

Only for Intel processors:

1. Find out Processor name- e.g. i3 M370
(Windows 7 - Right click on Computer --> Properties)

2. Find out Memory Specifications for that Processor from ark.intel.com
If you are unable to search properly in ark.intel.com , use google with a search string similar to -
ark.intel.com  i3  M370 

3. Note 2 things:
Max Memory Size - e.g. 8GB 
Memory Type - DDR3-800/1066

Important : For i3 M370, 800/1066 are the RAM speeds.
It is important that only these 2 values are used. 
All RAM chips will have the RAM speed specified on them (i.e. by looking at the RAM chip, we can tell the RAM speed).





Friday, October 18, 2013

jQuery - scroll to element

http://stackoverflow.com/questions/6677035/jquery-scroll-to-element
$('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);

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)

Followers

Blog Archive