PyCon India 2019

Yaaaaa!!!! it was my first PyCon India. One day I was chatting to Sayan and suddenly he told me that start saving some money from now and attend the pycon India this year. I had never been any kind of conference ever before so I was bit hesitated about this conference but Sayan and other folks from dgplug guided me a lot. I started my journey with my dad from Kolkata on 10th October and reached Chennai on 11th.

Day 0

On 12th October I left for the conference. When I reached the conference I saw sourabh, Pravar and Rayan there and talked with them. After that I got my attendee card then went for the breakfast and while eating I met some people and talked with them like Vijay, Noah later I proceeded to the conference. After that I attended the Jake VanderPlas’s keynote. After that I was going to various sponsors booth to collect the goodies :p. After that I went for Pradyun’s talk Python Packaging – where we are and where we’re headed. He described how packaging works with pip and how they are planning to move ahead.
I met many of the faces whom I used to know on IRC/Twitter only. Later me and Sayan explored the Poster Session. It was really exciting and my first day of the conference was over. After the conference me and some other folks went for visiting the Palavakkam Beach and spent some good time there.

goodies & swags 😉

Day 1

On 13th it started with keynote by Ines Montani. After that there was annual DGPLUG staircase meeting. Sayan conducted the meeting and we all introduced our self to each other and discussed about what went wrong to this year’s summer training. We also discussed about the tasks given by Sayan this year. After finishing the lunch we also solved some word puzzles and coding questions to get the t-shirts and swags. The conference ended with David Beazley keynote and he live coded a stack machine, wrote an interpreter for Web Assembly game that was initially written for Rust in Python and in the end added PyGame to make it into an actual game. I was amazed after seeing it. The keynote ended with standing ovation from all the people in the hall. After the conference we went for DGPLUG dinner and spent some good time with other folks and had our dinner there.

DGPLUG group

Day 2

On 14th(my birthday :p) morning I left for IIT Madras Research Park and in the morning there was my workshop on docker. After finishing the workshop I joined devsprint. There was lots of mentors conducting the devsprint and from that I choosed to join the Python Packaging Sprint which was conducted by Pradyun. It was my first devsprint and I didn’t even know anything about it but Pradyun helped me a lot understand the issue and what should be my approach to solve that. after the devsprint we went for dinner again. On that day most of my friends were returning so it was time to say goodbye to them 🙂

day 3

On 15th again there was devsprint happening there and I was solving an issue in pip and Pradyun was helping me regarding that issue. Besides devsprint me and Sourabh was discussing about some security stuff. After the devsprint I talked with other people.

After the devsprint

Summary

Pycon India has gave me the opportunity to communicate and meet people from all across the world as well as different background. I got to know about lots of new technologies and other technical stuff. I made lots of new friends there and I returned home with some great memories with me 🙂 . If I go next year then I would like to be a volunteer there.

Advertisement

Learned to Build a simple pascal interpreter using python

Photo by Max Duzij on Unsplash

Recently I was going through the series of ‘Let’s Build A Simple Interpreter‘ by Ruslan Spivak which was given by Sayan as an assignment of summer training. Here you can see the whole series codes. I have gone through all the parts and added what I have learned in the README.md file.

In this series the main focus was to build an simple pascal interpreter by python which can execute simple pascal codes like mathematical operations and procedure calling. This series introduced me lots of thing like scanner, token, parser, interpreter and grammar, etc. At first I was thinking that I will not be able to complete the series properly as I didn’t know anything about interpreter and compiler but as move forward in this series things get cleared because everything was elaborated properly. Whenever I stuck at any point I search it in the internet and try to find the proper solution. For me in this series the most interesting part was the grammar of any programming language and how they help.

In this series I also learned how to write better commits so people can understand my code and also learned how to reset my commit to previous commit when I commit wrong things or made any bad commit message. Here you can see my commits.

Thank you 🙂

Fun with python requests module

I was reading this part of the pym book and thought that I should change this code a little bit so that it can do some better thing like instead of storing the content in a text file it stores it in a HTML file and it also checks if there is any same named file exists in the directory or not. Here is the code –

import os.path
import requests

def download(url):
    """
    Download the given url and saves it to the current directory
    :arg url: URL of the file to be downloaded.
    """
    req = requests.get(url)
    if req.status_code == 404:
        print('No such file found at %s' % url)
        return
    fileName = url.split('/')[-1].split('.')[0] + '.html'
    print(fileName)
    if os.path.isfile(fileName):
        print('Same file name already exist')
    else:
        with open(fileName, 'wb') as fobj:
            fobj.write(req.content)
        print('Download over')

if __name__ == "__main__":
    url = input("Enter a URL: ")
    download(url)

