Finally the irc bot can save the channel’s logs

Finally batuli can save the channel’s logs. I can still remember the very first day when I and sanketdg joined the irc channel ##testbot to work for irc bot batuli and I asked sanketdg “Won’t batuli save the logs of the channel as batul does for dgplug?” , sanketdg replied to me “Make it save the logs if you can!”.

I couldn’t ever imagined that making batuli save the logs of the channel could be done in so simple way. Ah yes, I spent my days studying about logging module and twisted log module. And i took help of twisted log module to make batuli save the channel’s log and sent a pull request. But sanketdg told me to make it simple and he suggested me to use logging module, yes he was pretty correct. The script was looking pretty complex. Hence I started working with logging module. On the next morning suddenly an idea came to my mind. I asked myself that why I am using these logging modules to save the channel’s log, I also have other options in Python . Because, Python is such a programming language with what you can do just anything. Coding in Python is nothing but playing with it 😉 . And what I did is just append the message of user to a file. There couldn’t be any simpler way to make your bot save the logs. Let me share it with you 🙂

with open(args.filename,'a') as fobj:
    fobj.write('\n' + time.strftime('[%d-%m-%Y %H:%M:%S]') + \
            ' <' + user + '> ' + msg)

To take command line argument, I have used argparse module instead to sys module to make the command line interface more interactive with user and it was an idea of sanketdg  🙂

So I am really happy that batuli now saves the logs of ##testbot. Join our channel ##testbot on irc.freenode . Fork us on github . Follow README section to know how to use batuli , just give it a try and I am sure that you will love it 😉

Calci

I have built Calci, a command line calculator for linux that performs basic operations like addition, subtraction, division and multiplication. I have used Python3 to build this command line tool. You will find that I had already made a blog post on Command line calculator earlier. Now this new post comes with some edits of the earlier one and another important thing is that I have made this open source .

To run Calci follow the steps given below:

  • git clone https://github.com/trishnaguha/Calci.git
  • python3 main.py followed by arguments

Since it is a command line tool you’ll need to provide arguments after python3 main.py . Type python3 main.py -h or python3 main.py –help to know this in details.

you can also fork Calci on github and send pull requests to add extra features or edit the existing features. You are also invited to open issue if you find any.

I am really excited about this project, Looking forward to turn this into a scientific one. 🙂

Learning Java, How A Java Code Is Compiled And Interpreted

Today, I have started my morning with learning Java programming language. The first thing that arose my interest in Java is the way a Java code is compiled and interpreted. The process of running Java code is Hybrid-Compiler-Interpreter where Javac works as hybrid compiler which is included in JDK/Java Development Kit and JVM/Java Virtual Machine works as interpreter. mbuf helped me to make my concept clear on how it works.

In Java, all code must reside inside a class and the class name should match with the file name that holds the code. I will give a simple example of a java program that prints Hello World.


public class A  //Defines a class called A
{
    public static void main(String args[]) //Calls the main() method
    {
        System.out.println("Hello world");//Prints Hello world to the console
    }
}

Here we need to give the name of the file as A.java since the name of the class is A. To run this java code do the following in terminal.

Terminal
javac A.java compiles the code A and creates a file named A.class that contains the bytecode version of the program which makes the code platform independent. This is an intermediate representation of the code that contains instructions the JVM will execute on next step.

Now java A actually runs the program. Here JVM works as interpreter. When Java source code is compiled, a file is created using .class extension with the name of the class used in the code. This is why Java file name and class name must be same. When we do java A we actually specify the name of the class that we want to execute. java A searches for a file by that name that has .class extension. If it find the file, it executes the code contained in the class.

The way a java code is compiled and interpreted is so interesting that I couldn’t stop myself sharing this blog post with you 🙂

Finish what you started, don’t give up

“Finish what you started, don’t give up” one of the most important motto of Open Source Project. This is not applied for just only Open Source but also for everything.

I have learnt something great from sanketdg in dgplug, can be termed as life lesson, i.e, “Completing the task that I have started or committed at any cost with out giving it up. “

I sent a pull request to pym in GitHub on some typo. On Wednesday kushal suddenly told to me to resolve conflict of the pull request that I have sent. My branch was having conflict , that’s why kushal was not able to merge the pull request with his master branch. And it took almost three hours to resolve the conflict.

Actually what I did was I fetched the upstream from git and rebased it  with my master branch. But the branch from where I sent the pr I forgot to it sync with master branch, thus my branch was totally messed up. sanketdg who knows git very well went on telling me the steps to resolve the problem. Two hours passed, still the conflict was not resolved. I told him that I better close the pr that I have made and open a new one. He told “nah. we better resolve this”. Every time I told sanketdg the same, he replied me the same. And finally with his help I solved the conflict. I learnt that it is necessary to always rebase your local branches with the master branch changes.

