❌

Normal view

There are new articles available, click to refresh the page.
Yesterday β€” 21 November 2024Payilagam

Reading#Eat the Frog: Ch-2

21 November 2024 at 12:00

In continuation from Chapter 1, Chapter 2 starts with how to approach the priority list. Because for a normal person[without any priority like me :-)] every task will be a priority. Unlike that, the author is suggesting an alternative.

It goes like this. Take a piece of paper or use a text editor and name that as β€œPriorities” and start writing all the tasks that comes to your mind which you wanted to do. Not necessarily in a day, week or month. Just random. For eg: Complete reading a book, finish the assignment, save a minimum amount, practice meditation etc., By the end of this activity, you will have an exhaustive list of task that you wish you could complete.

Next, take one more sheet of paper or open one more text editor and name this as monthly. In here, from the list that you created in β€œPriorities”, pick up those tasks which could be or has to be completed in the next month. From our example, we can choose β€œFinish an assignment” and add it to the β€œmonthly” list.

Now the monthly list will be comparatively less than the entire priorities and you have a clear idea of what needs to be done in next 30 days. From here, create one more list for β€œWeekly”. And do the same exercise of choosing the things that has to or could be completed in next 7 days. And start including them in the weekly list.

Hard part is now complete. From here, connect the things that was described in Chapter#1. Pick up the frog that is bigger to eat and add it to your daily list.

From a larger picture, the moment you knock off one task from daily it creates a ripple effect. That is, it knocks off a task from weekly, then monthly and from the entire priorities. You will accomplished by the end of first week. And if we do this on week 2 we will feel even more happier and accomplished.

This is all about Chapter-2. Once again, this is my understanding and nothing to do with authors narration.

See you again in Chapter-3! Thank you for reading!

IRC – My Understanding V2.0

By: Sugirtha
21 November 2024 at 10:47

What is plaintext in my point of view:
Its simply text without any makeup or add-on, it is just an organic content. For example,

  • A handwritten grocery list what our mother used to give to our father
  • A To-Do List
  • An essay/composition writing in our school days

Why plaintext is important?
– The quality of the content only going to get score here: there is no marketing by giving some beautification or formats.
– Less storage
– Ideal for long term data storage because Cross-Platform Compatibility
– Universal Accessibility. Many s/w using plain text for configuration files (.ini, .conf, .json)
– Data interchange (.csv – interchange data into databases or spreadsheet application)
– Command line environments, even in cryptography.
– Batch Processing: Many batch processes use plain text files to define lists of actions or tasks that need to be executed in a batch mode, such as renaming files, converting data formats, or running programs.

So plain text is simple, powerful and something special we have no doubt about it.

What is IRC?
IRC – Internet Relay Chat is a plain text based real time communication System over the internet for one-on-one chat, group chat, online community – making it ideal for discussion.

It’s a popular network for free and open-source software (FOSS) projects and developers in olden days. Ex. many large projects (like Debian, Arch Linux, GNOME, and Python) discussion used. Nowadays also IRC is using by many communities.

Usage :
Mainly a discussion chat forum for open-source software developers, technology, and hobbyist communities.

Why IRC?
Already we have so many chat platforms which are very advanced and I could use multimedia also there. So this is very basic, right?

Yes it is very basic, but the infrastructure of this IRC is not like other chat platforms. In my point of view the important differences are privacy and decentralized.

Advantages over other Chat Platforms:

  • No Ads Or Popups: We are not distracted from other ads or popups because my information are not passed to any company to track my needs and give marketing.
  • Privacy: Many IRC networks does not need your email or mobile number or even registration. Simply you can type your name or nick name, select your server and start chat instantly. Chat Logs also getting stored if required.
  • Open Source and Free: Server, Client – the entire networking model is free and open source. Anybody can install the IRC servers/clients and connect with the network.
  • Decentralized : As servers are decentralized, it could able to work even one server has some issues and it is down. Users can connect to different servers within the same network which is improving reliability and performance.
  • Low Latency: Its a free real time communication system with low latency which is very important for technical communities and time sensitive conversations.
  • Customization and Extensibility: Custom scripts can be written to enhance functionality and IRC supports automation through bots which can record chats, sending notification or moderating channels, etc.
  • Channel Control: Channel Operators (Group Admin) have fine control over the users like who can join, who can be kicked off.
  • Light Weight Tool: As its light weight no high end hardware required. IRC can be accessed from even older computers or even low powered devices like Rasberry Pi.
  • History and Logging: Some IRC Servers allow logging of chats through bots or in local storage.

Inventor
IRC is developed by Jarkko Oikarinen (Finland) in 1988.

