Stories of raydeeam

By Rayan

After resuming my study I've learned about File handling (I can recall file handling in C).

  • File handling Python gives us an easy way to manipulate files. We can divide files in two parts, one is test file which contain simple text, and another one is binary file which contain binary data which is only readable by computer.

    • File opening The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:

      "r" - Read - Default value. Opens a file for reading, error if the file does  not exist
      "w" - Write - Opens a file for writing, creates the file if it does not exist
      "a" - Append - Opens a file for appending, creates the file if it does not exist
      "x" - Create - Creates the specified file, returns an error if the file exists
      
    • Creating a file To create a new empty file:

      >>> f = open("file.txt", "x")
      
    • To Create a new file if it does not exist:

      >>> f = open("file.txt", "w")
      
    • Opening a file To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open. If we don't mention any mode then it will open the file as read only.

      >>> f = open ("file.txt")
      >>> f
      <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'>
      
    • Closing a file After opening a file one should always close the opened file. We use method close() for this.

      >>> f = open ("file.txt")
      >>> f
      <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'>
      >>> f.close()
      
    • Reading a file To read the whole file at once use the read() method.

      >>> f = open("sample.txt")
      >>> f.read()
      'I am Rayan\nI live in Bangalore\nI am from West Bengal\n'
      

      If we call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file.

      >>> f = open("sample.txt")
      >>> f.readline()
      'I am Rayan\n'
      >>> f.readline()
      'I live in Bangalore\n'
      

      To read all the lines in a list we use readlines() method.

      >>> f = open("sample.txt")
      >>> f.readlines()
      ['I am Rayan\n', 'I live in Bangalore\n', 'I am from West Bengal\n']
      

      We can loop through the lines in a file object.

      >>> f = open("sample.txt")
      >>> for x in f:
      ...     print(x, end=' ')
      ...
      I am Rayan
      I live in Bangalore
      I am from West Bengal
      

      Example:

      >>> f = open("sample.txt", "w")
      >>> f.write("I am Rayan\nI live in Bangalore\nI am from West Bengal")
      >>> f.close()
      >>> f = open("sample.txt", "r")
      >>> print(f.read())
      I am Rayan
      I live in Bangalore
      I am from West Bengal
      
    • Using the with statement (which I found so cool) In real life scenarios we should try to use with statement. It will take care of closing the file for us.


Today I read about few things those are listed below:

  • Data Structures in Python Data structures is a way to store and organize data. Obviously, some data structures are good in one set of problems, but terrible in other ones. The right choice of data structure can make your code faster, more efficient with memory and even more readable for other human beings. Python has few in-built data structures.

    • Lists List is a sequence of elements. It can store anything: numbers, strings, other lists, functions and etc. The fact that it can store anything is great but it has a disadvantage. This kind of list will require more memory. Let’s take a look at a basic example of list:

      # create list
      >>> list= ['Noname', 'Rayan', 'xyz', 100, 42, 55]
      >>> list
      ['Noname', 'Rayan', 'xyz', 100, 42, 55]
      # check if element is in list
      >>> 42 in list
      True
      
    • Tuples Another way to store a sequence of elements is to use tuples. Tuple is basically the same thing as list but with one difference. You can’t add or remove elements from tuples after initialization. It’s immutable data structure.

      >>> a = ('Noname', 'Rayan', 'xyz', 100, 42, 55)
      a
      >>> ('Noname', 'Rayan', 'xyz', 100, 42, 55)
      
    • Dictionary nother important data structure is dictionary. The difference between dictionary and list is that you access elements in dictionary by key, not by index.

      >>> dict = {'Rayan': 'Das','Kushal': 'Das','Sayan': 'Chowdhury'}
      >>> dict
      {'Rayan': 'Das', 'Kushal': 'Das', 'Sayan': 'Chowdhury'}
      
    • Sets Set stores only unique elements.

      >>> letters = {'a', 'b', 'c'}
      >>> 'c' in letters
      True
      >>> letters.add('d')
      >>> letters
      {'c', 'b', 'd', 'a'}
      
  • Strings In Python we declare strings in between “” or ‘’ or ‘’’ ‘’’ or “”” “”“ There are different methods available for strings.

    • Strip a String Got to know how to strip a string.
  • Functions A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

    • Defining a function This way we can define a function.

      >>> def func(params):
      ...     statement1
      ...     statement2
      
    • Calling a function

      >>> def func():
      ...     print("hello from func")
      ... 
      >>> func()
      hello from func
      
    • Local and Global variables

    • Keyward only arguments We can also mark the arguments of function as keyword only. That way while calling the function, the user will be forced to use correct keyword for each parameter.

    • Docstrings We use docstrings in Python to explain how to use the code, it will be useful in interactive mode and to create auto-documentation.

    • Got to know about Higher-order function. It does at least one of the following step inside: -Takes one or more functions as argument. -Returns another function as output.

    • Map function map is a very useful higher order function in Python. It takes one function and an iterator as input and then applies the function on each value of the iterator and returns a list of results.


