Four Python builtin functions we should know

For debugging we use those functions a lot.

The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

>>> type(1)           
<type 'int'>
>>> li = []
>>> type(li)          
<type 'list'>
>>> import fibo
>>> type(fibo)  
<type 'module'>
>>> import types     
>>> type(fibo) == types.ModuleType

You can use the built-in dir function to list the identifiers that a module defines. The identifiers are the functions, classes and variables defined in that module.

When you supply a module name to the dir() function, it returns the list of the names defined in that module. When no argument is applied to it, it returns the list of names defined in the current module.

>>> li = []
>>> dir(li)           
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)            
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper)   
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']


Help function, name it self defines the usage of this function. This function returns the help related to python module, object  or method if it is called with respective argument but without any argument it will return the help related to currently running programming module.

>>> help(str)

Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  Method resolution order:
 |      str
 |      basestring
 |      object

__doc__ :

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object’s docstring is defined by including a string constant as the first statement in the object’s definition.

>>> int
<type 'int'>
>>> print int.__doc__
int(x=0) -> int or long
int(x, base=10) -> int or long

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.

If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base.  The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
>>> list
<type 'list'>
>>> print list.__doc__
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
>>> dict
<type 'dict'>
>>> print dict.__doc__
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)

SFTP Command to Transfer Files on Remote Servers

SSH File Transfer Protocol, a network protocol used for secure file transfer over secure shell.

SFTP (Secure File Transfer Protocol) runs over SSH protocol on standard port 22 by default to establish a secure connection. SFTP has been integrated into many GUI tools (FileZilla, WinSCP, FireFTP etc.).

Below are the most used commands for SFTP:

1. Connect to SFTP

To connect with SFTP we can use below commands.

[root@salayhin ~]# sftp salayhin@

Connecting to
tecmint@'s password:

If we are using AWS we can add the pem file location with this command.

[root@salayhin ~]# sftp -i PemFile.pem salayhin@

Continue reading SFTP Command to Transfer Files on Remote Servers

Python locale error: unsupported locale setting

Sometimes we are getting local error and cannot install packages via pip.

I found a solution to get rid of it.

Run this command from your command line interface.

$ export LC_ALL=C

Output from locale is:

$ locale

Get the date n days ago and n days after in Python

Few day’s ago I found a helpful method to get n day’s ago date and n days after date from current date. Following functions are written based on Python 3.

Date n day’s ago:

from datetime import datetime, timedelta

def get_n_days_before_date(date_format=&quot;%d %B %Y&quot;, days_before=120):

    date_n_days_ago = - timedelta(days=days_before)
    return date_n_days_ago.strftime(date_format)

Date n day’s after:

from datetime import datetime, timedelta

def get_n_days_after_date(date_format=&quot;%d %B %Y&quot;, add_days=120):

    date_n_days_after = + timedelta(days=add_days)
    return date_n_days_after.strftime(date_format)

Error installing rmagick on Ubuntu

While running bundle install I am getting this error:

$ gem install rmagick Building native extensions. This could take a while...

ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. Can't install RMagick 2.13.2. Can't find Magick-config

I have solve this problem by installing rmagick and libmagick++-dev package

Install imagemagick:

sudo apt-get install imagemagick

Install rmagick:

$ sudo apt-get install libmagick++-dev

Create custom error pages dynamically in ruby on rails 4

The default status code templates are served by a Rack exception application. You can override this to be any Rack compatible app. To override this you need to add following line in your application.rb file.

# config/application.rb
config.exceptions_app = self.routes

Now we need to create ErrorsController:

class ErrorsController &amp;lt; ApplicationController
  def show
    @exception = env['action_dispatch.exception']
    render action: request.path[1..-1]

  def write_to_log_file
    if @exception.present?
      logger.error(&amp;quot;Error occured: #{@exception.message}, Status: #{status_code}\n Time: #{}&amp;quot;)


  def status_code
    params[:code] || 500

In show method we have added a function to write the exception to log file.

Now create templates for each status code in errors directory. I have created three template for 404.html.erb, 422.html.erb and 500.html.erb

# app/views/errors/404.html.haml
%h1 404 - Not Found

Now create route for this errors:

# config/routes.rb
 %w( 404 422 500 ).each do |code|
    get code, :to =&amp;gt; 'errors#show', :code =&amp;gt; code

And that’s it for dynamic error page.

Happy coding 🙂

Create RSS from your ruby on rails application

For one my recent project need RSS feed. So I have created myself.

This will show you how to create a RSS feed that the Feed Validator considers valid.

First create a FeedsController to host the RSS feed.

class FeedsController < ApplicationController

  layout false

  def rss
    @posts = Post.published_posts.limit(50)


Then create a view in views/feeds/rss.rss.builder for RSS.

xml.rss :version => '2.0', 'xmlns:atom' => '' do do
    xml.title 'Feed title'
    xml.description 'Feed description' root_url
    xml.language 'en'
    xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => posts_url

    for post in @posts
      xml.item do
        xml.title post.title
        xml.pubDate(post.created_at.rfc2822) post_url(post)
        xml.guid post_url(post)
        xml.image_url post.image_url



Create a route to the feed in config/routes.rb:

get 'feed.rss', to: 'feeds#rss', :format => 'rss'

You can get browsers to auto-detect your Rails blog rss feed with a single line of Ruby on Rails code:

<%= auto_discovery_link_tag(:rss, "") %>

That’s it.

Happy Coding 🙂