Some IRC networks/Servers:
Libera.Chat(#ubuntu, #debian, #python, #opensource)
EFNet-Eris Free Network (#linux, #python, #hackers)
IRCnet(#linux, #chat, #help)
Undernet(#help, #anime, #music)
QuakeNet (#quake, #gamers, #techsupport)
DALnet- for both casual users and larger communities (#tech, #gaming, #music)

Some Clients-GUI
HexChat (Linux, macOS, Windows)
Pidgin (Linux, Windows)
KVIrc (Linux, Windows, macOS)

Some IRC Clients for CLI (Command Line Interface) :
WeeChat
Irssi

IRC Clients for Mobile :
Goguma
Colloquy (iOS)
LimeChat (iOS)
Quassel IRC (via Quassel Core) (Android)
AndroIRC (Android)

Directly on the Website – Libera WebClient – https://web.libera.chat/gamja/You can click Join, then type the channel name (Group) (Ex. #kaniyam)

How to get Connected with IRC:
After installed the IRC client, open.
Add a new network (e.g., β€œLibera.Chat”).
Set the server to irc.libera.chat (or any of the alternate servers above).
Optionally, you can specify a port (default is 6667 for non-SSL, 6697 for SSL).
Join a channel like #ubuntu, #python, or #freenode-migrants once you’re connected.

Popular channels to join on libera chat:
#ubuntu, #debian, #python, #opensource, #kaniyam

Local Logs:
Logs are typically saved in plain text and can be stored locally, allowing you to review past conversations.
How to get local logs from our System (IRC libera.chat Server)
folders – /home//.local/share/weechat/logs/ From Web-IRCBot History:
https://ircbot.comm-central.org:8080/

References:
https://kaniyam.com/what-is-irc-an-introduction/
https://www.youtube.com/watch?v=CGurYNb0BM8

Our daily meetings :
You can install IRC client, with the above link help, can join.
Timings : IST 8pm-9pm
Server : libera.chat
Channel : #kaniyam

ALL ARE WELCOME TO JOIN, DISCUSS and GROW

Before yesterdayPayilagam

Reading#Eat the Frog – Ch:1

19 November 2024 at 11:51

I always have the challenge of reading. Whether it is technical documentation, general documentation or anything. If I remember correctly, the last time I read something continuously was when I was in my school and college days. And that too nothing extraordinary but weekly magazines like Anandha Vikatan/Kumudham and very rarely newspapers. That got improved when I started my work and regularly read the news headlines from β€œThe Hindu”. That’s all the reading I have got in my entire life. I have this habit of purchasing the books and will think.. One day.. that One day will come and I will become a Pro Reader and I will read all the books. But that did not happened till date.

So I was pouring all these frustration in the β€œ#Kaniyam” IRC chat along with some more concerns like I have trouble planning things. I use to start with one and if I come across something else I will leave whatever I was doing and start doing the new item and it goes on and on. Then Srini from the Kaniyam IRC group suggested various ideas to give a try and one such idea is reading this book called β€œEat the Frog”.

I wouldn’t say the book has changed me completely overnight but the practice of reading a few pages continuously gives a sense of satisfaction. I am not saying I have read 20-30 pages continuously instead I planned to complete a chapter whenever i start.

The book as such has got things we often hear or see elsewhere but more importantly it is structured. When I say it is structured, it starts with the topic explanation on why the author has named the book as β€œEat the Frog”.

In our daily life if we think eating a frog is one of our primary task. How will one plan. Because eating a frog is not that easy. And that too if you have more than one frog how will one plan to do that. Here the author compares the frog to that of the tasks we have in a day. Not all tasks are difficult as eating a frog. So if we have frogs of different size and the task is to complete eating them all in a day. How will one approach. He will target finishing the bigger one then the next then the next and it goes on. By the time one completes the biggest he will get the confidence to go for the next smaller sized frog.

This analogy works the same way for our daily tasks. Rather than picking the easy ones and save the bulk or harder tasks for a later time, plan to finish the harder or most difficult task first which will help us move with the next difficult task with a lot more confidence.

This was primarily discussed on Chapter 1. After reading this I wanted to see if this approach works. I started implementing it immediately but listing the items it wanted to complete for that day. And in that I sorted those items based on the difficulty(in terms of time). I did not create an exhaustive list rather 4 tasks for that day and out of which 2 are time taking or difficult task.

End of the day I was able to complete the top 2 leaving the remaining 2. I still felt happy because i completed the top 2 which is harder. And moved the pending 2 to next day and kept the priority as top for those 2.

So far it is working and I will continue to write about the other chapters as I complete reading them.

β€œLet us all start get into the habit of reading and celebrate..happy reading”

Collections Tasks

By: Sugirtha
19 November 2024 at 01:55

TASKS:

  • // 1. Reverse an ArrayList without using inbuilt method
  • // 2. Find Duplicate Elements in a List
  • // 3. Alphabetical Order and Ascending Order (Done in ArrayList)
  • // 4. Merge Two Lists and Remove Duplicates
  • // 5. Removing Even Nos from the List
  • // 6. Array to List, List to Array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


public class CollectionsInJava {
	public static void main(String[] args) {
		// 1. Reverse an ArrayList without using inbuilt method
		// 2. Find Duplicate Elements in a List 
		// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
		// 4. Merge Two Lists and Remove Duplicates
		// 5. Removing Even Nos from the List
		// 6. Array to List, List to Array
		ArrayList<String> names = new ArrayList<>(Arrays.asList("Abinaya", "Ramya", "Gowri", "Swetha",  "Sugi", "Anusuya", "Moogambigai","Jasima","Aysha"));
		ArrayList<Integer> al2 = new ArrayList<>(Arrays.asList(100,90,30,20,60,40));
		
		ArrayList<Integer> al =  insertValuesIntoAL();
		System.out.println("Before Reversing ArrayList="+ al);
		System.out.println("Reversed ArrayList="+ reverseArrayList(al));
		
		System.out.println("Duplicates in ArrayList="+findDuplicates(al));
		
		System.out.println("Before Order = "+names);
		Collections.sort(names);
		System.out.println("After Alphabetical Order = " + names);
		Collections.sort(al);
		System.out.println("Ascending Order = "+ al);
		
		System.out.println("List -1 = "+al);
		System.out.println("List -2 = "+al2);
		System.out.println("After Merging and Removing Duplicates="+mergeTwoLists(al,al2));
		System.out.println("After Removing Even Nos fromt the List-1 = "+removeEvenNos(al));
		
		arrayToListViceVersa(al,new int[] {11,12,13,14,15}); //Sending ArrayList and anonymous array
	}
	
	// 1. Reverse an ArrayList without using inbuilt method
	private static ArrayList<Integer> reverseArrayList(ArrayList<Integer> al) {
		int n=al.size();
		int j=n-1, mid=n/2;
		for (int i=0; i<mid; i++) {
			int temp = al.get(i);
			al.set(i, al.get(j));
			al.set(j--, temp);
		}
		return al;
	}
	
	// 2. Find Duplicate Elements in a List 
	private static ArrayList<Integer> findDuplicates(ArrayList<Integer> al) {
		HashSet<Integer> hs = new HashSet<>();
		ArrayList<Integer> arl = new ArrayList<>();
		for (int ele:al) {
			if (!hs.add(ele)) arl.add(ele);
		}
		return arl;
	}
	
	//4. Merge Two Lists into one and Remove Duplicates
	private static HashSet<Integer> mergeTwoLists(ArrayList<Integer> arl1,ArrayList<Integer> arl2) {
		ArrayList<Integer> resAl = new ArrayList<>();
		HashSet<Integer> hs = new HashSet<>();
		hs.addAll(arl1);
		hs.addAll(arl2);
		return hs;
	}
	
	// 5. Removing Even Nos from the List
	private static ArrayList<Integer> removeEvenNos(ArrayList<Integer> al) {
		ArrayList<Integer> res = new ArrayList<>();
		Iterator itr = al.iterator();
		while (itr.hasNext()) {
			int ele = (int)itr.next();
			if (ele%2==1) res.add(ele);
		}
		return res;
	}
	
	// 6. Array to List, List to Array
	private static void arrayToListViceVersa(ArrayList<Integer> arl, int[] ar) {
		Integer arr[] = arl.toArray(new Integer[0]);
		System.out.println("Convert List to Array = " + Arrays.toString(arr));
		List<Integer> lst = Arrays.asList(arr);
		System.out.println("Convert Array to List = " +  lst);
	}
	
	private static ArrayList<Integer> insertValuesIntoAL() {
		Integer[] ar = {30,40,60,10,94,23,05,46, 40, 94};
		ArrayList<Integer> arl = new ArrayList<>();
		Collections.addAll(arl, ar);
		//Collections.reverse(al);   //IN BUILT METHOD
		return arl;
			//Arrays.sort(ar);  
		//List lst = Arrays.asList(ar);    //TBD
		//return new ArrayList<Integer>(lst);
		
	}

}

OUTPUT:

Exception Handling

By: Sugirtha
13 November 2024 at 03:06

What is Exception?

An Exception is an unexpected or unwanted event which occurs during the execution of a program that typically disrupts the normal flow of execution.

This is definition OK but what I understand : The program’s execution is getting stopped abnormally when it reaches some point which have some mistake/error – it may be small or big, compilation or runtime or logical mistake. And its not proceeding with further statements. Handling this situation is called exception handling. Cool. Isn’t it?

Why Exception Handling?

If we do not handle the exception program execution will stop. To make the program run smoothly and avoid stopping due to minor issues/exceptions, we should handle it.

So, how it is represented, In Java everything is class, right? The derived classes of java.lang.Throwable are Error and Exception. For better understanding lets have a look at the hierarchical structure.

Here I could see Exception and Error – when we hear these words looks similar right. So What could be the difference?

Errors are some serious issues which is beyond our control like System oriented errors. Ex. StackOverFlowError, OutOfMemoryError (Lets discuss this later).

Exception is a situation which we can handle,

  1. through try-catch-(finally) block of code
  2. Throws keyword in method signature.

try-catch-Finally :

What is the meaning? As we are the owner of our code, we do have some idea about the possible problems or exceptions which we can solve or handle through this try-catch block of code.

For Ex. Task : Make a Tasty Dish.

What could be the exceptions?

  1. Some spice added in lower quantity.
  2. Chosen vessel may be smaller in size
  3. some additional stuff may not be available

To overcome these exception we can use try-catch block.

try {
  Cooking_Process();
}
catch(VesselException chosenLittle) {
   Replace_with_Bigger_One();
}
catch(QtyException_Spice spiceLow) {
   add_Little_More_Spice();
}
catch(AddOnsException e) {
  ignore_Additional_Flavors_If_Not_Available();
}
catch(Exception e) {
  notListedIssue();
}
Finally {
  cleanUp_Kitchen();
}

Here there could be more catches for one try as one task may encounter many different issues. If it is solvable its called exception and we try to catch in catch blocks. The JVM process our code (cookingProcess) and if it encounter one problem like QtyException_Spice, it will throw the appropriate object. Then it will be caught by the corresponding catch, which will execute add_Little_More_Spice() and prevent the code from failing.

Here we see one more word, Exception, which is the parent class of all exceptions. Sometimes we may encounter the issue that is not listed (perhaps forgotten) but its solvable. In such cases, we can use the parent class object (since a parent class object can act as a child object) to catch any exception that is not listed.

Fine, all good. But what is the purpose of Finally here? Finally is the block of code that will always be executed, no matter if exception occurs or not. It doesn’t matter if you made a good dish or a bad one, but the kitchen must be cleaned. The same applies here: the finally block is used for releasing system resources that were mainly used (Ex. File). However, we can also write our own code in the finally block based on the specific requirements.

We have a situation where you have one cylinder to cook, and it gets emptied during cooking, so we cannot proceed. This will fail our process TastyDish, this situation cannot be handled immediately. This is called Error. Now lets recall the definition β€œErrors are serious issues that are beyond our control like a system crash or resource limitations.” Now we could understand, right?

Ex. OutOfMemoryError – when we load too much data, JVM runs out of memory. StackOverFlowError – when an infinite loop or recursion without base condition will make the stack overflow.

Lets revisit exceptions – they can be classified into two categories:

  • Checked Exception
  • UnChecked Exception.

What is Checked Exceptions?

Checked Exception is the exception which occurs at compile time. It will not allow you to run the code if you are not handling through try-catch or declares throws method.

Lets get into deeper for the clear understanding, the compiler predicts/doubts the part of our code which may throw the exceptions/mistakes which lead to stopping the execution. So that it will not allow you to run, it is forcing you to catch the exception through the above one of mechanisms.

If it is not clear, let us take an example, in the above code we have VesselException and QtyException_Spice . You are at your initial stage of cooking under the supervision of your parent. So we are ordered/ instructed to keep the big vessel and the spices nearby in case you may need it when the problem arise. If you are not keeping it nearby parent is not allowing you to start cooking (initial time ). Parent is compiler here.

throws:

So Expected exception by the compiler is called Checked Exception, and the compiler force us to handle. One solution we know try-catch-finally, what is that through declaration in the method? The exception in which method can be expected, that method should use the keyword β€œthrows <ExceptionClassName-1>” that is, it specifies this method may lead to the exceptions from the list of classes specified after throws keyword. After throws can be one class or more than one. whoever using this method with this declaration in method signature will aware of that and may handle it.

The good example for this is, IOException (parent) – FileNotFoundException (child). If you are trying to open a file, read it, the possible exceptions are: File Path Incorrect, File doesn’t exist, File Permission, Network issues etc. For Ex.

public static void main(String[] args) {
        try {
            // Calling the method that may throw a FileNotFoundException
            readFile("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            // Handle exception here
            System.out.println("File not found! Please check the file path.");
            e.printStackTrace();
        }
    }   

 // Method that throws FileNotFoundException
    public static void readFile(String fileName) throws FileNotFoundException {
        File file = new File(fileName);
        Scanner scanner = new Scanner(file);  // This line may throw FileNotFoundException
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }

What is Unchecked Exception?

The compiler will not alert you about this exception, instead you will experience at runtime only. This not required to be declared or caught, but handling is advisable. These are all subclasses of RunTimeException (Error also will throw runtime exception only). It could be thrown when runtime issues, illegal arguments, or programming issues.

Ex.Invalid index in an array, or trying to take value from a null object, or dividing by zero.

Ex. NullPointerException

String str = null; System.out.println(str.length()); /* Throws NullPointerException */

ArrayIndexOutOfBoundsException

int[] arr = new int[3]; System.out.println(arr[5]); /* Throws ArrayIndexOutOfBoundsException */

What is throw?

Instead JRE throws error, the developer can throw the exception object (Predefined or UserDefined) to signal some erroneous situation and wants to stop the execution. For ex, you have the idea of wrong input and wants to give your own error message.

public class SampleOfThrow {
    public static void main(String[] args) {
        // a/b --> b should not be 0
        Scanner scn = new Scanner(System.in);
        int a = scn.nextInt();
        int b = scn.nextInt();
        if (b==0) throw new ArithmeticException("b value could not be zero");
        System.out.print(a/b);
    }
}

Hey, wait, I read the word, User Defined Exception above. which means the developer (we) also can create our own exception and can throw it. Yes, absolutely. How? In Java everything is class, right? So through class only, but on one condition it should extend the parent Exception class in order to specify it is an exception.

//User Defined Exception
class UsDef extends Exception {
    public UsDef(String message) {
        super(message); //will call Exception class // and send the own error message
    }
}

public class MainClass {
    public static void main(String[] args) {
        try {
            Scanner scn = new Scanner(System.in);
            boolean moreSalt = scn.nextBoolean(); 
            validateFood(moreSalt);
 // This method will throw an TooMuchSaltException
        } catch (TooMuchSaltException e) {
            System.out.println(e.getMessage());  // Catching and handling the custom exception
        }
    }

    // Method that throws TooMuchSaltException if food contains too much salt and can't eat
    public static void validateFood(boolean moreSalt) throws TooMuchSaltException {
        if (moreSalt) {
            throw new TooMuchSaltException("Food is too salty.");
        }
        System.out.println("Salt is in correct quantity");
    }
}

Now Lets have a look at some important Exception Handling points in java of view. (The following are taken from chatGPT)

Error Vs. Exception

AspectErrorException
DefinitionAn Error represents a serious problem that a Java application cannot reasonably recover from. These are usually related to the Java runtime environment or the system.An Exception represents conditions that can be handled or recovered from during the application’s execution, usually due to issues in the program’s logic or input.
Superclassjava.lang.Errorjava.lang.Exception
RecoveryErrors usually cannot be recovered from, and it is generally not advisable to catch them.Exceptions can typically be caught and handled by the program to allow for recovery or graceful failure.
Common TypesOutOfMemoryError, StackOverflowError, VirtualMachineError, InternalErrorIOException, SQLException, NullPointerException, IllegalArgumentException, FileNotFoundException
Occurs Due ToTypically caused by severe issues like running out of memory, system failures, or hardware errors.Typically caused by program bugs or invalid operations, such as accessing null objects, dividing by zero, or invalid user input.
Checked or UncheckedAlways unchecked (extends Throwable but not Exception).Checked exceptions extend Exception or unchecked exceptions extend RuntimeException.
Examples– OutOfMemoryError
– StackOverflowError
– VirtualMachineError
– IOException
– SQLException
– NullPointerException
– ArithmeticException
HandlingErrors are usually not handled explicitly by the program. They indicate fatal problems.Exceptions can and should be handled, either by the program or by throwing them to the calling method.
PurposeErrors are used to indicate severe problems that are typically out of the program’s control.Exceptions are used to handle exceptional conditions that can be anticipated and managed in the program.
Examples of Causes– System crash
– Exhaustion of JVM resources (e.g., memory)
– Hardware failure
– File not found
– Invalid input
– Network issues
ThrowingYou generally should not throw Error explicitly. These are thrown by the JVM when something critical happens.You can explicitly throw exceptions using the throw keyword, especially for custom exceptions.

Checked vs. Unchecked Exception:

AspectChecked ExceptionUnchecked Exception
DefinitionExceptions that are explicitly checked by the compiler at compile time.Exceptions that are not checked by the compiler, and are typically runtime exceptions.
SuperclassSubclasses of Exception but not RuntimeException.Subclasses of RuntimeException.
Handling RequirementMust be caught or declared in the method signature using throws.No explicit handling required; they can be left uncaught.
ExamplesIOException, SQLException, ClassNotFoundException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Common UsageTypically used for exceptional conditions that a program might want to recover from.Used for programming errors or unforeseen runtime issues.
Checked atCompile-time.Runtime (execution time).
Effect on CodeForces the developer to handle the exception (either with a try-catch or throws).No such requirement; can be ignored without compiler errors.
Examples of CausesMissing file, network failure, database errors.Null pointer dereference, dividing by zero, illegal array index access.
When to UseWhen recovery from the exception is possible or expected.When the error typically indicates a bug or programming mistake that cannot be recovered from.

throw vs. throws:

Aspectthrowthrows
DefinitionUsed to explicitly throw an exception from a method or block of code.Used in a method signature to declare that a method can throw one or more exceptions.
UsageUsed with an actual exception object to initiate the throwing of an exception.Used in the method header to inform the compiler and the caller that the method might throw specific exceptions.
Keyword TypeStatement (flow control keyword).Modifier (appears in the method declaration).
Examplethrow new IOException("File not found");public void readFile() throws IOException { ... }
LocationCan be used anywhere inside the method or block to throw an exception.Appears only in the method signature, usually right after the method name.
ControlImmediately transfers control to the nearest catch block or exits the program if uncaught.Allows a method to propagate the exception up the call stack to the caller, who must handle it.
Checked vs UncheckedCan throw both checked and unchecked exceptions.Typically used for checked exceptions (like IOException, SQLException) but can also be used for unchecked exceptions.
Example ScenarioYou encounter an error condition, and you want to throw an exception.You are writing a method that may encounter an error (like file I/O) and want to pass the responsibility for handling the exception to the caller.

References : 1. https://www.geeksforgeeks.org/exceptions-in-java/

Installing Arch Linux in UEFI systems(windows)

12 November 2024 at 15:22

This will be a very basic overview in what is to be done for installing Arch Linux. For more information check out Arch wiki installation guide.

The commands shown in this guide will be in italian(font).

Step 1: Downloading the required files and applications

I have downloaded a few applications to help ease the process for the installation. You can download them using the links below.

Rufus:
This helps in formatting the USB and converting the disc image file to a dd image file. I have used rufus, you can use other tools too. This only works on windows.
rufus link

BitTorrent
The download option in the wiki page suggests we use BitTorrent for downloading the disc image file.
BitTorrent for windows

Arch Linux torrent file
This is for downloading the Arch Linux Torrent File. The download link can be found in the website given below.
Arch Linux Download Page

Step 2: The bootable USB

You will need a USB of size at least 2GB and 4GB or above should be very comfortable to use.

First open the BitTorrent application or the web based version and upload the magnet link or the torrent file to start downloading the disc image file.

Then to prepare the USB:

  1. Launch the application to make the bootable USB like rufus.

2.In the device section select your USB and remember all the data in the drive will be lost after the process.

3.In boot selection, choose the disc image file that was downloaded through torrent.

4.In the target system select UEFI as we are using a UEFI system.

5.In the partition scheme make sure GPT is selected.

6.In file system select fat32 and 4096 bytes as cluster size.

7.When you click ready it will present you with 2 options, select the dd image file which is not the default option.

After the process is done the USB will not be readable to windows, so there is no need to panic if you cannot access the USB.

If you are using a dual boot make sure you have at least 30 GB of unallocated space.

I would recommend to turn off bitlocker settings as it could give rise to other challenges during the installation.

Then get into the UEFI Firmware settings of your system. One easy way is to:
1.Hold shift key while pressing to restart the computer
2.Go into Troubleshoot
3.Go into Advanced Settings
4.Select UEFI Firmware Settings
5.You will have to restart again but you will be in the required place.

Turn off secure boot state. It is usually in the security settings.

Select save changes and exit.

When you log back into your system ensure that secure boot state is off by going into system information.

Go back to UEFI Firmware settings by repeating the process.

In the boot priority section, give your USB device the highest priority. This is usually in the boot section. Then select save changes and exit.

Step 3: Preparing Arch Linux Installation

When all the above steps are done and the system restarts, you will be prompted with a few options. Select Arch Linux install medium and press 'Enter' to enter the installation environment. After this you will need to follow a series of steps.

1. Verifying you are in UEFI mode.

To do that type the command
cat /sys/firmware/efi/fw_platform_size

You should get the result as 32 or 64. If you get no result then you may not be using UEFI mode.

2. Connecting to the internet:

If you are using an ethernet cable then you don't have to worry as you might already be connected to internet.
Use the command
ping -c 4 google.com
or another website to ping from to check if you're connected to the internet.

To connect to wi-fi, type in the command
ip link

This should show you all the internet devices you have. Your wi-fi should typically be wlan0 or something like wlp3s0, which is your device name.

Then type the command
iwctl

This should get you into an interactive command line interface.
You can explore the options by using the command
help

My device name was wlan0 so I'm using wlan0 in the command I'm going to show if yours is different make the appropriate changes.

To connect to the wifi use the command
station wlan0 connect "Network Name"
where "Network Name" is the name of your network.

If you want to know the name of your network before doing this you can try the command
station wlan0 get-networks

To get out of the environment simply use the command
exit

After you exit, you can verify your connection with
ping -c 4 google.com

If it doesn't work, try the command
ping -c 4 8.8.8.8

If the above also doesn't work, the problem may lie with your network.

However if the second option works for you, the fix would be to manually change the DNS server you're using.
To do that, run the command
nano /etc/systemd/resolved.conf

In this file if the DNS part is commented using a #, remove the # and replace it with a DNS server you desire. For eg: 8.8.8.8

ctrl + x to save and exit

Now try pinging a website such as google.com again to make sure you're properly connected to the internet.

3. Set the proper time

When you connect to the internet you should have the proper time. To check you can use the command
timedatectl

4. Create the partitions for Arch Linux

To check what partitions you have, use the command
lsblk

This will list the partitions you have. It will be in the format /dev/sda or /dev/nvme0n1 or something else. Mine was /dev/nvme0n1 so I'll be using the same in the commands below.

To make the partitions, use the command
fdisk /dev/nvme0n1

This should bring you to a separate command line interface.

It will give you an introduction on what to do.

Now we will create the partitions.
To create a partition, use the command
n

It will show you what you want to number your partition and the default option. Click enter as it will automatically take the default option if you don't enter any value. Let's say mine is 1.

It will show you what sector you want the partition to start from and the default option. Click enter.

Then it will ask you where you want the sectors to end: type
+1g

1g will allot 1 GB to the partition you just created.

Then create another partition in the same way, let's say mine is sector number 2 this time and finally instead of
+1g use +4g

This will allot 4 GB to the second partition you just created.

Create another partition and this time leave the last sector to default so it can have the remaining space. Let's say this partition is number 3.

partition 1 - EFI system partition
partition 2 - Linux SWAP partition
partition 3 - Linux root partition

5. Prepare the created partitions for Arch Linux installation

Here, we are going to format the memory in the chosen partitions and make them the appropriate file systems.

For the EFI partition:
mkfs.fat -F 32 /dev/nvme0n1p1

This converts the 1 GB partition into a fat32 file system.

For SWAP partition:
mkswap /dev/nvme0n1p2

This converts the 4 GB partition into something that can be used as virtual RAM.

For root partition:
mkfs.ext4 /dev/nvme0n1p3

This converts the root partition into a file system that is called ext4.

6. Mounting the partitions

This is for setting a reference point to the partitions we just created.

For the EFI partition:
mount --mkdir /dev/nvme0n1p1 /mnt/boot

For the root partition:
mount /dev/nvme0n1p3 /mnt

For the swap partition:
swapon /dev/nvme0n1p2

Step 3: The Arch Linux Installation

1. Updating the mirrorlist (optional)

The mirrorlist is a list of mirror servers from which packages can be downloaded. Choosing the right mirror server could get you higher download speeds.

This step isn't required as the mirror list is automatically updated when connected to the internet but if you would like to manually do it, its in the file
/etc/pacman.d/mirrorlist

2. Installing base Linux kernel and firmware

To do this, use the command
pacstrap -K /mnt base linux linux-firmware

Step 4: Configuring Arch Linux system

1. generating fstab

The fstab is the file system table. It contains information on each of the file partitions and storage devices. It also contains information on how they should be mounted during boot.

To do it, use the command:
genfstab -U /mnt >> /mnt/etc/fstab

2. Chroot

Chroot is short for change root. It is used to directly interact with the Arch Linux partitions from the live environment in the USB.

To do it, use the command:
arch-chroot /mnt

3. Time

The timezone has 2 parts the region and the city. I am from India so my region is Asia and the city is Kolkata. Change yours appropriately to your needs.

The command:
ln -sf /usr/share/zoneinfo/Asia/Kolkata /etc/localtime

We can also set the time in hardware clock as UTC.
To do that:
hwclock --systohc

4. Installing some important tools

The system you have installed is a very basic system, so it doesn't have a lot of stuff. I'm recommending two very basic tools as they can be handy.

i) nano:
This is a text editor file so you can make changes to configuration files.
pacman -S nano

ii) iwd:
This is called iNet wireless daemon. I recommend this so that you can connect to wi-fi once you reboot to your actual arch system.
pacman -S iwd

5. Localization

This is for setting the keyboard layout and language. Go to the file /etc/locale.conf by using
nano /etc/locale.conf

I want to use the english language that is the default in most devices so for doing that you have to uncomment(remove the #) for the line that says
LANG=en_US.UTF-8

As there are a lot of lines you can search using ctrl+F.

Then ctrl+X to save and exit.

Then use the command
locale-gen

This command generates the locale you just uncommented.

6. Host and password

To create the host name, we should do it in the /etc/hostname file. Use
nano /etc/hostname

Then type in what your hostname would be.
ctrl + X to save and exit.

To set the password of your root user, use the command
passwd

7. Getting out of chroot and rebooting the system

To get out of chroot simply use
exit

Then to reboot the system use
reboot

Remove the installation medium(USB) as the device turns off.

Step 5: Enjoy Arch Linux

Arch Linux is one of the most minimal systems. So you can customize it to your liking. You can also install other desktop environments if you feel like it.

My First Public Speaking

By: Sugirtha
12 November 2024 at 14:59

Public Speaking – It’s just two words, but it makes many people feel frightened. Even I did. I felt embarrassed to stand in front of my schoolmates/colleagues.

Usually, I am present in college during working days, but if it’s seminar days, you can’t find me – I will be absent. But whatever you try to avoid in life, one day you’ll face it, right? That was what happened in my interview. Fear! Fear!!

But how could we compare an interview with public speaking? Why not? If the interview panel has multiple people, and they ask you questions you may or may not know the answers – but at least in public speaking, you will speak about what you know.

I still have that fear. So, I decided not to run away but FACE THE ISSUE. A few good people supported me in overcoming this situation. First, my professor Muthu Sir, who advised me to join open-source communities, specifically ILUGC and KanchiILUGC. He said, β€œJust join, they will take care of you if you follow them.” I joined, and under Mr. Shrini’s guidance, I started doing simple projects. In between, he asked me to give a presentation at an ILUGC meet.

I said OK immediately (I already wanted to overcome my fear). I felt I accepted in a rush, and suddenly had mixed feelings like run away πŸ™‚ But he was so fast – I received an email to give my name, and the formalities proceeded. The real race started in my heart.

My inner thoughts: β€œWhat, Sugi? What are you going to do? The subject is fine, but can you speak in front of people?”

I said to myself, It’s OK, whatever, I have to do. Then, Muthu Sir, Ms.Jothy, friends, classmates, my family and all others encouraged me.

I still remember what Muthu Sir said: β€œWhat’s the worst that can happen? One, you can do well. If so, you’ll feel good and confident. Two, you may not do well, but that will push you to do better next time. Both outcomes will yield good and positive results, so just go for it.”

Then I practiced alone and felt OK. I had some paper notes in my hand, but when the laptop screen turned on, my heart rate went up, and my hands started shaking. When people asked me to start, I said, β€œI am Sugirtha,” and then forgot everything.

Thank God I at least remembered my name! Fine, let’s see the paper – What is this? I couldn’t read it, nothing was going inside my brain. It felt like Latin, which I don’t understand. I threw the paper aside, started recollecting, and said, β€œHTML stands for HyperText Markup Language.” Inside, I thought, Oh my God, this is not my first line to say, I thought I would start differently. For about 5 to 10 minutes, I fumbled with the points but didn’t deliver them as I expected. But when I started working on the code, I felt OK, as I got immersed in it.

Finally, it was over. There was still some tension, and after some time, I thought, I don’t know if my presentation was good or not, but at least I finished it. Then, after a while, I thought, Oh God, you did it, Sugi! Finally, you did something.

Now, I wonder if I get another chance, could I do it again? Back then, I somehow managed, but now… the fear returns. But this not the same as before which I feel I can overcome easily. So to overcome this I have to do more and more. I don’t want to prove anything to anyone, but I just want to prove something to myself. For my own satisfaction, I want to do more. I feel I will do better.

If I can, why can’t you?

Getting Started with Django: Creating Your First Project and Application

By: Sakthivel
12 November 2024 at 14:17

Django is a powerful and versatile web framework that helps you build web applications efficiently. Here’s how you can set up a Django project and create an application within it.

Step 1: Install Django

First, you’ll need to install Django on your machine. Open your terminal or command prompt and run:

pip install django

Step 2: Check Django Version

To confirm Django is installed, you can check the version by running:

python3 -m django --version

Step 3: Set Up Project Directory

Organize your workspace by creating a folder where your Django project will reside. In the terminal, run:

mkdir django_project
cd django_project

Step 4: Create a Django Project

Now, create a Django project within this folder. Use the following command:

django-admin startproject mysite

This will create a new Django project named mysite.

Project Structure Overview

Once the project is created, you’ll notice a few files and folders within the mysite directory. Here’s a quick overview:

  • manage.py: A command-line utility that lets you interact with this Django project in various ways (starting the server, creating applications, running migrations, etc.).
  • __init__.py: An empty file that tells Python to treat the directory as a Python package.

Step 5: Run the Development Server

Now that the project is set up, you can test it by running Django’s development server:

python3 manage.py runserver

Visit http://127.0.0.1:8000/ in your browser, and you should see the Django welcome page, confirming your project is working.

Step 6: Create an Application

In Django, projects can contain multiple applications, each serving a specific function. To create an application, use the command:

python3 manage.py startapp firstapplication

This will create a folder named firstapplication inside your project directory, which will contain files essential for defining the app’s models, views, templates, and more.

With this setup, you’re ready to start building features in Django by defining models, views, templates, and URLs. This foundation will help you build scalable and structured web applications efficiently.


TASKS:

1. Create a Django Application to display Hello World Message as response.

2. Create One Django Application with multiple views.

3. Create a Django Application to display Current Date and Time.

Open settings.py inside the project folder and add a application name(firstapplication) to INSTALLED APPS List[]

Next open the views.py inside the application folder import httpresponse and create a function.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def display(request):
    views_content='<h2>HELLO WORLD!<H2>'
    return HttpResponse(views_content)

def display1(request):
    views_content='<h2>WELCOME TO DJANGO<H2>'
    return HttpResponse(views_content)

def display2(request):
    views_content='<h2>WELCOME TO MY APPLICATION<H2>'
    return HttpResponse(views_content)

import datetime

# Create your views here.

def time_info_view(request):
    time = datetime.datetime.now()
    output = '<h1> Currently the time is ' + str(time) + '</h1>'
    return HttpResponse(output)

next open the urls.py inside the project folder

from firstapplication(application) import views

create a urls of the page in urlpatterns list[]

from django.contrib import admin
from django.urls import path
from firstapplication import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('welcome/',views.display),
    path('second/',views.display1),
    path('third/',views.display2),
    path('datetime/',views.time_info_view)
]

Now open the local host 127.0.0.1:8000 you will see the below page

it contains 5 pages admin(default),welcome,second,third,datetime these are we created ones.

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/welcome/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/datetime/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/second/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/third/ you will see below page

These are the essential steps for creating a Django project as a beginner, helping you understand the basic setup and flow of a Django application.

Address Book v2.0 as on 08Nov2024 – (DEVELOPMENT IN PROGRESS)

By: Sugirtha
8 November 2024 at 16:08

Project Title : Address Book

S/w Used : HTML, CSS, JavaScript with LocalStorage for storing data (little Bootstrap)

Framework Used : Text Editor

Description : A small addressbook which is having name, email, contact no, and city which is having CRUD operations.

Till Today :

  • From v1.0, design changed completely.
  • Code done for Adding new Contact with modal window.
  • And whenever new entry added that will get displayed in the table dynamically with del and edit buttons.
  • Delete button action also done.
  • Alignment I could not able to do well, so took chatGPT help.

To Do:

  • Edit action and Search are pending.
  • Add New screen is not getting closed after adding – has to be rectified.
  • Design should get changed in AddNew screen
  • Table – Headings font size should get changed. (As used bootstrap table class – th is not getting changed through css – have to research in it.
  • Some Code duplication is there, have to be optimized like keep in one function (inside validationPassed & addNewContact).

Technical WorkFlow:

function validationPassed : This function checks all the fields are not empty.

function getAddrBook : This function returns an Array which extracts the existing contacts from localStorage, if available, and parse it. Otherwise an empty array will be returned.

function addNewContact : If validationPassed, then new contact entry is created from 4 fields (Name, Email, ContactNo and City), together will form an object and pushed into addrBook array (got through getAddrBook) and will get saved into localStorage. showBook() function is getting called immediately to show the added contact.

function showBook() : This is actually a table where rows(contacts) with delete and edit buttons are getting added dynamically and will be shown.

function deleteCont(idx) : As the name suggests it will take the index of the array as input and delete the contact when the delete button pressed.

Output till now :

This image has an empty alt attribute; its file name is image-5.png

AddNew Screen:

gitlab : https://gitlab.com/Sugirtha/Kaniyam.git

Task#6-New version of integrating the Store Billing app to produce a well formatted pdf file using python

8 November 2024 at 15:00

I was so much into using the fpdf module that I almost gave up on this particular task. The challenge I faced is that, I can pass the entire content to the createpdf function but the formatting went completely off track. The other option i was thinking is that send lines one after the other to a text file and finally convert that text file to a pdf. But even that task looked out of my ability. I paused this for a few days and poured in all my frustration not just with this task but with all the other challenges in my IRC channel #kaniyam where I received awesome suggestions from Shrinivasan.T, again not just with the solution to this problem but in general about overcoming the challenges in reading.

Took a deep breath and started fresh and came across a resource where they implemented pdf creation using a different module called reportlab where there was a solution to insert the text to display into a python list and get the entries from the list using a loop and add it to the pdf construct. I was able to finally complete the first step using that module.

Here is the code block

import configparser
import psycopg2
import psycopg2.extras
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
config = configparser.ConfigParser()
config.read('config.ini')
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
bill=0
final_bill_txt = ''
textlines = []
def fetch_BillAmount(in_item,in_qty):
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
def billing():
global bill,textlines
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
textlines.append(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
def write2Pdf(lsTextline):
pdf = canvas.Canvas('Demo.pdf')
pdf.setFillColorRGB(0,0,255)
pdf.setFont("Courier-Bold",24)
pdf.drawCentredString(290,720,"Shoppers Mart")
pdf.line(30,710,550,710)
text = pdf.beginText(40,680)
text.setFont("Courier",18)
for line in lsTextline:
text.textLine(line)
pdf.drawText(text)
pdf.save()
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
textlines.append(f'Your total bill amount is ${bill}')
print('Thank you for shopping!')
textlines.append('Thank you for shopping!')
write2Pdf(textlines)
break

Task#5- My next attempt to create a pdf file using python

8 November 2024 at 14:48
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
textlines = ['Sample text 1','Sample text 2','Sample text 3','Sample text 4']
pdf = canvas.Canvas('Demo.pdf')
text = pdf.beginText(40,680)
text.setFont("Courier",18)
for line in textlines:
text.textLine(line)
pdf.drawText(text)
pdf.save()
view raw pdfGenDemo.py hosted with ❀ by GitHub

Task#4- Secure the DB config using configParser

6 November 2024 at 10:50

The below program uses configparser module to secure the DB config or the connection parameters. In the earlier programs the DB connections were all exposed and kept in the same program. In this program, DB connection is saved under a different file named β€œconfig.ini” and the parameters were called with the help of β€œConfigParser”.

import configparser#Note: All lowercase
import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
config = configparser.ConfigParser()#Note:the calling method is a camel case
config.read('config.ini')
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
view raw configparserDemo.py hosted with ❀ by GitHub

One day One Command(CLI)

30 October 2024 at 15:08

Day 1: pwd
1.pwd: This command stands for Print Working Directory. As the name suggests it helps us know the current/working directory.
Syntax: pwd
1 a.pwd -P: Stands for pwd physical. It returns the current physical directory ignoring all the symbolic links in the path.
Syntax: pwd -P
1 b.pwd -L: Stands for pwd logical. It returns the current logical directory completely preserving the symbolic links in the path.
Syntax: pwd -L

Day 2: poweroff

$ sudo poweroff The poweroff command shuts down the system safely and immediately terminating all processes where unsaved work could be lost. It also unmounts all file systems then powers off the hardware. It is a quick way to turn off the system safely. Users in most cases cannot operate this command without sudo.
$ sudo poweroff --force This command shuts the down the system immediately without terminating any processes. It is generally unsafe to do so. It could be used if the system is unresponsive.
$ sudo poweroff --halt This command works just the way poweroff works but it does not finally cut the power to the hardware systems. It could be used if you want to terminate all the current running processes.

Day 3: ls

  1. ls: The ls command stands for list and it is used to list the files and directories. If used simply without any context it lists the files and directories in the current working directory. It can also be used to list files in other directories by following it up with the path to the directory. To list the files and directories of a file that requires root access we can use sudo on which otherwise we get permission denied. Syntax:ls ls /path/of/directory sudo ls /path/of/restricted directory 3 a.ls -l: This command does the same as ls files with more details. It gives more details such as permissions, ownership, size, date last modified, etc. Syntax:ls -l 3 b.ls -a:This command like the ls file also shows files and directories including hidden ones. Those files usually start with a '.'. Syntax:ls -a 3 c.ls -lh:It is just like ls -l but is in a more human readable format. The sizes are mentioned in kb,mb, etc.

Day 4: cat

  1. cat: This command stand for concatenate. When used on a file it shows the content of the file. If used on executable files or on files containing images they usually return garbled text and symbols as it is interpreting binary data. This command can also copy the content of a file and append it to another file. cat file1 >> file2 appends the contents of file1 to file2. It can also combine two files and copy it to another file. cat file1 file2 > newfile combines the contents of file1 and file2 in newfile. Syntax: cat filename cat file1 >> file2 cat file1 file2 > newfile 4 a.cat -n: This command does the same as cat and numbers all the lines in the output. Syntax: cat -n filename 4 b.cat -b: This command does the same as cat -n but it doesn't number the blank lines. Syntax: cat -b filename 4 c.cat -s: This command does the same as the cat command but it suppresses repeated blank lines into only one blank line. Syntax: cat -s filename 4 d.cat -T: This command does the same as cat but show tabs as ^I helping us differentiate between tabs and spaces. Syntax: cat -T filename 4 e.cat -E: This command is similar to cat -n and instead of numbering all the lines it leaves the $ symbol at the end of a line to help us distinguish between the end of a line or if they just continue. Syntax: cat -E filename 4 f.cat -A: This command is a combination of cat -E and cat -T where it shows the end of each line by leaving a $ symbol and helps distinguishing spaces from tabs by replacing tabs with ^I. Syntax: cat -A filename

Some of these options can be used together.
For eg: cat -ns numbers the lines from start and shortens the repeated blank lines to just one and the numbering is done on the remaining blank line. cat -ET does the same as cat -A. cat -bE numbers only the non blank lines leaves a $ symbol at the end of a line, etc.

Day 5: echo

  1. echo: The echo command sends a message or a variable to all active users or can be used to create or overwrite files. Syntax: echo "Hi everyone" echo $HOME echo "the text" > filename.extension

5 a.echo -e: This command works the same way as echo does but it takes in escape sequences as well. For eg: \n,\t,etc.
Syntax: echo -e "First Line\nNext Line"

Day 6: head and tail

=====================================

I'm sorry to have missed yesterday. So today I will be doing 2 commands.

=====================================

  1. head: It displays the first few lines of a file it is used with. The default number of lines it shows is 10. If used on a file containing binary data it outputs garbled texts and symbols. When used on multiple files it will display each file with a file header.

Syntax: head file.extension
head file1.txt file2.txt

=====================================

6 a. head -n: It behaves the same as head but instead of the default number of lines, it displays the number of lines mentioned. If the mentioned number exceeds the data in the particular file then it displays all of the file without any errors. If this command is used on multiple files it outputs the number of lines in each of the files.

Syntax: head -n file.extenstion
head -n 5 file.txt

=====================================

6 b. head -c: It behaves similar to head -n but instead of the lines it takes number of bytes which the user has mentioned. Similarly, it displays the entire file if the number of bytes mentioned is more than what is available without any errors.

Syntax: head -c file.extension
head -c 25 abc.txt

=====================================

The commands after this may not work for non GNU systems.

=====================================

6 c. head -q: When this is used on multiple files it suppresses the file headers. It can also be used in combination with head -c or head -n.

Syntax: head -q file1.txt file2.txt
head -q -n 2 file1.txt file2.txt

=====================================

6 d. head -v: When this is used even on a single file then the file headers are displayed. If used together with head -q, head -v has the higher priority in whatever order it is done. So head -q -v or head -v -q will always display the headers.

Syntax: head -v file.txt

=====================================

  1. tail: This command is similar to head command with the only difference being it displays the last few lines.

Syntax: tail file.txt

=====================================

7 a. tail -n: This like the tail command instead of the last default number of lines we can specify the number of lines we want.

Syntax: tail -n file.txt

=====================================

7 b. tail -c: This command outputs the last number of specified bytes of the file.

Syntax: tail -c file.txt

=====================================

The commands after this may not work on non GNU systems.

=====================================

7 c. tail -f: This command works similar to the tail command, at the beginning it only displays the last 10 lines but it will continue to give more outputs as the file grows. This can be useful for growing log files. If data is overwritten instead of appended to the said file, tail -f may not work properly.

Syntax: tail -f file.extension

=====================================

7 d. tail -F: This is just a better version of tail -f. If it encounters any errors such as the file is temporarily deleted or being overwritten it retries and when the file is available again, it starts the process again.

Syntax: tail -F file.extension

=====================================

7 d i. tail -F/f --max-unchanged-stats: As tail -F keeps on checking the file indefinitely, it can be stopped using this command. We can issue the number of times tail -F can retry and if there is constantly no updates in the file it will stop retrying.

Syntax: tail -F --max-unchanged-state=5 file.extenstion

=====================================

7 d ii. tail -F/f --pid: This command is the same as tail -F but it stops retrying after a specific process ends.

Syntax: tail -F --pid= file.extension
tail -F --pid==123 logfile.txt

=====================================

7 e. tail -q: This suppresses the file headers if multiple files are used.

Syntax: tail -q file1.extension1 file2.extension2

=====================================

7 f. tail -v: This forces the file headers in the output even if only one file is used.

Syntax: tail -v file.extension

*************************************

Day 7: grep

=====================================

  1. grep: This command is used to look for a given pattern in a files or output lines.

Syntax: grep "pattern" filename

=====================================

8 a. grep -i: This command works the same way as grep but it is case insensitive.

Syntax: grep -i "PaTtern" filename

=====================================

8 b. grep -r: This command searches for the given pattern recursively completely in a given directory. It searches every file or director that is contained in the given directory and gives its results.

Syntax: grep -r "pattern" filename

=====================================

8 c. grep -n: This command does the same as the grep command but it also numbers the output lines.

Syntax: grep -n "pattern" filename

Task#3c: BillingApp with output in pdf file(not formatted properly)

30 October 2024 at 11:46

After many unsuccessful attempts, I was able to send the output from my previous code block to a pdf file. Definitely a huge learning in terms of how to properly import the necessary packages how to troubleshoot the error messages and find out the deprecated syntax and replace with the updated ones etc.,

here is the snapshot of the exceptions i received during the process of fixing

And here I am with a screenshot with no exception mentioned

My final code snippet below:

import psycopg2
import psycopg2.extras
from fpdf import FPDF
from fpdf.enums import XPos, YPos
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
final_bill_txt = ''
def billing():
global bill,final_bill_txt
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
final_bill_txt = final_bill_txt + (f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}\n')
def write2Pdf(in_text):
pdf = FPDF()
pdf.add_page()
pdf.set_font("helvetica", size = 15)
pdf.cell(200, 10, text = "Shoppers Mart",new_x=XPos.LEFT, new_y=YPos.NEXT, align = 'C')
pdf.cell(200, 10, text = final_bill_txt,new_x=XPos.LEFT, new_y=YPos.NEXT,align = 'L')
pdf.output("ShoppersReceipt.pdf")
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
final_bill_txt = final_bill_txt + (f'\n\n\n\nYour total bill amount is ${bill}\n\n\n\n\n\n''Thank you for shopping!')
print(final_bill_txt)
write2Pdf(final_bill_txt)
#print('Thank you for shopping!')
break

PDF Output:

General: Failure to learn from mistakes!

30 October 2024 at 11:35

I have been working on a task where I need to collect input(eg: Item code) from user, query the database to fetch the price and then to calculate the bill amount and print the output. I was able to do this successfully. Then comes the next learning where it was asked to feed this output into a pdf file.

I thought it would be a simple task where we will be importing a package and use that to write the output into a pdf file. I was proved terribly wrong.

I found a link where it was asked to use FPDF as a package to import and use it in the code. When I tried to install on my linux machine i kept getting the below error:

As usual I did not get the signal to use my senses rather my IT mindset to start searching like β€œunable to install fpdf” πŸ™‚ I went link over link over link but ended up with the same error. It started from 4:45 am this morning and finally around 6 am I decided to learn from β€œmistakes”. My senses started to work, especially the eyes and the sense of seeing πŸ™‚

I carefully went through the exception, yet my IT brain started to override and asked me to just copy and paste the command from the link. This is classic πŸ™‚

It was mentioned something like this:

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

Then I tried exactly the same command but this time my brain partially worked it seems so replaced xyz to fpdf:

Thank god. Computers aren’t meant to use abusive language. hehehehe πŸ™‚

Then I went back to the pavillion and started searching other links where they asked to install jinja2( i tried that too). And in the same error message, it was mentioned to consider virtual environment, why to leave that, yes I tried that too.

Somehow I got through installing the virtual environment. But after that, I do not know what to do or interpret the error details. So the failure streak continues

Finally…………………………….

My senses were awaken πŸ™‚ And the brain started to work as if I had an espresso shot πŸ™‚ This time i tried the below

Though it failed again. As I said, β€œI learnt from mistakes(error message)”. And this happened after that.

Moral of the story:

it was told by many people whom I have interacted so far that always β€œread through the error message. 99% it has got enough information to change and rerun the code or installation” But because of my inherited IT brain I have avoided that till today. But from today, I am planning to change…and β€œto learn from mistakes(errors)” always. πŸ™‚

Thanks for reading my funny story! πŸ™‚

Finding SubArray

By: Sugirtha
30 October 2024 at 11:23
package taskPkg;

import java.util.Scanner;

public class SubArray {

	public static void main(String[] args) {
		// FINDING SUBARRAY AND ITS POSITION
		System.out.println("Enter a sentence to search in.");
		Scanner scn = new Scanner(System.in);
		String sentn = scn.nextLine();
		System.out.println("Enter a word to be searched.");
		String word = scn.next();
		scn.close();
		char[] sentence = sentn.toCharArray();
		char[] key = word.toCharArray();
		int n = sentence.length, m = key.length;
		int i = 0, j = 0, st = 0; // i- maintain index in the sentence, j-maintain index in key
		boolean match = false;
		while (i < n && j < m) {// 
			//System.out.println("i=" + i + "     sentence[i]=" + sentence[i] + "    j=" + j + "   key[j]=" + key[j]);
			if (sentence[i] == key[j]) { //if it matches incrementing both pos
				i++;
				j++;
				if (j == m) { //if the key reaches end, made the match and exit
					match = true;
					break;
				}
			} 
			else {    // if no match move on to the next letter, but key should start from 0
				j = 0;
				i=st+1;
				st = i;  // this is to save the starting of the subarray
			}
		}
		if (match)
			System.out.println("SubArray is found at " + st);
		else
			System.out.println("SubArray is not found");
	}
}

OUTPUT:

Python(the programming language)

29 October 2024 at 12:30

Python: A programming language which many consider beginner friendly. A language which some programmers would argue to other aspiring programmers not to learn it first. Python is widely used in artificial intelligence programs, machine learning, data science, ethical hacking and so much more.

Created in February 20, 1991 by Guido Van Rossum, it is said that the name was inspired from the BBC TV show Monty Python's Flying Circus as the creator was a big fan of the show. It is said that he wanted to create a programming language that was easy to read compared to other programming languages at the time which people considered to have a more difficult syntax.

Python is one of the most used programming languages today. Some of the important reasons are that it is an open source programming language, many people would argue it has a very large library for every field in programming. It also has a large community with people who also create custom libraries, it even has custom IDEs. It is also used in many fortune 500 companies.

With all this why is there a group of people who argue this is a language beginners can learn and sometimes even the same people from the same group that argue that beginners shouldn't start learning it? The main argument the 2nd group advocates is that the programming language is too easy compared to other languages and when they try to learn other languages they might struggle in doing so.

There is no particular answer to the question, it just depends on the person learning it. The first programming language I properly learnt was python, but learning other languages after that was easy as i had something to compare to and I wasn't learning something complex without any context. In fact learning other languages made me understand how python could be working on a deeper level that I was unaware of by only knowing python and I hope that others who start by learning python have a similar experience.

I think that python is definitely a great programming language due to its simplicity while coding and trying to understand it. It also has what some people would consider disadvantages that it is not closer to the system compared to other languages but there are other people who consider the same statement to be an advantage for python. So it all comes down to what a particular person wants and sometimes python just occurs to be a very good option.

Task#3b – Billing application from DB using loop

29 October 2024 at 11:29
import psycopg2
import psycopg2.extras
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
def billing():
global bill,itemized_bill
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print_txt = 'Your total Bill amount : ',bill
print('Your total Bill amount : ',bill)
print('Thank you for shopping!')
break

Task#3a – To retrieve the bill amount for a specific store item from database

29 October 2024 at 09:14

In this program, the user can get the input about what item is required from the store and how many quantities. Based on the input the dynamic query returns the price of the item selected and the bill amount is calculated and printed.

import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

❌
❌