This is what we face in real time problems. There is no way to move away when you are having an issue/problem, we will have to solve it at any cost. In the same way we,who are now practicing can’t take a back because of being unable to solve a problem. What we have started, we have to finish it. Giving up is not an option.

Thank you 🙂

A Command-line Calculator using Python 3

Kushal introduced us to command-line parsing module argparse in Python3 on Wednesday in dgplug. Well now I am having the real fun with Python.

I have made a simple calculator using argparse that calculates addition, subtraction, division and multiplication. Run the code in Linux terminal as given below in the image.

The code:

import argparse

#Addition function
def add(a,b):
    val = a+b
    return val

#Subtraction function
def sub(a,b):
    val = a-b
    return val

#Division function
def div(a,b):
    val = a/b
    return val

#Multiplication function
def multi(a,b):
    val = a*b
    return val

#Main function
def Main():
    parser = argparse.ArgumentParser()

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-fa","--fadd",help="Performs addition",action="store_true")
    group.add_argument("-fs","--fsub",help="Performs subtraction",action="store_true")
    group.add_argument("-fd","--fdiv",help="Performs division",action="store_true")
    group.add_argument("-fm","--fmulti",help="Performs multiplication",action="store_true")

    parser.add_argument("num1",help="Number1 to calculate",type=int)
    parser.add_argument("num2",help="Number2 to calculate",type=int)

    args = parser.parse_args()
    
#Optional arguments 
    if args.fadd:
        print("The addition result of {} and {} is {}".format(args.num1,args.num2,(add(args.num1,args.num2))))
    elif args.fsub:
        print("The subtraction result of {} and {} is {}".format(args.num1,args.num2,(sub(args.num1,args.num2))))
    elif args.fdiv:
        print("The division result of {} and {} is {}".format(args.num1,args.num2,(div(args.num1,args.num2))))
    elif args.fmulti:
        print("The multiplication result of {} and {} is {}".format(args.num1,args.num2,(multi(args.num1,args.num2))))
    else:
        print("Error:Requires an argument to perform an action")

if __name__ == '__main__':
    Main()

This works like :

Screenshot from 2015-08-07 02:00:12

Leave comments for modification of the code 🙂

Let’s make an irc Bot using Python

The idea came from fhacdroid and SanketDG when we were talking about bots in dgplug. The bot named batul made by dgplug masters works brilliant. Being inspired from this we have also decided to make a bot using Python.

The first initiative was taken by SanketDG. He named a bot batuli. We have just started working on it using Python.

fhacdroidsanketdgtrishna_gAbhishekArora (names given as irc nicks) are the current members of this project. We have created a channel for testing bot. On freenode you are free to do /join ##testbot and contribute to this project to make this a better one. You can fork it from here. You can also send pull requests to batuli on github. We are experimenting with various kind of bots in ##testbot. This is really very exciting. We are having too much fun with testing the bots.

To run batuli do the following steps in terminal

  • git clone git@github.com:SanketDG/batuli.git
  • pip install -r requirements.txt
  • python main.py

We need a lot of modifications for this bot. We have just started 2 days ago. You are welcome to leave comments if you have any doubt/question. Happy to share with you 🙂

Check if a string is in a text file using Python 3

Check whether the string given by the user belongs to the text file or not using Python 3. A user has to give an input of a string. The script will check whether the string is there in the text file or not.

My objectives are

  1. Printing “Matched” if the input string is there in the text file.
  2. When user gives no input it tells user to “Enter a string” until gets any value.
  3. If the string is not there in the text file, it tells user to give an input again until the result is “Matched”.

I have written the script in two different ways.

  • if-else
  • try and except

I was stuck at completing my 3rd objective using if-else method. The “continue” statement in the else part was not working as the way I wanted. SanketDG from dgplug has helped me to achieve what I wanted , so thanks to him 🙂

Using If-else


#!/usr/bin/env python3

#Open the file
fobj = open("example.txt")
text = fobj.read().strip().split()

#Conditions
while True:
    s = input("Enter a string: ") #Takes input of a string from user
    if s == "": #if no value is entered for the string
        continue
    if s in text: #string in present in the text file
        print("Matched")
        break
    else: #string is absent in the text file
        print("No such string found,try again")
        continue
fobj.close()

Using try and except


#!/usr/bin/env python3
with open("example.txt") as fobj:
    text = fobj.read().strip().split()
    while True:
        try:
            s = input("Enter a string: ")
            if s == "":
                continue
            if s in text:
                print("Matched")
                break
            raise Exception("No such string found, try again")
        except Exception as e:
            print(e)

Modifications of the scripts are always welcome. Please leave comments for any kind of modification 🙂