Above we are getting the content of the content of the url by requests.get(url) method. Then checking if that url is valid or not. If valid then parsing the url by split() method like first we are splitting it by “/” and taking the last value of the list and then splitting it again with “.” and taking the first value of the list. Then checking if there is no same name file exist and if there is no same name file then we are creating a file then writing the content in the file.
Thank you 🙂

Study, day 3

I have started learning python 3 from pym book by Kushal.

Read about following topics and solved problems.

  • Strings
    • Strip the string.Finding text.palindrome checking.Number of words.
  • Function
    • Defining function.Local and Global variable.keyword and keyword only arguments.Docstring.
  • File Handling.
    • Opening and closing a file.Reading data inside a file.Copying data from one file to another.Counting spaces, tabs and new lines in a file.
  • Exceptions
    • Various type of errors.
    • Handling exceptions.
    • Using finally keyword for cleaning.

Learning python3

Photo by Hitesh Choudhary on Unsplash

I started learning python back in 2017 and since then I am still learning it and using it and almost everyday I write some python code. Python is an interpreter based language, you can write the code directly in the interpreter or in a separate file(extension is .py) and run it.

Using the interpreter

Fire up your terminal and type python3. And you will see something like this below code snippet.

$ python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Now we are going to print “Hello World!” using the interpreter.

>>> print("Hello World!")
Hello World!

Using a source file

Create a file called helloWorld.py and enter the following text:

print("Hello World!")

We can run this file by python3 command.

$ python3 helloWorld.py 
Hello World!

Whitespaces and indentation

Language like c/c++ use pair of curly brackets to divide different identifiers. In the python it uses indentation for that. The whitespaces at the beginning of the line is known as indentation. If you give wrong whitespaces then it will give you errors. Python use 4 whitespaces for a single indentation. Below there is an example.

>>> a = "Aniruddha"
>>>  b = "Basak"
  File "<stdin>", line 1
    b = "Basak"
    ^
IndentationError: unexpected indent

Comments

Comment is a line in python that will start with # and the interpreter of python will just ignores the lines. You can write anything here to describe your code.

>>> # This is a comment
>>> # The next line will multiply two numbers
>>> a = 12 * 34
>>> print(a) # Printing the value of a

If your description is long then it is recommended that you use multiline comments. There is two options for that.

# This is option 1
# Multiline comment
"""
This is option 2
Multiline comment
"""

Modules

The reason why python is loved by so many people is it gives so many modules to work on almost everything you can imagine. Basically modules are python files that contains different functions classes and variable that you can reuse.

>>> import os
>>> print(os.name)
posix

Keywords and Identifiers

Below the following identifiers are main keywords of python. They must exactly types as it is.

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise

Variables and Datatypes

In python we don’t specify the type of the variable while declaring it.If we declare a = 1 then a will become an integer type and if we define b = "Hii" then b will become an string type variable.

>>> a = "Hi "
>>> b = "how you doing?"
>>> a + b
'Hi how you doing?'

Taking input from keyboard

We can take input from users while executing the program. We can use the input() function given by python for this. Let’s see an example of taking input from user.

number = int(input("Enter number: "))
print(number)

Here is the result –

$ python3 input.py 
Enter number: 25
25

Operators and Expressions

Python language supports the following types of operators.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Arithmetic operator:

It is used to perform common mathematical operations.

>>> a = 2
>>> b = 4
>>> a + b
6
>>> a - b
-2
>>> a * b
8
>>> a / b
0.5
>>> a % b
2
>>> a ** b
16
>>> a // b
0

Comparison operator:

It is used for comparing two values and returns either True or False.

>>> a = 2
>>> b = 4
>>> a == b
False
>>> a != b
True
>>> a > b
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True

Assignment operator:

This operator is used to assign values to some variable.

>>> x = 5
>>> x += 5
>>> x -= 5
>>> x *= 5
>>> x /= 5

Logical operators:

Logical operators are the and, or, not operators.

>>> x = True
>>> y = False
>>> print('x and y is ', x and y)
x and y is  False
>>> print('x or y is', x or y)
x or y is True
>>> print('not x is', not x)
not x is False

Bitwise operators:

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60 and b = 13. Now in binary format they will be as follows –

>>> a = 60
>>> b = 30
>>> a & b
28
>>> a | b
62
>>> a ^ b
34
>>> ~a
-61
>>> a >> 2
15
>>> a << 2
240

Membership Operators:

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below −

a = 'Hello World'
print('H' in a)

Identity Operator:

Identity operators compare the memory locations of two objects. There are two Identity operators explained below −

>>> a = 5
>>> b = 5
>>> c = 10
>>> print(a is not b)
False
>>> print(a is b)
True
>>> print(a is c)
False

Customize your vim like any other IDE