I've started Python again from Pym book by Kushal

Read about following topic and solved few basic problems.

  • Data types
  • f-string ( Which I found so cool)
  • Type conversion
  • Conditional statements
  • Loops
    • When I started Python back in college I found it so confusing but then I got to know how it works.

I've paused here. Cleared all my basics again till now. Basics are the key ingredients in long run I believe.


About me

As I said learning is never easy. At least for me. When I first started learning Python from youtube back in my college, Every time tutorials starts with Variables, Operators and Expressions. I thought it's more like C/C++ and then I used to pause the tutorial and procrastinate. I procrastinate so much that I procrastinate the actual procrastination.

Well later I realized that I've wasted the time. But then I've started again and this time through docs. Yes from PYM book and blogs. I think docs gave me a better picture. I'm still learning. It's not that thing that you can complete within a week. Better things take time. Here are few things for beginners who is getting started with Python.

Whitespaces and indentation:

Whitespace and indentation in Python is important. Whitespace in the beginning of the line called indentation. For wrong indentation Python throws an error. Example:

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

There are more places where we should be following the same type of whitespace rules:

  • Add a space after “,” in dicts, lists, tuples, and argument lists and after “:” in dicts.
  • Spaces around assignments and comparisons (except in argument list)
  • No spaces just inside parentheses.

Comments:

Comments are simple English to explain what this code does. It's easier to understand your code if you follow proper commenting for every code snippets. Comment line starts with # and everything after is considered as a comment. Example:

#This is a comment
a = 10
b=20
#This line will add two numbers
a+b

Multi Line Comments:

#This is a comment
#written in
#more than just one line
print("Hey there")

or we can add a multiline string (triple quotes) in our code, and place our comment inside it.

'''
This is a comment
written in
more than just one line
'''
print("Hey there") 

Modules:

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application. To create a module just save the code you want in a file with the file extension .py To use a module you have to import it first. Example:

>>> import math
>>> math.sqrt(16)
4.0

Keywords and Identifiers:

Following identifiers are used as a keywords and these can not be used as an ordinary identifiers. 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

In Python we don’t specify what kind of data we are going to put in a variable. So you can directly write abc = 1 and abc will become an integer datatype. If you write abc = 1.0 abc will become of floating type. Example:

>>> a=10
>>> b=20.0
>>> type(a)
<type 'int'>
>>> type(b)
<type 'float'>

From the above example you can understand that to declare a variable in Python , what you need is just to type the name and the value. Python can also manipulate strings They can be enclosed in single quotes or double quotes like:

>>> 'Python is not a snake'
'Python is not a snake'
>>> "Python is a programming language"
'Python is a programming language'

Input from Keyboard:

Generally the real life Python codes do not need to read input from the keyboard. In Python we use input function to do input.

$ vim hello.py

number = int(input("Enter an integer: "))
if number < 100:
    print("Your number is smaller than 100")
else:
    print("Your number is greater than 100")

Output:

$ ./hello.py
Enter an integer: 229
Your number is greater than 100
$ ./hello.py
Enter an integer: 1
Your number is smaller than 100

Multiple assignments in a single line:

We can assign values to multiple variables in a single line:

>>> i, j = 100, 200
>>> a
100
>>> b
200

Operators and Expressions:

Operators are used to perform operations on variables and values. Python provides few operators which are below listed:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Arithmetic operator:

Arithmetic operators are used with numeric values to perform common mathematical operations:

>>> x=10
>>> y=10
>>> x+y #Addition
20
>>> x-y #Subtraction
0
>>> x*y #Multiplication
100
>>> x/y #Division
1.0
>>> x%y #Modulus
0
>>> x**y #Exponentiation
10000000000
>>> x//y #Floor division
1

Assignment operator:

Assignment operators are used to assign values to variables:

>>> x = 5
>>> x += 5
>>> x -= 5
>>> x *= 5
>>> x /= 5
Comparison operator:

Comparison operators are used to compare two values:

>>> x == y
>>> x != y
>>> x > y
>>> x < y
>>> x >= y
>>> x<= y

