Free space from boot

See what all linux images/kernels are present in your system

dpkg -l linux-image-\* | grep ^ii

Now see what all linux kernels you can remove

kernelver=$(uname -r | sed -r 's/-[a-z]+//')
mongoexample$ dpkg -l linux-{image,headers}-"[0-9]*" | awk '/ii/{print $2}' | grep -ve $kernelver

Now remove the linux kernels

sudo apt-get purge linux-image-4.4.0-70-generic

Why do some websites have "www." at the start, but others have "http://"?

Here's the secret: the "www." is a subdomain.  So "www.google.com "is actually a subdomain of, and in theory distinct from, the actual domain "google.com".  However, by convention, and to avoid confusion, the subdomain "www.google.com" is set up to take you to the the same place as the actual domain "google.com".
Incidentally, this is also why there is never a "www" in your email address: i.e. you can have the email "johndoe@example.com" but it's almost never "johndoe@www.example.com" (in reality, a web admin could set up email addresses with a www. subdomain in them if they wanted, but that would be just weird).
To give you to a physical analogy, imagine you've arrived at the office complex of "google.com".  The office complex consists of several departments, each of which occupy their own building, you see the "images" building (whose full address is "images.google.com"), a "maps" building (whose full address is "maps.google.com"), there is also a building called "www" (whose full address is "www.google.com").
You can see that the "www.google.com" building is not much different from the "maps.google.com" or "images.google.com" - it's just another building inside the complex.  However, it is clearly important because it was built front and center of the entire complex, such that when you arrive at "google.com" office complex, unless you had another department in mind, you would enter the "www.google.com" building.
This is good, it avoids confusion, going to http://google.com is functionally the same as going to http://www.google.com.  However, some websites aren't so neatly set up and forget to do this.  For analogy, this is like putting the "www." building somewhere in the office complex, but having the main entrance of the office complex lead to an empty lot.  People who arrive at "example.com" find themselves in the empty lot, and have to remember to go through a side-door that leads to "www.example.com" to get to what they want.
A more common error that you might see is that the web admins forget that the "www." domain is technically distinct from the main domain, and forget to set up login sessions that work across both.  This means if you logged in on "example.com", and then went to "www.example.com", it wouldn't know that you were logged in.  This is like arriving at the office complex and picking up your security badge at the main gate, then going to the "www.example.com" building, and the security guard telling you that your security pass is not valid for the "www" building, and that you need to log in again to get a second security pass.  To fix this, web admins have to specifically instruct the website that "main domain security passes and www subdomain security passes are interchangeable".
Finally, you might often see a "www2" instead of a "www".  This can be done when websites are undergoing maintenance - they'd set up a second building named "www2" and simply redirect visitors to it while renovation work is carried out on the "www" building.  Or alternatively if a website needs to distribute users across multiple servers to handle the load - that would be like setting up multiple identical buildings, and evenly distributing the visitors between them so that no single building gets overcrowded.
Basically, the "www" subdomain, by convention, contains the main website.  By convention it's the same as going to the domain, except for when things aren't set up correctly due to an error or ignorance, and ends up confusing users.
The "http:" part on the other hand is always there, whether it's "http://google.com" or "http://www.google.com".  That part tells your browser what kind of connection to make to the website.  HTTP is in effect the "language" that your browser uses to talk to the server to request the website.  These days, you'll often see "https:" instead of "http:"; HTTPS is the secure version of HTTP.  When your browser accesses an "https:" site, your browser sets up an encrypted connection with the server, therefore preventing anyone monitoring your internet traffic from seeing your data, particularly important if you're making a purchase with a credit card.
There are a lot of these protocols in use over the internet, they're known as the URI Scheme, and you can find a list of the "official" ones here: Uniform Resource Identifier (URI) Schemes.  To give you another example of a URI scheme other than http: or https:, you may also come across ftp:, which is used for file transfer (I pick this as an example because your browser happens to support it, but there are many more protocols that need their own software).  For example ftp://ftp.ucsb.edu/ is a UCSB's publicly accessible FTP portal.  The analogy for this is: if http: is an instruction to enter the visitor's entrance of the building (and https: is like an extra-safe way, where you enter the visitor's entrance via an unmarked black car and with a private security detail scanning your surroundings to make sure you weren't followed), then ftp: is like an instruction to drive a truck over to the loading bay of the building to load or unload goods.
Bonus material:
Let's talk about ports.  This is often hidden from users by the web browser, but in reality, a building can have many different entrances, and each entrance has a number (but not all entrances are open, and not all entrances have something behind them ready to receive visitors).  Entrance 80 (i.e. port 80) is the default entrance for web pages.  When you tell your browser you want an http connection, the browser will by default attempt to connect to port 80 unless you tell it to otherwise.  Conversely, https is port 443, and ftp is port 21.
You can specify a custom port number by doing this: "http://www.google.com:80" (though in the case of Google, they've got it set up to redirect you over to the https version of the site).
Want to confuse the server?  Tell your browser to go to an incorrect port, for example "http://www.google.com:443"  Here, 443 is the port for encrypted https connections, but you're telling your browser to use plain old http: you are attempting to make an unencrypted http connection to a port that is waiting for an encrypted connection.  You'll usually get a "connection reset" message, which means the server decided that your browser is not talking in a language that it can (or is willing to) understand, and has closed the connection with you.  This is like you arriving at the English-speaking entrance of the building and yelling Spanish at them until they close the door on you.  Note that going to "https://www.google.com:443" works, because you're telling your browser to make an encrypted https connection to the 443 port, which is what is expected.
There are many reasons a different and non-standard port might be used.  Often, a security measure is to use non-standard ports.  For example, port 22 is used for the ssh protocol, which is used to remotely administrate servers.  This is like the private employee entrance that has a keypad on the door.  However, there are certain criminals who go looking for these doors and try to guess the password, hoping to gain unauthorized access to the building (perhaps to steal information).  This is like going up to door 22 and trying different passwords on the keypad until the right one is found.  Various countermeasures are available, such as having the keypad lock people out on multiple failed attempts, or switching to a key-card entry (the employee must present a key-card rather than enter password).  Such countermeasures are essential for security, but don't solve the problem of criminals rattling the handles every few seconds.  To help with that, one possibility is simply moving the employee entrance to a different door (a different port).  This way door 22 doesn't even have a handle to try - as long as the crims don't know where the employee entrance was moved to, they would simply encounter a bricked-over entryway where door 22 used to be.
So to conclude, if your address bar says something like "https://www.quora.com", it's doing this:
- Address: "quora.com" domain (which, by the way, lives in the ".com "top-level domain)
- Department: "www"
- Language to speak: HTTPS
- Door: 443 (the default door to go to for HTTPS speakers)
The things your computer does to get you a webpage is fascinating and complex: we haven't even talked about IP addresses and DNS, or exactly how your computer knows how to reach a website; or HTTP methods, or HTTP status codes yet.

Answered by - Yuan Gao on Quora.

HTTP Status Code for newbies

If you are having hard time understanding or remembering HTTP codes then this article is for you.

credit - monkeyuser.com

301 Moved Permanently

The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.
The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

305 Use Proxy

The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.

307 Temporary Redirect

The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

404 Not Found

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

408 Request Timeout

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

413 Request Entity Too Large

The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.
If the condition is temporary, the server SHOULD include a Retry- After header field to indicate that it is temporary and after what time the client MAY try again.

417 Expectation Failed

The expectation given in an Expect request-header field (see section 14.20) could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server.

500 Internal Server Error

The server encountered an unexpected condition which prevented it from fulfilling the request.

How to shorten the bash shell prompt

So sometimes it happens that you are working on command terminal and you navigate inside a directory then again in inner directory and so on until half of the screen width is filled with prompt string. Example below....

rana@Brahma: dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8 $ ls 

Now I want to display just the last directory in terminal prompt string so that I am left with enough width space to execute length commands.

For this We need to change the prompt string from .bashrc file. Below are the steps -

1. Go to your home directory.
2. Open .bashrc file.
3. Search for string 'PS1'. To search quick open the file in vi and type /PS1 and hit enter.
4. now you will find below code. (or similar to it) [ I am working on Ubuntu 16.04]
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
5. Replace the 'w' (highlighted in blue color) with capital W. So your new code will be.
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]: \[\033[01;34m\]\W\[\033[00m\]\$ '
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
6. Restart the terminal and navigate inside any directory. You will see just the last directory in teminal prompt.
rana@Brahma: dir8$

Happy Learning.


How to hide pages on google sites

Sometimes you might required to hide some pages from public views in Google sites. Or you may want to delete the page but then you might use same page again so you decided to save the page as draft temporarily.

Here is the step by step process to do so.

- Login to your account. Open the google site.
- Open any page. Click on the settings button on top right corner.

- Look for sharing and permission menu item. Click on it.

- on next page, click on 'Turn page level permission on'.

- Now select any page you want to hide or save as draft.
- Change the permission settings to desired value.

How to use custom UserModel in django

In previous article we learned how to use django authentication in your application. But sometimes it may happen that default user model of django does not fit your requirement. You may want to add more fields to it. Now there are multiple ways to do it.

1. Use proxy model. No new model is created.
2. Use one-to-one relationship and create another model.
3. Create your own user model and use default authentication system.
4. Create your own user model and create your own authentication system.

Previous article - http://www.newbie42.com/2016/09/implementing-authentication-in-django.html

We will be learning 3rd method here.

Note : This needs to be done before performing any migration.

- First create the custom user model and custom user manager.

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone
from django.db.models import Max

class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self,login, parent_type, last_name, first_name, password):
return create_superuser(self,login, parent_type, last_name, first_name, password)

def create_superuser(self,login, parent_type, last_name, first_name, password):
maxx = self.model.objects.all().aggregate(Max('sys_id'))
if maxx["sys_id__max"] is None:
maxx["sys_id__max"] = 0
user = self.model(
                 sys_id = maxx["sys_id__max"] + 1,
                 login = login,
                 parent_type = parent_type,
                 last_name = last_name,
                 first_name = first_name,
                 display_name = last_name + " " + first_name,
                 created_when = timezone.now()
# no difference here...actually can set is_admin = True or something like that.
return user

class UserModel(AbstractBaseUser):
# custom user class

sys_id = models.BigIntegerField(primary_key=True, blank=True)
last_name = models.CharField(null=False, blank=False, max_length=40)
first_name = models.CharField(max_length=40, null=False, blank=False)
display_name = models.CharField(max_length=80, unique=True, null=False, blank=True)
login = models.CharField(max_length=40, unique=True, null=False, blank=False)
authentication_method = models.CharField(max_length=80, null=True, blank=True)
access_valid_start = models.DateTimeField(null=True, blank=True)
access_valid_end = models.DateTimeField(null=True, blank=True)
notes = models.CharField(max_length=2048, null=True, blank=True)
is_active = models.BooleanField(default=True)

objects = MyUserManager()

# REQUIRED_FIELDS must contain all required fields on your User model, 
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = [ 'last_name', 'first_name']

class Meta:
app_label = "appname"
db_table = "Users"

def __str__(self):
return self.display_name

def get_full_name(self):
return self.display_name

def get_short_name(self):
return self.last_name

- Now in your settings.py file add this line. It will tell your application that you have to use your custom model for authentication instead of default one.

AUTH_USER_MODEL = 'accounts.UserModel'

- Write your login/logout functions just like in previous article.

Implementing authentication in Django

Django - 1.9
Python - 3.4

To implement the authentication in django follow these steps.

- First complete the initial migration so that initial tables are created in DB.
- Create superuser.
- Login to admin module using the credentials created in step above.
- Create another user which might be admin 'staff' member or not.
- Edit your url.conf file and add the urls corresponding to login and logout.
 [replace appname with your app's name in code below]

    url(r'^$', views.index, name='index'),
    url(r'^login/$', views.appname_login, name='appname_login'),
    url(r'^logout/$', views.appname_logout, name='appname_logout'), 

- Create login, logout and index functions in your view.py file

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse

def index(request):
    context = {}
    context["user"] = request.user
    return render(request, "appname/index.html", context)

def tenant_login(request):
    context = {}
    if request.method == "GET":
        if "next" not in request.GET:
            context["next"] = "/appname/"
            context["next"] = request.GET["next"]
        return render(request, "appname/login.html", context)
        username = request.POST["username"]
        password = request.POST["password"]
        next_url = request.POST["next"]
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect(next_url, args=(),kwargs={})
                context["message"] = "User is not active"
            context["message"] = "Invalid username or password"
        return render(request, "appname/login.html", context)

def tenant_logout(request):
    url = reverse("appname:appname_login")
    return redirect(url, args=(),kwargs={})

- Create login.html file in template directory.

   <form method="post" action="{% url "appname:appname_login" %}">
        {% csrf_token %}
<input type="text" name="next" hidden="" value="{{next}}">         
        <input type="text" name="username"> 
        <input type="password" name="password">
<input type="submit" name="submit" value="Log In">

- Inside your index.html file

   {% if user.is_authenticated  %}
    <a href="{% url "tenant:tenant_logout" %}">Logout</a>

    {% endif %}

- Run the python server. Goto localhost:8000/appname/.
- In view file you can see that 'index' method uses login_required decorator, if you are not logged in than you will be redirected to login page.
- When you are redirected to login page from any xyz page then a url parameter is added to url which tells where to redirect on successful login. Observe the url in address bar when you are redirected to login page.
- Enter the username and password of the user created in a step above. Log in.
- You will redirected to index page. If user is authenticated (if user is not AnonymousUser) then user's first name and logout link is displayed otherwise not.
- Clicking logout will logout you from the application and try to redirect to index page. but since index page requires login you will be redirected to login page.
- You can print user's full name in index template because you have full access to user object. Use {{user.get_full_name}} or {{user.first_name}} in template.

Let me know if you face any issues in this.