So, almost 2 years ago I heard about C programming language from my close friend and I thought I should give it a try and I asked “how can I start with it?” and he gave me some notes and said just install turboC++ and start writing code. So, I installed it and started with C language and eventually I got demotivated and quit programming after some time. Actually it was not fun and engaging with that environment. After one year in my college their was a seminar of network security and the guest speaker said that everyone should try python once and it is really amazing language. And I went home and searched for the python in the YouTube and found lots of tutorial on it and picked up one and that tutorial is using VSCode after that I loved that text editor and still I use it in my daily work.

In my recent days I got to know about a new text editor called vim and I recently installed and start using it. The most funny thing is when I first open a file with it I was not able to exit from it :p. Now I use it in most of the time while writing code. When you will first install it then it will look something below like this

The vim allow us to customize it however we want and we customize it by writing some code in the ~/.vimrc and if the file is not there you can add it by doing touch ~/.vimrc command. Now add below line to your file first.

syntax enable

set shell=/bin/bash

set tabstop=4
set shiftwidth=4
set expandtab
set number
set autoindent
set ruler
set showcmd
set hlsearch
set wrap
set linebreak
set noswapfile
set incsearch
set nohlsearch
set ignorecase
set smartcase
set showmatch
set showmode
set cursorline
set title
set clipboard=unnamedplus
set encoding=UTF-8

set nocompatible

set background=dark
set termguicolors

Now we will add some plugins in this file and then we are going to install it.There are couple of ways to install plugins and the way i like is by Vundle And the section below shows how to add plugins .

set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

Plugin 'VundleVim/Vundle.vim'
Plugin 'scrooloose/nerdTree' "Documents tree
Plugin 'davidhalter/jedi-vim' "python autocompletion
Plugin 'scrooloose/syntastic' "code syntaxis
Plugin 'Raimondi/delimitMate' "automatic closing of quotes, parenthesis...
Plugin 'yggdroot/indentline' "Show indent lines (useful for loops)
Plugin 'vim-airline/vim-airline'
Plugin 'vim-airline/vim-airline-themes'
Plugin 'ervandew/supertab' "<Tab> for code completion
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'ntpeters/vim-better-whitespace'
Plugin 'sjl/badwolf'
Plugin 'python/black'
Plugin 'andviro/flake8-vim'
Plugin 'fatih/vim-go'
Plugin 'tpope/vim-commentary'
Plugin 'airblade/vim-gitgutter'
Plugin 'jreybert/vimagit'
Plugin 'ryanoasis/vim-devicons'

call vundle#end()

autocmd BufWritePre *.py execute ':Black'
let g:black_linelength = 79

let g:PyFlakeOnWrite = 1
let g:PyFlakeCheckers = 'pep8,mccabe,frosted'
let g:PyFlakeDefaultComplexity=10
let g:PyFlakeDisabledMessages = 'E1101,C0111,E1136,W0703,C0103,C0330,W504'
let g:PyFlakeAggressive = 0
let g:PyFlakeCWindow = 6
let g:PyFlakeSigns = 1
let g:PyFlakeSignStart = 1
let g:PyFlakeForcePyVersion = 3

filetype plugin indent on

colorscheme badwolf


" Go syntax highlighting
let g:go_highlight_fields = 1
let g:go_highlight_functions = 1
let g:go_highlight_function_calls = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_operators = 1

" Go preview disable
set completeopt-=preview

" Auto formatting and importing
let g:go_fmt_autosave = 1
let g:go_fmt_command = "goimports"

" Status line types/signatures
let g:go_auto_type_info = 1

" Run :GoBuild or :GoTestCompile based on the go file
function! s:build_go_files()
  let l:file = expand('%')
  if l:file =~# '^\f\+_test\.go$'
    call go#test#Test(0, 1)
  elseif l:file =~# '^\f\+\.go$'
    call go#cmd#Build(0)
  endif
endfunction

" Map keys for most used commands.
" Ex: `\b` for building, `\r` for running and `\b` for running test.
autocmd FileType go nmap <leader>b :<C-u>call <SID>build_go_files()<CR>
autocmd FileType go nmap <leader>r  <Plug>(go-run)
autocmd FileType go nmap <leader>t  <Plug>(go-test)

au filetype go inoremap <buffer> . .<C-x><C-o>

" NERDTree setup
map <C-z> :NERDTreeToggle<CR> “ Toggle side window with `CTRL+z`.
let g:NERDTreeDirArrowExpandable = '▸'
let g:NERDTreeDirArrowCollapsible = '▾'
let NERDTreeShowHidden=1 " Show hidden files

" Vim airline
let g:airline_powerline_fonts=1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#left_sep = ' '
let g:airline#extensions#tabline#left_alt_sep = '|'
let g:airline#extensions#tabline#formatter = 'default'

" Git Gutter
" Use fontawesome icons as signs
let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '>'
let g:gitgutter_sign_removed = '-'
let g:gitgutter_sign_removed_first_line = '^'
let g:gitgutter_sign_modified_removed = '<'