Logical operator:

and #Returns True if both statements are true
or #Returns True if one of the statements is true
not #Reverse the result, returns False if the result is true

Identity operator:

is #Returns true if both variables are the same object
is not #Returns true if both variables are not the same object

Membership operator:

in #Returns True if a sequence with the specified value is present in the object
not in #Returns True if a sequence with the specified value is not present in the object

Bitwise operator:

& #AND- Sets each bit to 1 if both bits are 1
| #OR- Sets each bit to 1 if one of two bits is 1
^ #XOR- Sets each bit to 1 if only one of two bits is 1
~ #NOR- Inverts all the bits
<< #Zero fill lest shift (Shift left by pushing zeros in from the right and let the leftmost bits fall off)
>> #Signed fill right shift (Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off)

This will guide you through making a pull request to a Git repository through the terminal so that you can make your life easier while working on a project.

How it works:

1. A developer creates the feature in a dedicated branch in their local repo. 2. The developer pushes the branch to a public GitHub repository. 3. The developer files a pull request 4. The rest of the team reviews the code, discusses it, and alters it. 5. The project maintainer merges the feature into the official repository and closes the pull request.

Fork a Repository:

To create a pull request you need to have made your code changes on a separate branch or forked repository. To fork a repository you need to open the repository and click on the fork button. You'll get a copy of the repository after fork. You can work with forked repository made your code changes then create a PR.

Clone the Repository:

To make your own local copy of the repository you would like to contribute to, let's fire up the terminal. We'll use git clone command with the URL that points to your fork of the repository.

$ git clone https://github.com/username/repository.git

Create a Branch:

To avoid trouble later, let's create a new branch in our repo so that the work you'll do is sorted separately.

$ git checkout -b [branch-name]

This command will create a new branch in your repo and switch to it.

Make changes locally:

This is where you'll add your features. If you create a new file remember to add it with git add command and commit them by git commit -m

$ git add [file-name] $ git commit -m [commit-message]

At this point you can use git push command to push the changes to the current branch of your forked repo.

$ git push origin [new-branch]

Make the Pull Request:

This is the most simple step if till now you've done correctly. Now click on the New pull request button in your forked repo. Write down a nice report explaining why these changes should be included in the official source of your project and then confirm. Project author will get a notification that you submitted a PR. They will review your code and you'll get notification for their further actions. They may reject your PR or they may suggest something for changes. Go back, edit it and push again. PR will be automatically updated. If the maintainer is want to integrate your contributions to the project, the maintainer have to click Merge and your code will become a part of the original repo.


Git is a very popular and efficient Distributed Version Control System used by many contributors for many projects. “Distributed” means that all developers within a team have a complete version of the project. It's free and open source. Most of us dislike Git on the first try even after running the most basic Git commands. Git is complicated at first I agree. But Git is so dear to Programmers. Sadly programmers life is a mess without Git. Its very helpful for managing projects.

“I know who did what, when, and why.” -Git

There are few commands using which we can make our life easier and let Git to track everything.

Getting & Creating Projects:

$ git init: Create a new directory, open it and perform git init to create a new git repository.

$ git clone: By running this command create a working copy of a local repository. There are several ways to clone repositories. 1. https:// clone URLs are available on all repositories, public and private. 2. SSH URLs provide access to a Git repository via SSH, a secure protocol.

Basic Snapshotting:

$ git status: It simply shows you what's been going on with git add and git commit. The Status messages also include relevant instructions for staging/unstaging files. Sample output showing that on branch “Pluto_Branch” nothing to commit.

[hackman@localhost foobar]$ git status
On branch Pluto-Branch
nothing to commit, working tree clean

$ git add: Git add command adds a change in the working directory to the staging area. It tells Git that you want to include updates to a particular file in the next commit.

$ git add [file-name.txt]: This command stage all changes in [file-name.txt] for the next commit.

$ git add -A: This command will add all new and modified files to the staging area. Along with unwanted/test files

$ git commit -m "[commit message]": m is used for connecting a commit message to your commit.

$ git rm -r [file-name.txt]: to remove a file/directory

Branching & Merging:

$ git branch: List all the branches associated with the repository. (the asterisk points to the current branch)

$ git branch -a: List all the branches associated with your repository (local and remote)

$ git branch [branch name]: this command is to create a new branch in the current repository

$ git branch -d [branch name]: Used to delete mentioned branch.

$ git push origin --delete [branch name]: This command is used to delete a remote branch

$ git checkout -b [branch name]: Used to create a new branch then switch to it