let g:gitgutter_override_sign_column_highlight = 1
highlight SignColumn guibg=bg
highlight SignColumn ctermbg=bg

set updatetime=250

nmap <Leader>gn <Plug>GitGutterNextHunk  " git next
nmap <Leader>gp <Plug>GitGutterPrevHunk  " git previous
nmap <Leader>ga <Plug>GitGutterStageHunk  " git add (chunk)
nmap <Leader>gu <Plug>GitGutterUndoHunk   " git undo (chunk)

" Open vimagit pane
nnoremap <leader>gs :Magit<CR>       " git status

" Move between buffers
map gn :bn<cr>
map gp :bp<cr>
map gd :bd<cr>

" Move line up and down
nnoremap K :m .-2<CR>==
nnoremap J :m .+1<CR>==
vnoremap K :m '<-2<CR>gv=gv
vnoremap J :m '>+1<CR>gv=gv

" Set Ctrl+h for highlight search
nnoremap <c-h> :set hlsearch!<cr>

" Disable K for documentation of go and py
let g:go_doc_keywordprg_enabled = 0
let g:jedi#documentation_command = 0

That’s how we add Plugins to the vim by writing Plugin and after that what plugin we want to install. Now to install plugins first type Esc then : and after that type PluginInstall then press enter and all the plugins will install one by one.

Now vim is looks something like blow image.

Thank you 🙂

DGPLUG, more than a summer training

So, DGPLUG(Durgapur Linux Users Group) is a group where they provide free training to people who wanted to start contributing to FOSS. It is not only a group of Durgapur but it is a now international group. In this blog I am not going to tell you about how and what they teach in their summer training because I haven’t take their summer training yet this yearn I am going to take that but I am going to tell you something more than that like how a community helps to push you to the next level. Their motto is “শেখ এবং শেখাও” it’s a Bengali word meaning is “Learn and teach”.

So, on a regular Sunday I was checking Quora answers and suddenly one of Sayan’s answer written that he had started his journey of open source from DGPLUG and I pinged him on messenger that what is this DGPLUG. He said it is a Linux users group of Durgapur and they provide a summer training every year and you can join it on #dgplug on freenode. On the next day I joined the group and there was going some upstream project discussion and I was quite hesitated to say something and I privately messaged Kushal Das who is the founder of this group. I gave my introduction like who I am and which project I am contributing. He welcomed me and said you should tell this in the group so that everyone can know you. Then I started conversation with a “Hi” and gave my introduction and suddenly some folks welcomed me in this group and I was amazed that how this DGPLUG community is so good and welcoming to a new person and after that I never hesitated to ask any question in this group.

But it is not enough there is a lot more than that, after couple of weeks I made some good friends over there like Kushal, Nabarun, Sourabh and one who regularly comment on my blogs Jason. After that when I stuck any problem I ask their and I know their is somebody at least who is going to help to solve that problem. And now the most important thing what I have learnt from this group is “How to build better network”, “Not to private messaged anyone”, “Read everyday to increase your knowledge”, “Write what you have learnt”.

Thank you 🙂

It is not ok to quit

So, If you face any problem in your day to day life you always have two option either you can quit or you can stick to that problem untill and unless you solve it. Today I am going to tell you about one thing from that I have learned something. So, I am always eager to learn new technologis and I was planning to start learning Ansible from past couple of days.

Let me give you a overviw aout Ansible. It is a IT automation tool to manage our systems and it uses a very simple language called YAML. In this blog I am not going to tell you about Ansible briefly if you want to learn it here is the right place for you.

So, as like all of us when you start learning something you face lots of problem even in the very basic thing. After I started learning Ansible from their official docs I added some IP in the /etc/ansible/hosts file but when I am executing this command ansible all -m ping it is giving me some weired errors that I was not able to figure out what it is and after that I searched a lot in the internet and found the exact solution. After that I again stuck somewhere and this time I was not able to find the relevent solution in the internet and decided to ask in the DGPLUG(it is Linux Users Group og Durgapur where we all hang around and share our knowledge) and a member named Nabarun Pal helped me. We discussed about the error for over 1 hour and after all of that I understand the concept and successfully implemented it. And after overcomming all kind of errors I today I have succesfully wrote my first ansible playbook. Here below the code.

---
- hosts: webservers
  gather_facts: yes
  become_user: root
  tasks:
  - name: Install tree
    apt: pkg=tree state=present
    notify:
    - restart tree
  handlers:
    - name: restart tree
      service: name=tree state=restarted

- hosts: dbservers
  become_user: root
  tasks:
  - name: Install mysql
    apt: pkg=mysql-server state=present

Above the code does very simple thing that it install tree package in my webserver host and install mysql in my dbserver host but I am very happy to see it because I havn’t quit in between my journey and completed what I decided to do.

Thank you. 🙂