$ git checkout [branch name]: Used to switch to the mentioned branch.

$ git checkout - : used to switch to the branch last visited.

$ git checkout -- [file-name.txt]: discard all the changes to a file

$ git merge [branch name]: This command is used to integrate changes from another branch.

$ git merge [source branch] [target branch]: Allows us to merge a the source branch into the target branch.

Sharing & Updating Projects:

$ git push origin [branch name]: Pushes all the modified local objects to the remote repository and advances its branches.

$ git push -u origin [branch name]: This command sets the upstream of the current local branch, so that it tracks [branch name] branch of the remote repository origin.

$ git push origin --delete [branch name]: To delete a remote branch we use this command with —delete flag.

$ git pull: This command fetches the files from the remote repository and merges it with your local one.

$ git pull origin [branch name]: It will fetch the remote branch and merge it into your current local branch.

$ git remote add origin ssh://git@github.com/[username]/[repository-name].git: This command is used to add a remote repository.

$ git remote set-url origin ssh://git@github.com/[username]/[repository-name].git: To set a repository's origin branch to SSH

Inspection & Comparison:

$ git log: Shows a listing of commits on a branch including author, date, number of commits, current branch, what all things are required to commit, message, content.

$ git log --summary: This command will shows the list of commits with more details.


For a beginner, who just started playing with computers, SSH (Secure Shell) is basically a set of rules which provides a secure connection between two computers. It can be used to securely connect a computer to a remote computer. For example Developers or System Admins could continue their work while they're on vacation on another country using SSH. The way SSH works is by making use of a client-server model to allow for authentication of two remote machines and encryption of the data that passes between them.

There are three different types of encryptions used by SSH. 1. Symmetric encryption 2. Asymmetric encryption 3. Hashing

These techniques are used to maintain data transmission in ciphertext (written in a secret code). In the world of cryptography, specific ciphers are usually cracked at some point, and new stronger ciphers are developed. So SSH implementations will drop older ciphers and support newer ciphers over time.

Symmetric Encryption:

In symmetric encryption, only one key (let's say private key or secret key) is used both for encryption and decryption of the data transferred between client and server. Anyone who holds the 'one key' can decrypt the data. The process of creating a symmetric key is carried out by a key exchange algorithm

Key Exchange Algorithm is a method of securely exchanging cryptographic keys between two parties. If the sender and receiver wish to exchange encrypted messages then each must be encrypt the messages to be sent and decrypt the messages received.

Asymmetric Encryption:

In asymmetric encryption, both keys (private as well as public key) are used for encryption and decryption.

Suppose Tux wants to send some data to Nux. So Tux uses Nux's public key to encrypt data for it. Nux, on the other hand, uses its private key to decrypt the data which was encrypted by its public key. Similarly, if Nux wants to send some data to Tux then Tux's public key is used by Nux to encrypt the data and Tux's private key is used to decrypt the data.

So, which one is used in SSH?

SSH uses both symmetric and asymmetric encryption. Since asymmetric encryption is more time consuming, most of the SSH connections use symmetric encryption.

Want too know how SSH works? Check it out: How Secure Shell Works (SSH)


I was thinking to pen down my thoughts. So here it is, about how I got introduced to Open-Source. When I was in my final year, somehow I got to know about the word 'Open-Source'. It was all a mystery for me back then. Coming from a third-tier college, Open Source culture was a myth after 2013,2014 I guess. In my batch, hardly someone knows about Open Source and about communities. My college was not like the old era of college, when few masterminds like Kushal, Ratnadeep(rtnpro), Sayan, Chandan were there. Yes they are my college senior. I got to know about it later after I got to know about dgplug. Anyways that is another story. Yeah about Open Source, I started digging more about it, I asked one of my friends and I remember he said “Open-source software is a software whose source code is open to all, everyone can see and modify it”. That day something happened to me I guess. Suddenly I got my interests in it. At very first, after trying on my own I lose hope because I was struggling to learn to contribute and thought that it's impossible. So I left it midway for 3-4 months. Then one day I was talking to Ganesh Kadam in LinkedIn, he suggested me to join dgplug on IRC. Then again I started struggling to set up IRC (as I weren't aware of IRC) and joined dgplug channel. I dropped 'hi' there. Got a reply from sayan. I introduced myself that my name is Rayan and I'm in my final year and I'm from Dr. B.C. Roy Engineering College. Then got a reply from sayan: I feel sorry for you. And I had a chat with everyone, was trying to be online there all the time. Then got to know about Summer Trainning. That's how it all stated for me.


About me