❌

Normal view

There are new articles available, click to refresh the page.
Yesterday β€” 1 June 2025Main stream

Git Reset – A tool to correct your (commited) mistakes.

1 June 2025 at 05:43

Terminologies

  1. Work Tree: Your working tree are the files that you are currently working on. Your local folder.
  2. Git Index/Staging Area: The git β€œindex” is where you place files you want commit to the git repository. The index is also known as cache, directory cache, current directory cache, staging area, staged files. Before you β€œcommit” (checking) files to the git repository, you need to first place the files in the git β€œindex”.

The index is not the working directory, you can type a command such as git status, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename command).

In simple words, git reset is to correct your mistakes. Consider a scenario, where you have mistakenly did some wrong code and commited it too. Everything started to fall apart. Now you want to go back to the previous stable state (or previous commit). This is the scenario, where git reset helps you. In this blog post you will understand the usage of git reset in 3 different ways.

Visualization of Working Folder, Staging, Local Repository

Git Reset

In general, git reset’s function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. Git reset helps you in two broad categories.

  1. To remove changes from staging area.
  2. To undo commits at repository level.

Scenario #1 : To remove changes from staging area

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: sample.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add sample.txt

Checking the stage area

Now the file is been added to the staging area (but not commited). But now you realize that you have a wrong content inside it. So inorder to remove it from the staging area, you just need to execute git reset <filename>.

Now you can see that the file is been moved from the staging area to working directory. and the contents inside the file is preserved.

Some of the possible scenarios,

  1. If there are many files in the staged area, then you can simply use git reset.
  2. There is also another command to unstage files, git restore. git restore --staged .

Scenario #2 – To Undo commits at repository level

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: file.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add file1.txt
  6. Create a text file (eg: file2.txt)
  7. Add some content inside it.
  8. Add the file to the staging area. git add file2.txt
  9. Create a text file (eg: file3.txt)
  10. Add some content inside it.
  11. Add the file to the staging area. git add file3.txt
image.png

There are 3 modes to reset a commit from the local reposity.

Once any file or folder is committed, we won’t have the concept of resetting the file. It will be resetting the commits only.

All these 3 modes, will move the HEAD to a specified commit, and all the remaining recent commits will be removed. The mode will decide whether these changes are going to remove from staging area and working directory or not.

Mixed Method (Default)

Command: git reset --mixed <commit-id>

Functionality: It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status.

Use this when you realize you made some bad commits, but you want to keep all the work you’ve done so you can fix it up and recommit. In order to commit, you’ll have to add files to the index again (git add …).

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --mixed 002aa06

Now we can see the HEAD moved to the commit which we specified. And the file3.txt is removed from the local repository and staging.

But the contents inside the file is preserved in the working directory. We can check using the git status to see the file under Untracked files.

Soft Method

Command: git reset --soft <commit-id>

Functionality: All your files are intact as with –mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you’ve made some bad commits, but the work’s all good all you need to do is recommit it differently.

The index is untouched, so you can commit immediately if you want the resulting commit will have all the same content as where you were before you reset.

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --soft f8d7c74

Now we can see the HEAD moved to the commit which we specified. And the file2.txt is removed from the commit, but staging.

The contents in the file are preserved and its already present in the staging. We can check this using the git status to see the file under Added files.

Hard Method

Command: git reset --hard <commit-id>

Functionality: This is the easiest to understand, probably. All of your local changes get clobbered.

One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don’t change the branch but get rid of all local changes.

The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

Hands On: Our working directory will look like this,

We can add one more commit (so that we will have some commits to test).

so now we have 2 files in commit, and one file in working directory (untracked file – file3.txt). We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --hard f8d7c74

Now we can see the HEAD moved to the commit which we specified. Also the file2.txt is been removed from the local repository, staging and the working directory.

It removed the files that were present in the commit. This is the one that can really make you lose work, because it modifies your work tree.

The Strange Notation

When you are searching for the working for git reset, you might noticed people using HEAD^ and HEAD~1. These are just the shorthand or specifying commits, without having to use a hash name like f8d7c74.

It’s fully documented in the β€œspecifying revisions” section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things

  • HEAD~ is short for HEAD~1 and means the commit’s first parent. HEAD~2 means the commit’s first parent’s first parent. Think of HEAD~n as β€œn commits before HEAD” or β€œthe nth generation ancestor of HEAD”.

  • HEAD^ (or HEAD^1) also means the commit’s first parent. HEAD^2 means the commit’s second parent. Remember, a normal merge commit has two parents – the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).

  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

In this blog post we understood the working of different ways to reset a commit. I am having one question for you. When we are resetting to a different commit, (i.e) pointing the head to a different commit, what will happen to the removed commits ? Is there any way to go back to it ?

Java Methods

By: Prasanth
30 May 2025 at 16:31

Method is block of code or collections(group) of statement that perform a specific task.All method in java belong to a class.method similar to function and expose the behavior of objects.which only runs when it is called.

method must have return type weather void or return data like int , string...etc

Syntax

AccessModifer returntype methodName(Parameter List)
{
// method body 
}

Access Modifiers:-

=> public, private, protected, default – controls method access

Method overloading:

Same class same method name , different parameters
(compile-time polymorphism)

Method Overriding:-

Different class (extend(is an-relationship) )parent and child relationship and Redefining-parent method in child class( same method name and parameters)

Types of methods:

  • Static method
  • Instance method
  • Construtor(special method)

Why use methods?
To reuse code: define the code once , and use it many times

without method

public class Test_Withoutmethod {

    public static void main(String[] args) {

        int a =5 , b=3;
        int sum = a+b;
        System.out.println("Sum: "+ sum);

        int x=10, y=2;
        int result =x*y;
        System.out.println("Sum: "+result);
    }

}

with method:


public class Test_withMethod {


    static  void  add(int a , int b)
    {
        int sum =a+b;
        System.out.println("Sum: "+ sum);
    }
public static int minFunction(int n1, int n2)
{
    int min;
//  System.out.println("Min value is : "+min); you can not initialize local variable  ,when printing came compile time error.

    if (n1>n2)
    {
        min =n2;
    System.out.println("Min:n2 is : "+min);
    return min;
    }
            else
            {   
    min=n1;
    System.out.println("Min:n1 is : "+min);
    return min;
            }
    }


    public static void main(String[] args) {

   add(5,3);// callmethod 
   add(10,2); // reuse method 
   minFunction(1,2);
    }

}

Method Defining and Calling with return types and void :-


// method  defining and  calling
public class Method_Example1 {

    public static void main(String[] args) {
  int total= add(210,210);
  System.out.println(" Return value example => Total: 210+210 = "+total);
  twlethMark(550);
    }

    //  method using to void example 
    public static void twlethMark(int mark)
    {
        if(mark>580)
        {
            System.out.println("Rank:A1");
        }
        else if (mark >=550)
        {
            System.out.println("Rank:A2");

        }
        else
        {
            System.out.println("Rank:A3");
        }

    }

    public static int add (int n1,int n2)
    {
        int total = n1+n2;

        return total;


    }

}


swapping values inside method:-

public class Method_SwappingValue {

public static void main(String[] args) {

    int a =30;
    int b =45;
    System.out.println("Before swapping, a =" +a+ " and b ="+b);
    swapValueinFunction(a,b);
    System.out.println("\n Now ,Before and After swapping values will be same here");
    System.out.println("After swapping, a = "+a + ", b = "+b);
}

public static void swapValueinFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = "+a + ", b = "+b);

int c =a;  // a(30) value moved to c (),now a (empty) is  empty
a= b;  // b(45) value moved  a, because a is empty, now a is 45
b=c;  // c(30)  value   moved  to b(empty) , now b is 30
System.out.println("After swapping(Inside), a = "+a + ", b = "+b);



}

}

Method&Calling_Passing_Parameters

public class Method_Passing_Parameters {

    static String letter = " open the letter\n \n"
            + "To Smantatha,\n"
            + "\n"
            + "You are my heartbeat πŸ’“\n"
            + "My heart is not beeping... because you're not near to hear it.\n"
            + "Come close and make it beep again.\n"
            + "Make my heart lovable with your presence. ❀️\n"
            + "\n"
            + "Forever yours,\n"
            + "Prasanth πŸ’Œ";

    public static void main(String[] args) {
     sendLetter("prasanth","Java Developer"); //passing string parameter
    }

 static void readLetter(String reader,String career,int age) {
        System.out.println(reader+" read the letter from prasanth:");
        System.out.println(reader + letter);
    }

static void sendLetter(String sender,String career) {

System.out.println(sender+" sent a letter to samantha");    
//System.out.println("Message: "+letter);
System.out.println();
readLetter("samantha","Actress",35);

    }

}

Example: method using to return value and void

public class JavaReturnandVoid{

    public static void main(String[] args) {
        int Balance =myAccountBalance(100);
System.out.println("Balance: "+Balance);
System.out.println("\n");
samInfo(25,55);
char [] data=samInfo(25,55,5.9);
System.out.println(data);


    }

static void samInfo(int i, int j) {

    System.out.println("Age: "+i);
    System.out.println("Weight: "+j);


    }
// differen  paremeter if you have ,  how to return  ?
static char[] samInfo(int i, int j, double d) {
    System.out.println("differen  paremeter if you have ?  how to return ");
    String data = "Age:" +i+", weight"+j+", Height:"+d;
    return data.toCharArray(); //convert to char[]

}

static int myAccountBalance(int AccountBalnce ) {

    int myPurse = 1;
    int Balance =myPurse+AccountBalnce;
        return Balance;
    }


}

<u>How to different way return the value:-</u>

public class MethodReturnExample {

public static void main(String[] args) {
    // 1. calling void method 
     greet();
     // 2. calling int return method
       int sum=add(210,210);
       System.out.println("sum: "+ sum);
       //3.calling  String return method
       String message=getMessage("Prasanth");
       System.out.println(message);
       //4. calling method that returns both and string
          Object[] data=getUserinfo();
          System.out.println("Id "+ data[0]);
          System.out.println("Name "+ data[1]);


}

// 1.void method - just print
static void greet() {
System.out.println("Hello ,Welcome to java ");
}
//2. return int

static int add(int num1,int num2)
{
int sum= num1+num2;

return sum;

}
//3. return string

static String getMessage(String name)
{
return "Hi My name is " + name +" i am Javadeveloper";
}

//4. return int and string using object[] or Array
static Object[] getUserinfo()
{
int id =101;
String name ="Hellow";

return new Object[] {id,name};

}

}



<u> Important Return Type Scenarios</u>

int return 5 + 3; Return a number
String return "Hello"; Return a message or text
boolean return a > b; Return true/false
char[] return name.toCharArray(); Return letters from a string
Array return new int[]{1,2,3}; Return multiple numbers
Object return new Person(...); Return class object
void System.out.println("Hi"); Just perform action, no return


// method ovlerloading and overriding we will see Java Oops concept


<u>Method&Block Scope:-</u>

public class MethodandBlock_Scope_Example {

public static void main(String[] args) {

//System.out.println(x);
int a =100;
System.out.println(a);

    //method Scope: x is visible any where inside main method
    //Anywhere in the method
    int x =100;
    System.out.println("x in method:"+x);

    if(x>50)
    {
        //Block Scope: y is only visible inside this if block
        //only inside the block
        int y =200;
        System.out.println("Y in if block: "+y);

    }
    // try to access y outside the block
//  System.out.println("y is outside if block: "+y); //error not visible out of block


}

}



<u>Java Recursion:-</u>



package java_Method;

// Factorial Using Recursion
public class Recursion_Example {

int fact(int n)
{
    int result;

    if (n==1)

        return 1;
        result =fact(n-1) * n;

        /*fact(3-1) *3 -> fact (2) * 3  becomes -> (fact(1) *2)*3)
         * fact(4-1) *4 -> fact (3) * 3  
         * 
         * 
         * 
         * 
         */
        return result ;


}


public static void main(String[] args) {

    Recursion_Example obj1 = new Recursion_Example();
    System.out.println("Factorial of 3 is "+ obj1.fact(3));
    System.out.println("Factorial of 4 is "+ obj1.fact(4));
    System.out.println("Factorial of 5 is "+ obj1.fact(5));

/*

  • fact(5) = 5 x 4 x 3 x 2 x 1 =120
  • fact(1) = 1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 = 24
  • fact(5) =24*5 =120
  • ------------------
  • fact(4) = 4 Γ— 3 Γ— 2 Γ— 1 = 24
  • fact(1) =1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 =24
  • fact(4) =24
  • ------------------
  • fact(3) = 3 Γ— 2 Γ— 1 = 6
  • fact(1) =1
  • fact(2) =1*2 =2
  • fact(3) =2*3 =6
  • ------------
  • */

    }

}


package java_Method;

// Sum of Natural Numbers Using Recursion
public class RecursionExample1 {

public static void main(String[] args) {


    int result = sum(10);
    System.out.println(result);


}

public static int sum(int k)
{
    if(k>0)
    {
        return k+ sum(k-1);
    }

    else
    {
        return 0;
    }
}

}








Constructor

By: Prasanth
23 May 2025 at 15:25

What is constructor?

  • A constructor is a special type of method it used to initialize objects.

  • It has same name as the class and does not have a return type.(why do not return type because constructor is initialize the object .not to return value).

  • Called automatically when an object is created using new keyword.

Constructor:-

  • Java constructor is special type of method that are used to initialize object when it is created
  • It has the same name as its class and is syntactically similar to a method ,however constructors have no explicit return type include void .
  • You will use a constructor to give initial values to the instance variables defined by the class or to perform any other star-up procedures required to create a fully formed object.

  • All classes have constructor , whether you define one or not because java automatically provides a default constructor that initializes all member variables to zero.once you define your constructor , the default constructor is no longer used.

  • Constructors in Java are called automatically when you create an object to initialize objects attributes(instance variable 0r data).

  • Constructors in Java are used only to initialize instance variables, not static variables(just try to static variable for initialize ,no came error but not recommend ). Each object get its own copy of the variables,they are stored in different memory locations.you can have only one constructor with the same parameter list(signature)
    ,you can create many objects using that constructor.

Why Constructors Can’t Be Inherited?

Constructors are not inherited: Sub-classes don't get super class constructors by default. or You cannot inherit (or override) a constructor from a parent class in a child class.But you can call the constructor of the parent class using super().

What does β€œinherited” really mean?
when a child class gets access to the parent class's and variables automatically-without writing again in the child class

Note: just they are inherited , does not automatically called (You get access automatically, but you use them manually), you still need call them like any normal method or variables.

when a child class extends a parent class ,it inherits method and variables , but not constructors.
The child class must to explicitly call the parts's constructor using super();

Example:-

public class Parent_Child {

    String var="Parent_variable";
Parent_Child
{
        System.out.println("Parent Constructor");
}

    void show()
    {
        System.out.println("Parent_instacemethod");
    }

}


public class Child_parent  extends Parent_Child{

Child_parent {
        super(); //  You must call it, not inherited
        System.out.println("Child Constructor");
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //    // Child class doesn't define 'var' or 'show()' but it gets them from Parent  
        Child_parent obj1 = new Child_parent();
        obj1.show(); // You’re calling the inherited method
        System.out.println(obj1.var); // You’re accessing the inherited variable.


    }

}

Constructor cannot be overridden

Overriding means redefining a method in a child class with the same signature.
But constructor are not inherited , so you can not override them.Also constructor are not normal methods, so overriding does not apply.
finally constructor can not to be inherited and overriding .

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    // This is not overriding
    Child() {
        System.out.println("Child Constructor");
    }
}

Rules for creating java Constructor:-

  • The name of the constructor must be the same as the class name.
  • Java constructors do not have a return type include void.
  • In a class can be multiple constructors in the same class ,this concept is known as constructor overloading.
  • You can use the access modifier in the constructor ,if you want to change the visibility/accessibility of constructors.
  • Java provides a default constructor that is invoked during the time of object creation . if you create any type of constructor, the default constructor (provide by java) is not invoked(called).

Cannot be called like normal methods (c.Parent() calls the method, not constructor)

do not define two constructor with same parameter type even if parameter names are different ,java can not accept.

Example:

class Student {
Student() {
System.out.println("Constructor called!");
}
}

public class Test {
public static void main(String[] args) {
Student s = new Student(); // Constructor is called automatically here
}
}

output:-
Constructor called!

You do not call the constructor like a method (s.Student()).
You just create the object, and Java will automatically call the constructor.

Creating constructor:-

Syntax

Class ClassName{



Classname()
{
}
}

Types of Java Constructors:-

  • Default constructor(implicit Default constructor) => No parameters and invisible.
  • No-args Constructor.(explicit Default constructor) => No parameters
  • Parameterized Constructor => with parameters multiple constructor with different parameters.Used to initialize object with specific values.

Default constructor

If you do not create any constructor in the class, java provides a default constructor that initializes the variables to default values like 0,null,false.

public class DefaultConstructor {
    String name ;
    int age;
    String jobRole;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DefaultConstructor obj1 = new DefaultConstructor();
        obj1.name="R.prasanth";
        obj1.age=25;
        obj1.jobRole="JavaDeveloper";
        System.out.println("Name: "+obj1.name+", Age: "+obj1.age+", JobRole: "+obj1.jobRole);

    }
}

Example:2

public class DefaultConstructor1 {
    int id;
    String name;
    public static void main(String[] args) {

        DefaultConstructor1 s1 =new DefaultConstructor1();
        System.out.println("ID: "+s1.id);
        System.out.println("Name: "+s1.name);

    }
}

No-args Constructor.

The No-Argument constructor does not accept any argument,By using the no-args constructor you can initialize the class data members(fields or global variable) and perform various activities that you want on object creation.

Example:-


public class SimpleConstructor {
    //Explicitly you created constructor now ,no more invoked java provide default constructor
    SimpleConstructor()
    {
        System.out.println("Vankam da mapla Thiruttani irunthu");
    }
    public static void main(String[] args) {
        System.out.println("The main() method ");
        //creating a class's object, that will invoke the constructor.
        SimpleConstructor obj1 = new  SimpleConstructor();

    }
}


Example;1

public class NoArgsConstructor {
    int id;
    String name;

    NoArgsConstructor()
    {
        id =101;
        name ="Jhon";

    }

    void show ()
    {
        System.out.println("ID: "+id+", Name: "+name);
    }
    public static void main(String[] args) {
        System.out.println("NoArgs-constructor");

        NoArgsConstructor s1 = new NoArgsConstructor();
        s1.show();
    }
}

3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized constructor.
use when you need to initialize different objects with different data.
Use with this keyword to avoid confusion between parameter and instance variable

Example:1

public  class Parmet_Constructor {

    String name,jobStatus,jobFinding;
    static int age;

    Parmet_Constructor (String name,int age,String jobStatus,String jobFinding)
    { //this.varName β†’ refers to current object's variable.
     this.name=name;
     this.age=age;
     this.jobStatus=jobStatus;
     this.jobFinding=jobFinding;
    }
    public void  studentDetails()
    {
        System.out.println("name: "+ name+", age: "+age+",jobStatus: "+jobStatus+",jobfinding: "+jobFinding);
    }

    public static void main(String[] args) {
        Parmet_Constructor  obj1 = new Parmet_Constructor ("Prasanth",25,"Job_seeker","Java_Developer");
        obj1.studentDetails();
    }
}


Example:2

public class ParameterizedConstructor {
   int experience ; 
   int salary;
   String jobVacancy, name;
   // Parameterized constructor
   ParameterizedConstructor(String name, String jobVacancy, int salary,int experience) {
       this.name = name;
       this.jobVacancy = jobVacancy;
       this.salary = salary;
       this.experience= experience;
   }
   void candidateInfo() {
       System.out.println("Candidate Name: " + name);
       System.out.println("Job Vacancy: " + jobVacancy);
       System.out.println("Salary: " + salary);
       System.out.println("Experience: " + experience);
       System.out.println("-------------------------------");
   }
   public static void main(String[] args) {
       ParameterizedConstructor candidate1 = new ParameterizedConstructor("Prasanth", "Java Developer", 25000,1);
       ParameterizedConstructor candidate2 = new ParameterizedConstructor("Vignesh", "Frontend Developer", 26000,1);
       candidate1.candidateInfo();
       candidate2.candidateInfo();
   }
}

Constructor Overloading:-

Constructor overloading means multiple constructors in a class.when you have multiple constructor with different parameters listed, then it will be known as constructor overloading.

Example:

/constructor overloading
public class StudentData_ConstructorOverloading {
    //fields or globalvariable
   String name, gender, class_section, DOB, BloodGroup;
   float height;
   int id;
   // Constructor 1
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String BloodGroup) {
//this used to refer to current object's variable:
       this.id = id; //local variable opposite side global variable
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.BloodGroup = BloodGroup;
   }
   // Constructor 2
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String DOB, float height) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.DOB = DOB;
       this.height = height;
   }
   // Constructor 3
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
   }
   void studentData() {
       System.out.println("ID: " + id);
       System.out.println("Name: " + name);
       System.out.println("Gender: " + gender);
       System.out.println("Class Section: " + class_section);
       System.out.println("DOB: " + DOB);
       System.out.println("Blood Group: " + BloodGroup);
       System.out.println("Height: " + height);
       System.out.println("-----------------------------");
   }
   public static void main(String[] args) {
       StudentData_ConstructorOverloading student1 = new StudentData_ConstructorOverloading(1, "Mukesh", "Male", "A", "B+");
       StudentData_ConstructorOverloading student2 = new StudentData_ConstructorOverloading(2, "Prasanth", "Male", "C", "03/06/2000", 5.10f);
       StudentData_ConstructorOverloading student3 = new StudentData_ConstructorOverloading(3, "Shivan", "Male", "B");
       student1.studentData();
       student2.studentData();
       student3.studentData();
   }
}
// global/field(static/non-static)  if do not initialize variable value it will provide default value.
/*
* int byte shrot long-> 0
* float double -. 0.0
* String  null
* boolean  default value is false
* 
*
*
*/


Example:-

public class Student_Constructor_DoandDonot {

    int id;
    String name,department;
    char gender;

    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    // do not define  two constructor with  same  parameter type even if parameter names are different ,java can not accept
    /*
    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
*/
    /*
    Student_Constructor_DoandDonot(int Id, String Name,String Department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    */
    Student_Constructor_DoandDonot(int id, String name,char gender,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
        this.gender=gender;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //do's
        Student_Constructor_DoandDonot student1 =new Student_Constructor_DoandDonot(101,"Prasanth","ComputerScience");
        Student_Constructor_DoandDonot student2 =new Student_Constructor_DoandDonot(102,"shivan","History");
        Student_Constructor_DoandDonot student3 =new Student_Constructor_DoandDonot(103,"Parvathi",'F',"History");
        student1.infoStudent();
        student2.infoStudent();
        student3.infoStudent3();

    }
    public void infoStudent() {
   System.out.println("id: "+id+", Name: "+name+", Department:" +department);       
    }
    public void infoStudent3() {
        System.out.println("id: "+id+", Name: "+name+", Gender:"+gender+", Department:" +department);       
        }
}

  • Constructors cannot be inherited, but you can call superclass constructor using super().
  • You cannot inherit (or override) a constructor from a parent class in a child class.
  • Constructors can use this keyword to refer to the current object.

=>this()

  • This refers current class object
  • This used to call another constructor in same class
  • this() Only use to inside constructor not any others
  • Must be the first line in the constructor.
  • not allowed in normal methods.
  • Does not work with static methods or variables.
  • can not be used with super() in same constructor. helps when may constructor share common values.
  • To access current class instance variable (to avoid confusion with parameter name)
  • To call instance method of same class

What this does not do:

  • Not for inheritance
  • Not for typecasting
  • Not used for calling parent constructor (use super() for that

=>super()

  • Used to call parent class constructor.
  • you can use super() inside the first line of the
    child class constructor to call parent constructor.
    (when you create a child object, the parent part must to initialized first.)
    why? to initialize parent class fields. (or)
    Used to initialize parent class properties.
    In child classes to call parent constructor (especially if the parent class has a parameterized constructor). can not call parents methods-only constructor.

  • Every child constructor must call a parent constructor (either explicitly with super() for parametrized constructor or implicitly (java automatically call ) if parent has no-args constructor). otherwise compilation error.
    why? Because java needs to create the parent part of the object first.even if yo did not write extends ,your class still extends object class,this class parent of all class in java.

if the parent only has parameterized constructors, you must explicitly call super(args) in the child constructor.

To access parent class variables/methods (if child class has same name).You cannot inherit constructors – Only call them using super()
Why?
A constructor name = class name, so it’s always specific to its own class.

Explain constructor overloading with example?

Constructor overloading means creating multiple constructor with the same class name but different parameter(number,type,order),purpose to initialize objects different ways.

What happens if both this() and super() are used?

you can not use both this() and super() in the same constructor, because both must be the first statement in the constructor.

Why constructors can’t be inherited?
comment me in the blog.
hint: inheritance is allows a child class it inherit properties(fields) and behavior(method) from parent class.

How do this and super differ?

Image description

When is constructor called in real life?

Constructors are automatically called when an object is created using new keyword.
Real-time Use Cases:

When reading user data (like name, age) into an object.

When fetching data from a database and storing in object (e.g., Employee, Product).

While creating objects in Java applications, games, or backed APIs.

can we create object in instance method?
yes we can create object in instance method.

Allowed Modifiers/Keywords for Constructors

Allowed

1.public - unrestricted Access
2.protected - subclass(is-relationship(extends)+ same package access.
3.default(package-private) - only accessible within the same package.
4.private - only usable within the class,
not Allowed (use-case Singletons & factory methods)

Not Allowed

5.final - constructors are implicitly final
why constructor are not inherited or overridden
6.static - constructor are always instance-related(used to initialize objects). static keyword use for constructor useless, static is class specific .

  1. abstract - abstract class can not create it's object directly,if you have abstract method must to be implemented child class.that's why does not work with constructors. simply:- abstract means:
  2. No implementation (no body).
  3. Child classes must provide the logic. 8.Synchronized

Constructor Programme:

this() using constructor:

super() using construtor:-

package inheritence;

public class Vehicle {
int speed;


 Vehicle(int speed)
 {
     this.speed=speed;
     System.out.println("Vehicle constructor: speed set to "+speed);


    }

}

package inheritence;

public class Car extends Vehicle{
    String model;
    Car (int speed,String model)
    {
        super(speed);
        this.model=model;
        System.out.println("Car constructor: model set to " + model);
    }

    void display()
    {
        System.out.println("Car speed: " + speed + ", Model: " + model);
    }

    public static void main(String[] args) {

        Car c1 = new Car(100,"Honda");
        c1.display();
    }

}

output:-
Vehicle constructor: speed set to 100
Car constructor: model set to Honda
Car speed: 100, Model: Honda

this() Example Program


public class Student {

    int id; 
    String name;

    Student()
    {
        this(101,"Default");
        System.out.println("No-arg constructor");
    }
    Student(int id,String name)
    {
        this.id=id;
        this.name=name;

  System.out.println("Parameterized constructor");
    }

    void infoDisplay()
    {
        System.out.println(this.id + " " + this.name); 
    }

    public static void main(String[] args) {

        Student student = new Student();
        student.infoDisplay();
    }

}

Constructor vs Method

Image description

copy constructor:-

A copy constructor is a constructor that creates new object by copying another object of the same class.

java does not provide default copy constructor you can create manually.

why to use copy constructor?
To create a duplicate(copy) of exiting object with the same values (copy data from one object to another).

what is clone() method?

It is method in java built in object class
it creates a copy(duplicate) of the object.

Example:-

Myclass obj1 = new Myclass();
Myclass obj1 =  (Myclass) obj1.clone();

clone () is complex to use correctly and it needs to implements cloneable and can cause errors.
recommended is copy constructor.

Important:-

what is mutable and immutable in java?

Mutable:
can be changed after the object is created.
If you class contains:
mutable fields( like arrays.lists,String Builder)
copy constructor must create new copies of those fields. This is called a deep copy. it each object independent data.No shared references.

Immutable:-
can not be changed once the object is created.

If you class contains:
Immutable fields Like String,Integer,Double,Boolean..etc
safe to just copy reference , no need to clone. This is called a shallow copy.

Example:


public class Example_Mutable_Immutable {




    public static void main(String[] args)
    {
        String s1 ="Java";
        String s2=s1 ;
        s1=s1+ "Programming";
        System.out.println("Immutable");
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        StringBuilder sb1 = new StringBuilder("java");
        StringBuilder sb2= sb1;
        sb1.append("Programming");
        System.out.println("\nMutable:");
        System.out.println("sb1 = " + sb1);
        System.out.println("sb2 = " + sb2);

    }

}

Output:
Immutable
s1 = JavaProgramming
s2 = Java

Mutable:
sb1 = javaProgramming
sb2 = javaProgramming

shallow copy vs deep copy:-

Shallow copy(immutable fields ):-

  • copies references , not to objects
  • memory shares to referenced objects(original and copy point to the same object in memory).
  • if you change original ,copy is also affected.
  • performance faster (less memory allocation)
  • Implementation Default clone() method
  • used when field are immutable(like string,int)

Deep copy(mutable fields ):-

  • create new objects with copied values.
  • creates separate memory for all objects
  • Change in original would not affect the copy. -Best when fields are mutable like StringBuilder,ArrayList
  • performance slower(more memory allocation)
  • custom implementation needed.
class Book {
     StringBuilder title;

     //Normal constructor
     Book(StringBuilder title)
     {
         this.title=title;

     }
     //shallow copy constructor 
     Book(Book b)
     {
         this.title=b.title; //same reference
     }

     //Deep copy constructor
     Book(Book b,boolean deep)
     {
         this.title= new StringBuilder(b.title.toString());
     }
    void showTitle()
    {
        System.out.println("Title: "+title);
    }
    public static void main(String[] args) {
        StringBuilder originalTitle = new StringBuilder("Java Programming");

  //orginal object
        Book book1 = new Book(originalTitle);
        //shallow copy
        Book book2 =new Book(book1);
        //Deep copy 
        Book book3 = new Book(book1,true);


        // Modify the original title
        originalTitle.append(" - Beginner");

        System.out.println("After modifying the original title:\n");

        System.out.print("Book1: ");
        book1.showTitle();

        System.out.print("Book2 (Shallow Copy):  ");
        book2.showTitle(); // Will be affected (same reference)

        System.out.print("Book3 (Deep Copy):  ");
        book3.showTitle(); // Will not be affected




}
}

static and non static

By: Prasanth
20 May 2025 at 15:42

static and non static

static

  • static is class specific
  • static variable: only one copy of it exists, and all objects share that one copy.

  • static method: Can be called using the class name directly, doesn't need an object.

what can be static java?
1.varibles(fields)
class Student{
static String college = "Jaya College";
}

  1. static methods(class-level method)

used when:

  • you don't need to use object data(this)
  • you want to call it without creating an object.

`class Utility
{
static void printMessage()
{
System.out.println("hell from static method");

}
}

//calling using Utility.printMessage();
`
3.Static Blocks(Runs only once when class is loaded)
used to : initialize static variable


class Example
{
static int data;
static {
data =100;
System.out.println("Static block executed");
}
}

4.static Nested class

use when : you want a class inside another class without needing the outer class object.

`
class Outer {
static class Inner {
void show() {
System.out.println("Inside static nested class");
}
}
}

`
call using:

Outer.Inner obj = new Outer.Inner();
obj.show();

you cannot use static :

Local varibales (int x=5; inside a method) static
Constructor static
Classes (top-level) static ( unless they are nested inside another class)

Example

class car {
static int car =4;
}
// now whether you create 1 object or 100 , all cars shares the same number of weels 

//static = belongs to class, shared by all, only one copy.



public class MyClass2 {
      static int val =1;
    public static void main(String[] args) {


        MyClass2 obj1 = new  MyClass2();
        MyClass2 obj2  = new  MyClass2();

        obj1.val=10;
        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);


    }

}

output:
obj1 val:10
obj2 val:10
//

non static

  • non-static is instance specific
  • if a variable is non-static ,then every object has its own separate copy that mean Non-static members belong to the object, it gets own copy of non static variables and can use non-static method.
Example: 1

public class MyClass {
    int val =1;

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();

        obj1.val=10; // change  value for obj1

        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);

    // non-static = belongs to object, each object has its own value.   



    }

}

output:
obj1 val:10
obj2 val:1

  1. non-static variables (instance variable)

use when: Each object should have it own values.

example 2:

class Student 
String name;
int id;

Student (String name ,int id)

{
this.name =name;
this.id = id;

}


void display()
{
System.out.println(name +"  "+id);
}




public  class Test {

public static void main(String[] args)
{
Student s1 = new Student("John", 1);
Student s2 = new Student("Emma", 2);
s1.display(); //John
s2.display(); //Emma
}

}

  1. Non-static Method (Instance Method) used when you want to work with object data like name,id you need use this keyword
class Car {
    String brand;

    void showBrand() {  // non-static method
        System.out.println("Brand: " + brand);
    }
}

//you must to create object to call it:

public class Test {
public static void main(String[] args)
{
Car c = new Car();
c.brand="Tata";
c.showBrand();
}
}

  • you can not use non-static members inside static methods directly.
class Example {
    int x = 10;  // non-static

    static void show() {
        // System.out.println(x); // Error
    }
}

//To access x, you must create an object:
static  void show {
Example e shwo = new Example();
System.out.println(e.x);
}

Image description

Image description

What does β€œbelong to class” mean?

  • It means the variable or method is shared by all objects of that class.
  • You don’t need to create an object to access it.
  • Use the static keyword.

What does β€œbelong to object” mean?

  • It means each object has its own copy of that variable or method.
  • You need to create an object to use it.
  • Do not use static keyword.

why can not use to static in class(top-level)?

because not belong to any another class, only for static variable ,block,methods ,inner class

now see top level-class valid and invalid modifiers for class

Valid Modifiers for Top-Level Classes:

1.public -> class is accessible from anywhere
2.default -> no keyword=package-private, used only within the same package.
3.abstract -> class cannot-be instantiated(can not create object) ,must be inherited(extend) and If the subclass does NOT implement all abstract methods,
then the subclass must also be declared abstract. Abstract class can have normal methods too.
// we will detail info of abstraction concept

Why can't we create an object of an abstract class?

Abstract class is incomplete- it might have abstract methods(with out body). you must create a subclass that completes those methods. so that's why doesn't allow you to create object directly.

Why abstract class cannot achieve 100% abstraction?
Because:

  • An abstract class can contain concrete methods (with body).
  • So, not everything is hidden from the user.
  • That’s why it cannot achieve 100% abstraction. You can say: Abstract class = Partial abstraction

Why interface can achieve 100% abstraction?

Because:

  • All methods in an interface are abstract by default (before Java 8).
  • You cannot write method body (in older versions).
  • It only contains method declarations, no implementations. So, the user only sees "what to do", not "how".
Animal a = new Animal();  // Error: Cannot instantiate abstract class
Animal a = new Dog();  //  Allowed: Dog is a subclass of Animal/

4.final -> class cannot be extended( no sub classing) like not is-relationship or prevent inheritance

Invalid Modifiers for Top-Level Classes:

1.private -> No class can see it in the world, so it's useless.
2.protected -> used for members only (variable and methods), not for top-level class
3.static -> Only for inner class, not outer class.

how and where static, instance, and local variables and methods are called, accessed, and hold values.

class Variable {

int instancevar=10;
static int staticVar =20;

    public static void main(String[] args) {
//local variable must be initialized        
    int localVar=30;
    System.out.println("Local variable"+localVar);
    System.out.println("Static Varibale:"+staticVar);
    //accessing instace variable -> directely not allowed 
    //System.out.println("Instace variable:"+obj1.instancevar);

    Variable obj1= new Variable();
    System.out.println("Instace variable:"+obj1.instancevar);
    obj1.instanceMethod();




}
 static void staticMethod()
    {
        System.out.println("inside static method");
        System.out.println("Static Varibale:"+staticVar);
        Variable obj1= new Variable();

        System.out.println("Instace variable:"+obj1.instancevar);
    }
 void instanceMethod()
    {
        System.out.println("inside instace method");

        staticMethod();
        System.out.println("Static Varibale:"+staticVar);
        System.out.println("Instace variable:"+instancevar);

    }
}

Note:-

  • Static Method: Can only access static members directly.
    • To access instance members, create an object.
  • Instance Method: Can access both static and instance members directly.
  • Local Variables: Only exist inside the method, and must be initialized.

Java -> class & object

By: Prasanth
19 May 2025 at 13:40

what is a Class in java?

  • A class in java is a blueprint/template/design ,it used to create objects.
  • It defines data(variable) and behaviors(method) that object can have.An object has its own copy of those variables, and it can run the methods.

  • No memory is allocated when a class is defined.

  • only memory allocated object create at runtime program execution.Written using class keyword.

  • Class is Logical Entity,it means

    • A logical entity is checked by the compiler when we write code ,like just writing structure or blue print of the program. this structure is called logical entity.
    • Only the compiler checks it
    • it does not take any memory until we create an object. class is idea/design/plan

example

class car{

String color; // declared , but no value stored yet
}

object

Car mycar =new Car();
mycar.color = "red"; // Real instance (holds real values and uses memory at runtime)

Just think car:-

  • What it has Variables (data) ->color,brand,speed
  • What it does Methods (behaviors) -> drive,stop,honk.
  • Object is the real thing created using the class.

  • It does not occupy memory  like object do , it just defines structure(variable + methods) but the actual values are not created or stored in memory until you make an object.
    
  • A class is compile-time entity .it means compiler sees and checks before the program runs like check syntax correct or not and variable type and method signature correct or not ,data type matching and rules of java followed .

  • class it the core concept of object-oriented programming(oops) in java.

example

public class Car
{
    // Data members (fields)- hold  the actual value

String brand;
int speed;
    // Behavior (method)
void drive()

{
System.out.println("driving a car");
}


}
//But it’s not a real car yet. It’s just the plan.

Class Name Rules:

  • 1.Must start with a Uppercase first letter or (_) underscore Or dollar sign ($).
  • 2.can not start with a number
  • 3.can not contain spaces or special characters
  • 4.use Pascal-case for naming

example

class EmployeeDetails

Access Modifier in class

  • Class is public accessible form anywhere,it default( not modifier) accessible only within the same package ( class have final,abstract) , class can not to use protected and private access modifier but inner class you can use all access modified we can see example.

example 1 : inner class

public class OuterClass {

    private class InnerPrivate
    {
        void show()
        {
            System.out.println("private inner class");
        }
    }

protected class InnerProtected
    {
        void show()
        {
            System.out.println("protected inner class");
        }
    }

class InnerDefault
{
    void show()
    {
        System.out.println("Default inner class");
    }
}


public class InnerPublic
{
    void show()
    {
        System.out.println("public  inner class");
    }
}


}
// we can see later inner-private class member how to access outer class.(Accessing Private Inner Class Inside Outer Class)

Top-Level Class

    Can use only:

-  public
-     default (no modifier)
-     Cannot use private or protected

Inner Class (class inside another class)

  Yes, inner classes can be:
-         private
-         protected
-         public
-         default

Because inner classes are members of the outer class (just like variables), they can have any access modifier.

example 2 : private in outer class

private  class PrivateClass
{
    public static void main(String[] args) {
    {
        System.out.println("private outer class ");
        //top-level classes (outer classes) cannot be private. Only inner classes can be private.

//modifier  private not allowed here, outer class is private, no other class can access it, even same package.it is useless that's why java does not allow  private outer class. 
    }
    }
}


// Simple term:-

private means: only accessible inside the same class
β†’ But if the class is private, no other class can use it, which defeats the purpose of defining it.

example 3 :- protected in outer class

protected class ProtectedClass {

    public static void main(String[] args) {

        System.out.println(" protected  outer class ");



    }

}
//protected is only useful for

- same package access
- subclass access  and even in another package,but top-level class can not be inherited if it is  protected in  another package.
- So, Java does not allow protected for top-level classes either.

why protected top-level class is not allowed?

*protected is for members and inner classes only
*top-level class need to be accessible by compiler
*subclass from another package can not even access it.

simple say:-

protected means: accessible to subclasses and same package
β†’ But you can't inherit or access a class that’s protected from another package, so Java does not allow it.

what a class can contain

  • *variable, methods ,constructors,blocks,inner classes,interface
  • *Only One Public Class Only one public class per .java file

File name rule

  • if the class is public , the file name must match the class name.
  • if the class is default( no access modifer) the file name does not match the class name.

correct
`// File: Car.java
public class Car { }

Incorrect
// File: Vehicle.java
public class Car { } // Error!
`

what is object ?

  • object is an instance of a class. It means example of the class.object created from the class that Uses the variables and methods of the class & Holds actual values in its variables.Memory is allocated when object is created.

  • A object is created runtime(while the program runs) is called runtime entity.Is created using the new keyword,Take memory and holds data(variable) and behavior(methods) from the class.

  • object is runtime entity ,real instance that uses class features.

  • object also called physical entity,it means
    *object created in memory when program runs(runtime)and allocated memory runtime,
    It holds real values (variable) and performs actions (methods).
    *data hold the real values and action can call methods.

  • multiple object can be created from class and each have different value.

  • Each object has its own copy of instance variables

    ` Car car1 = new Car();
    Car car2 = new Car();

    car1.color = "Red";
    car2.color = "Blue";
    

    `
    Objects can use the functions (methods) that are defined inside their class

class Car {
    void drive() {
        System.out.println("The car is driving.");
    }
}

public class Test {
    public static void main(String[] args) {
        Car myCar = new Car();   // object created
        myCar.drive();           // object calling the method
    }
}

Car myCar = new Car();

Car = class
myCar = reference variable
new Car(); = create a new object in memory.

Runtime -> mean when the program is actually running.
Enitity -> means something that exists

=> A runtime entity is something that is created and exists only while the program is running.

class & object

A class is a blueprint of an object. It defines variables and methods. The object uses those variables and methods, and holds actual values. For example, a car is a class may have variables like brand, color, and type, and methods like drive, stop,etc.

Example

public class Car {
    //Data = variables β†’ what the object has.
    String color;
    String brand;

       //Behavior = methods β†’ what the object does.
    void  drive()
    {
        System.out.println("The " + color + " " + brand + " is driving.");
    }
    void stop() {
        System.out.println("The car has stopped.");
    }


    public static void main(String[] args) {
        Car mycar = new Car ();
        mycar.color="Red";
        mycar.brand="Honda";
        mycar.drive();
        mycar.stop();

    }

}

runtime and compile time

syntax check - compile time
object-creation ,method execution ,value holding( in memory) -runtime

variable

  • variables is used to store data values like number,text,etc.access variable when needed,you can change the values until you set final. (or)

A variable is a container(name) used to store data values in memory. like label for a memory location that hold some values.

variables called fields, instance variables ,data members ,properties ,Attributes

syntax
datatype variablename = value;

example

int age = 25;           // declaring and initializing variable
String name = "Prasanth";
System.out.println(age); // using variable

Types of variables in java

  1. Local Variable Declared inside a method or block.Accessible only within that block

memory location : stack
Access: inside method only
Example: int sum =10;

2.Instance variable
Declared inside a class but outside methods, belongs to objects.
memory location : Heap
Example: obj.name

3.Static variable
Declared using static keyword.Belongs to class,not instance
memory location : method area
Example: class name.count or obj.count

// we will next blog heap,stack.

Important
*only static and instance variables get default values when you printing those variables not local variables ,you must initialize it, or you will get a compilation error.

public class car {

static String company ="honda"; // static varibale
string model; // instance variable

void setModel(String modelName)
{
String prefix ="Model: "; // local variable 
model= prefix + modelName;
}

}

// static is class specific
// non-static(instance) object specific 

Method-Used to Perform Actions (Behavior/Logic)

  • Define logic or instructions inside a method
  • Call the method to execute that logic
  • Pass values (arguments) to it

example

void greet() {
    System.out.println("Hello, Java!");
}

greet();  // calling the method

class vs object

Image description

Image description

Code Less, Prompt Better: Unlocking Python's Built-in LLM Enhancers

By: angu10
16 May 2025 at 22:07

In the rapidly evolving landscape of Large Language Models (LLMs), effective prompt engineering has become a crucial skill. While much attention is given to the art of crafting effective prompts, less focus has been placed on how to efficiently manage these prompts programmatically. Python, with its rich set of built-in features, offers powerful tools to dynamically construct, optimize, and manage LLM prompts.
This article explores how Python's built-in features can transform your approach to LLM prompt engineering, making your code more efficient, maintainable, and powerful.

1. Using locals() for Dynamic Context Injection

The Problem
When working with LLMs, we often need to inject contextual information into our prompts. The traditional approach involves manual string formatting:

def generate_response(user_name, user_query, previous_context):
    prompt = f"""
    User name: {user_name}
    User query: {user_query}
    Previous context: {previous_context}

    Please respond to the user's query considering the context above.
    """

    return call_llm_api(prompt)

This works well for simple cases, but becomes unwieldy as the number of variables increases. It's also error-prone – you might forget to include a variable or update a variable name.

The Solution with locals()
Python's locals() function returns a dictionary containing all local variables in the current scope. We can leverage this to automatically include all relevant context:

def generate_response(user_name, user_query, previous_context, user_preferences=None, user_history=None):
    # All local variables are now accessible
    context_dict = locals()

    # Build a dynamic prompt section with all available context
    context_sections = []
    for key, value in context_dict.items():
        if value is not None:  # Only include non-None values
            context_sections.append(f"{key}: {value}")

    context_text = "\n".join(context_sections)

    prompt = f"""
    Context information:
    {context_text}

    Please respond to the user's query considering the context above.
    """

    return call_llm_api(prompt)

Benefits:

Automatic variable inclusion: If you add a new parameter to your function, it's automatically included in the context.
Reduced errors: No need to manually update string formatting when variables change.
Cleaner code: Separates the mechanism of context injection from the specific variables.

2. Using inspect for Function Documentation

The Problem
When creating LLM prompts that involve function execution or code generation, providing accurate function documentation is crucial:

def create_function_prompt(func_name, params):
    prompt = f"""
    Create a Python function named '{func_name}' with the following parameters:
    {params}
    """
    return prompt

This approach requires manually specifying function details, which can be tedious and error-prone.

The Solution with inspect
Python's inspect module allows us to extract rich metadata from functions:

import inspect

def create_function_prompt(func_reference):
    # Get the function signature
    signature = inspect.signature(func_reference)

    # Get the function docstring
    doc = inspect.getdoc(func_reference) or "No documentation available"

    # Get source code if available
    try:
        source = inspect.getsource(func_reference)
    except:
        source = "Source code not available"

    prompt = f"""
    Function name: {func_reference.__name__}

    Signature: {signature}

    Documentation:
    {doc}

    Original source code:
    {source}

    Please create an improved version of this function.
    """

    return prompt

# Example usage
def example_func(a, b=10):
    """This function adds two numbers together."""
    return a + b

improved_function_prompt = create_function_prompt(example_func)
# Send to LLM for improvement

This dynamically extracts all relevant information about the function, making the prompt much more informative.

3. Context Management with Class Attributes

The Problem
Managing conversation history and context with LLMs often leads to repetitive code:

conversation_history = []

def chat_with_llm(user_input):
    # Manually build the prompt with history
    prompt = "Previous conversation:\n"
    for entry in conversation_history:
        prompt += f"{entry['role']}: {entry['content']}\n"

    prompt += f"User: {user_input}\n"
    prompt += "Assistant: "

    response = call_llm_api(prompt)

    # Update history
    conversation_history.append({"role": "User", "content": user_input})
    conversation_history.append({"role": "Assistant", "content": response})

    return response

The Solution with Class Attributes and dict
We can create a conversation manager class that uses Python's object attributes:

class ConversationManager:
    def __init__(self, system_prompt=None, max_history=10):
        self.history = []
        self.system_prompt = system_prompt
        self.max_history = max_history
        self.user_info = {}
        self.conversation_attributes = {
            "tone": "helpful",
            "style": "concise",
            "knowledge_level": "expert"
        }

    def add_user_info(self, **kwargs):
        """Add user-specific information to the conversation context."""
        self.user_info.update(kwargs)

    def set_attribute(self, key, value):
        """Set a conversation attribute."""
        self.conversation_attributes[key] = value

    def build_prompt(self, user_input):
        """Build a complete prompt using object attributes."""
        prompt_parts = []

        # Add system prompt if available
        if self.system_prompt:
            prompt_parts.append(f"System: {self.system_prompt}")

        # Add conversation attributes
        prompt_parts.append("Conversation attributes:")
        for key, value in self.conversation_attributes.items():
            prompt_parts.append(f"- {key}: {value}")

        # Add user info if available
        if self.user_info:
            prompt_parts.append("\nUser information:")
            for key, value in self.user_info.items():
                prompt_parts.append(f"- {key}: {value}")

        # Add conversation history
        if self.history:
            prompt_parts.append("\nConversation history:")
            for entry in self.history[-self.max_history:]:
                prompt_parts.append(f"{entry['role']}: {entry['content']}")

        # Add current user input
        prompt_parts.append(f"\nUser: {user_input}")
        prompt_parts.append("Assistant:")

        return "\n".join(prompt_parts)

    def chat(self, user_input):
        """Process a user message and get response from LLM."""
        prompt = self.build_prompt(user_input)

        response = call_llm_api(prompt)

        # Update history
        self.history.append({"role": "User", "content": user_input})
        self.history.append({"role": "Assistant", "content": response})

        return response

    def get_state_as_dict(self):
        """Return a dictionary of the conversation state using __dict__."""
        return self.__dict__

    def save_state(self, filename):
        """Save the conversation state to a file."""
        import json
        with open(filename, 'w') as f:
            json.dump(self.get_state_as_dict(), f)

    def load_state(self, filename):
        """Load the conversation state from a file."""
        import json
        with open(filename, 'r') as f:
            state = json.load(f)
            self.__dict__.update(state)```



Using this approach:

# Create a conversation manager
convo = ConversationManager(system_prompt="You are a helpful assistant.")

# Add user information
convo.add_user_info(name="John", expertise="beginner", interests=["Python", "AI"])

# Set conversation attributes
convo.set_attribute("tone", "friendly")

# Chat with the LLM
response = convo.chat("Can you help me understand how Python dictionaries work?")
print(response)

# Later, save the conversation state
convo.save_state("conversation_backup.json")

# And load it back
new_convo = ConversationManager()
new_convo.load_state("conversation_backup.json")

4. Using dir() for Object Exploration

The Problem
When working with complex objects or APIs, it can be challenging to know what data is available to include in prompts:



def generate_data_analysis_prompt(dataset):
    # Manually specifying what we think is available
    prompt = f"""
    Dataset name: {dataset.name}
    Number of rows: {len(dataset)}

    Please analyze this dataset.
    """
    return prompt

The Solution with dir()
Python's dir() function lets us dynamically discover object attributes and methods:


def generate_data_analysis_prompt(dataset):
    # Discover available attributes
    attributes = dir(dataset)

    # Filter out private attributes (those starting with _)
    public_attrs = [attr for attr in attributes if not attr.startswith('_')]

    # Build metadata section
    metadata = []
    for attr in public_attrs:
        try:
            value = getattr(dataset, attr)
            # Only include non-method attributes with simple values
            if not callable(value) and not hasattr(value, '__dict__'):
                metadata.append(f"{attr}: {value}")
        except:
            pass  # Skip attributes that can't be accessed

    metadata_text = "\n".join(metadata)

    prompt = f"""
    Dataset metadata:
    {metadata_text}

    Please analyze this dataset based on the metadata above.
    """

    return prompt


This approach automatically discovers and includes relevant metadata without requiring us to know the exact structure of the dataset object in advance.

5. String Manipulation for Prompt Cleaning

The Problem
User inputs and other text data often contain formatting issues that can affect LLM performance:



def process_document(document_text):
    prompt = f"""
    Document:
    {document_text}

    Please summarize the key points from this document.
    """
    return call_llm_api(prompt)


The Solution with String Methods
Python's rich set of string manipulation methods can clean and normalize text:



def process_document(document_text):
    # Remove excessive whitespace
    cleaned_text = ' '.join(document_text.split())

    # Normalize line breaks
    cleaned_text = cleaned_text.replace('\r\n', '\n').replace('\r', '\n')

    # Limit length (many LLMs have token limits)
    max_chars = 5000
    if len(cleaned_text) > max_chars:
        cleaned_text = cleaned_text[:max_chars] + "... [truncated]"

    # Replace problematic characters
    for char, replacement in [('\u2018', "'"), ('\u2019', "'"), ('\u201c', '"'), ('\u201d', '"')]:
        cleaned_text = cleaned_text.replace(char, replacement)

    prompt = f"""
    Document:
    {cleaned_text}

    Please summarize the key points from this document.
    """

    return call_llm_api(prompt)


Conclusion

Python's built-in features offer powerful capabilities for enhancing LLM prompts:

Dynamic Context: Using locals() and dict to automatically include relevant variables
Introspection: Using inspect and dir() to extract rich metadata from objects and functions
String Manipulation: Using Python's string methods to clean and normalize text

By leveraging these built-in features, you can create more robust, maintainable, and dynamic LLM interactions. The techniques in this article can help you move beyond static prompt templates to create truly adaptive and context-aware LLM applications.
Most importantly, these approaches scale well as your LLM applications become more complex, allowing you to maintain clean, readable code while supporting sophisticated prompt engineering techniques.
Whether you're building a simple chatbot or a complex AI assistant, Python's built-in features can help you create more effective LLM interactions with less code and fewer errors.

Before yesterdayMain stream

TASK 1: Python – Print exercises

20 April 2025 at 02:26

1.How do you print the string β€œHello, world!” to the screen?
Ans: Using sep and end Parameters is preferred way.
Image description

2.How do you print the value of a variable name which is set to β€œSyed Jafer” or Your name?
Ans: Note the Variable is case sensitive

Image description

3.How do you print the variables name, age, and city with labels β€œName:”, β€œAge:”, and β€œCity:”?
Ans: Using keyword sep="," brings in , between the Variable Name and Value itself, so avoid

Image description

4.How do you use an f-string to print name, age, and city in the format β€œName: …, Age: …, City: …”?
Ans: To insert variables directly into the string used f-string
Also, you can assign values to multiple variables in a single line as seen in 1st line

Image description

5.How do you concatenate and print the strings greeting (β€œHello”) and target (β€œworld”) with a space between them?
Ans: + is used to concat the items

Image description

6.How do you print three lines of text with the strings β€œLine1”, β€œLine2”, and β€œLine3” on separate lines?****

Image description

7.How do you print the string He said, "Hello, world!" including the double quotes?
Ans: To print quotes inside a string, you can use either single or double quotes to enclose the string and the other type of quotes inside it.

Image description

8.How do you print the string C:\Users\Name without escaping the backslashes?
Ans: you can also use a literal backslash "\" when using Concat or Try with 'r' to treat backslashes as literal characters

Image description

9.How do you print the result of the expression 5 + 3?

Image description

10.How do you print the strings β€œHello” and β€œworld” separated by a hyphen -?

Image description

11.How do you print the string β€œHello” followed by a space, and then print β€œworld!” on the same line?

Image description

12.How do you print the value of a boolean variable is_active which is set to True?

Image description

13.How do you print the string β€œHello ” three times in a row?

Image description

14.How do you print the sentence The temperature is 22.5 degrees Celsius. using the variable temperature?

Image description

15.How do you print name, age, and city using the .format() method in the format β€œName: …, Age: …, City: …”?

Image description

16.How do you print the value of pi (3.14159) rounded to two decimal places in the format The value of pi is approximately 3.14?
Ans: pi is the variable & .2f formats it as a floating-point number with 2 digits after the decimal

Image description

17.How do you print the words β€œleft” and β€œright” with β€œleft” left-aligned and β€œright” right-aligned within a width of 10 characters each?

Image description

Place button on wiki Page.

10 January 2025 at 14:14

I got a task, that to add a cody in wiktionary side. For do this we have knowledge of Wiki Gadget.

Create an Account on wiki page:

  • If we want to change in wiki page. First we want to create account in wiki.
  • Then we create a own javascript page for make change.
  • The changes can be seen in our page only.
  • If we want to change globally, i have a knowledge of Gadget_kitchen in wiki.

Find the place that have to change

  • Go to wiktionary site and seach any word it.
  • open F12 to view inspect and find the place heading usi.
  • I found in
    • body -> div(mw-page-container) -> div(mw-page-container-inner) -> div(mw-content-container) ->main -> header.
    • header contains nav, h1, div(title-shortlink-container), div(vector-dropdown.
    • h1 must be copy and button place near to h1 or div(title-shortlink-container).

Create common.js page and paste the code

Code:
const observer = new MutationObserver(() => {
    const heading = document.querySelector(".title-shortlink-container");
    if (heading) {
        // Create the button element
        const button = document.createElement("button");
        button.textContent = "Copy Text";
        button.style.marginLeft = "10px"; // Add some spacing from the container

        // Insert the button next to the .title-shortlink-container
        heading.insertAdjacentElement("afterend", button);

        // Add an event listener to copy the text
        button.addEventListener("click", () => {
            const textToCopy = heading.textContent.trim(); // Get only the container's text
            navigator.clipboard.writeText(textToCopy).then(() => {
                alert("Text copied: " + textToCopy);
            }).catch(err => {
                console.error("Failed to copy text: ", err);
            });
        });

        observer.disconnect(); // Stop observing once the element is found
    }
});

// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });

Code Explanation :

  1. Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
  2. If the Heading is not null. Then we create the button and styles.
  3. The Button is placed next to link. Use heading.insertAdjacentElement(β€œafterend”, button);
  4. Button action create a function in addEventListener.
  5. Get the link by heading.textContent and store in textToCopy
  6. For copy the text use navigator.clipboard.writeText(textToCopy)
  7. Then pop alert for the event.
  8. if error catch throw error message.
Problem faced (dynamically loaded content)
  1. First i use DOMContentLoaded. It cannot work in wiki.
  2. Then i use Polling (Setintervel for a Certain time). It works partcially.
  3. Then i use MutationObserver. I works perfectly to all pages.

Reference:

https://ta.wikipedia.org/wiki/Special:MyPage/common.js

https://stackoverflow.com/questions/24344022/how-to-use-mutationobserver

https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript

Place button on wiki Page.

I got a task, that to add a cody in wiktionary side. For do this we have knowledge of Wiki Gadget.

Create an Account on wiki page:

  • If we want to change in wiki page. First we want to create account in wiki.
  • Then we create a own javascript page for make change.
  • The changes can be seen in our page only.
  • If we want to change globally, i have a knowledge of Gadget_kitchen in wiki.

Find the place that have to change

  • Go to wiktionary site and seach any word it.
  • open F12 to view inspect and find the place heading usi.
  • I found in
    • body -> div(mw-page-container) -> div(mw-page-container-inner) -> div(mw-content-container) ->main -> header.
    • header contains nav, h1, div(title-shortlink-container), div(vector-dropdown.
    • h1 must be copy and button place near to h1 or div(title-shortlink-container).

Create common.js page and paste the code

Code:
const observer = new MutationObserver(() => {
    const heading = document.querySelector(".title-shortlink-container");
    if (heading) {
        // Create the button element
        const button = document.createElement("button");
        button.textContent = "Copy Text";
        button.style.marginLeft = "10px"; // Add some spacing from the container

        // Insert the button next to the .title-shortlink-container
        heading.insertAdjacentElement("afterend", button);

        // Add an event listener to copy the text
        button.addEventListener("click", () => {
            const textToCopy = heading.textContent.trim(); // Get only the container's text
            navigator.clipboard.writeText(textToCopy).then(() => {
                alert("Text copied: " + textToCopy);
            }).catch(err => {
                console.error("Failed to copy text: ", err);
            });
        });

        observer.disconnect(); // Stop observing once the element is found
    }
});

// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });

Code Explanation :

  1. Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
  2. If the Heading is not null. Then we create the button and styles.
  3. The Button is placed next to link. Use heading.insertAdjacentElement(β€œafterend”, button);
  4. Button action create a function in addEventListener.
  5. Get the link by heading.textContent and store in textToCopy
  6. For copy the text use navigator.clipboard.writeText(textToCopy)
  7. Then pop alert for the event.
  8. if error catch throw error message.
Problem faced (dynamically loaded content)
  1. First i use DOMContentLoaded. It cannot work in wiki.
  2. Then i use Polling (Setintervel for a Certain time). It works partcially.
  3. Then i use MutationObserver. I works perfectly to all pages.

Reference:

https://ta.wikipedia.org/wiki/Special:MyPage/common.js

https://stackoverflow.com/questions/24344022/how-to-use-mutationobserver

https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript

Linux Introduction-II

By: Prasanth
26 March 2025 at 16:45

Table of Contents:

1.Linux Architecture
2.Linux vs unix
3.Linux Distro
4.Booting Process

1.Linux Architecture

Image description

1. Hardware Layer


*The hardware layer is base of the Linux
architecture, it contain all the physical parts of a computer for example CPU , Ram , Storage, i/o device. The linux kernel communicates withe hardware using device drivers to control the physical parts.

2. Kernel Layer


*Linux kernel is a core part of the operating system
It acts as a bridge between hardware and software. It directly interacts with the hardware and manages system resources like CPU, memory, and devices.
*users give commands to the shell and the shell processes these commands the by interacting with the kernel .
example, if you runs ls, the kernel requests the file system to get file information from the hard disk.
Types

  1. Monolithic kernel
  2. Micro kernel
  3. Hybrid kernle.

3. Shell Layer

* shell in linux is a command line interface that allow to user interact withe operating system . It Acts as bridge b/w the user and kernel
Type:

1.Bash - default shell used to linux globally
2.Zsh(Z shell) - extended version of Bash shell like auto suggestion
3.fish(fish shell - it provides auto suggestion and web based config.
4.c shell - work like c programming ,mainly used developers

for real case work example

$cat /etc/shells - show only you installed shells
$echo #SHELL -show current shell
$chsh -s /bin/youinstalledshellname

4. User Applications Layer


include all programs and utilites(small programme or tool that help user perform specfic task like ls,cp,ping,top,ps)

2.Linux vs unix

Origin:-
Linux -Created by Linus Torvalds (1991)

Unix -Developed by AT&T Bell Labs (1970s)
License:-
Linux - Open-source & free (GPL)

Unix - Mostly proprietary (licensed)& paid

Usage:-
Linux -Used in PCs, servers, mobile (Android)
Unix - Used in enterprises, mainframes(big companies (like banks, telecoms, government)

Shell Support:-
Linux - Bash, Zsh, Fish, etc.
Unix - Bourne Shell, C Shell, Korn Shell

File System:-
Linux - ext4, XFS, Btrfs... etc

Unix - UFS, JFS, ZFS .... etc

Hardware Support:-
Linux - Runs on all devices (PCs, ARM, etc.)
ARM is type of process used in mobile,tablet,computer.
Unix - Runs on specific hardware (IBM, HP)

Strong security, frequent updates
Linux - gets regular update and fix the security issues and performance
Unix - very secure and less updates

Performance:-
Linux - high performece and flexible(code-chage and install different software and use may device)
Unix - less flexible and run on specific hardware

Examples:-
Linux - ubuntu ,Red hat,fedora,arch
Unix - AIX,HP-UX,solaris,macos

*3.Linux Distro
*

  1. Ubuntu - ubuntu.com
  2. Debian - debian.org
  3. Fedora - getfedora.org
  4. Arch Linux - archlinux.org
  5. Linux Mint - linuxmint.com
  6. openSUSE - opensuse.org
  7. Manjaro - manjaro.org
  8. Kali Linux - kali.org
  9. CentOS - centos.org
  10. Rocky Linux - rockylinux.org

4.Booting Process

i. BIOS/UEFI (Basic input/output system):-

Bios is firmware(means something does not change) store on a non-volatile memory chip on the motherboard that initialize and tests hardware components when a computer is powered on. It also loads the operating system. firmware it stored in a type of rom (read only memory) called firmware ,simply say firmware is written on to the Rom (Read only memory) during manfacturing ,it cannot be alteret,updated or erased later, permantely fixed in the memory.Now current environment used EEPROM(Electrically Erasable Programmable Read -only memory) or flash memory.

Functions of BIOS:

1.POST (Power-On Self-Test) – Checks if hardware components (CPU, RAM, storage,hardware ...etc) are working correctly.if any problem occurred (for example hdd not connect propery in motherboard,ram dust and not detect) show like beeps or error code.

2.Bootstapping (boot process) -find and load the os from storage into ram.

3.Harwae initalization - configure and initialize system hardware before os take the control.

4.Bios setup utility - allows users to configure system settings (boot order,secure boot ,bios password set)

5.basic i/o operations - acts as an interface b/w the os and hardware.

Types of Bios:-

*Legacy Bios _ older system used , it support only MBR partitioning and 16 bit interface( 16 bit processor) not support to GPT, user interface text-based ,keyboard-only, storage support 2.2 TB and 4 primary partition ,basic password protection and slower boot time.
UEFI - (Unified Extensible Firmware Interface)
*Now modern system used UEFi , user interface support graphical and keyboard ,mouse. operating system used 32 64 bit processor , storage support 18 exabyte and 128 partition. security boot ,advanced security feature, faster boot time.

  • search the bootloader in the MBR if bios otherwise UEFI means GPT. bios passes the control bootloader.

ii. Bootloader (GRUB, LILO, etc.)

  • MBR is responsible for loading and executing the grub boot loader ,let we discuss depth , GRUb(GRand Unified Bootloader) is bootloader used in Linux sysem to load the operating system into primary memory RAM when computer starts. it is the first software that after runs firmware(BIOS/UEFi) complete the hardware initialization.

stage 1:(MBR/EFI Execution)
BIOS/UEFI load the first stage o GRUp the MBR if

BIos (or) EFI system partion for UEFI.
MBR fist stage 512 bytes in the boot disk

stage 2:(Loading Kernel & initrd)

GRUB Loads the kernel (vmlinuz) into ram .
vmlinuz = "Virtual Memory LINUx gZip-compressed"
*It is the compressed Linux kernel used for booting the system and also GRUB load the initrd(initial ram disk ) or initramfs(initial Ram Filesystem),which contains essential drivers and tools,
initrd(old)/initramfs(modern) temporary root filesystem load into ram by the bootloader like grub, before then mount root filesystem (mount attach(connect) ,umount detach(disconnect),initramfs not need to mounted like initrd,load the directely in the ram.

*The main GRUB menu is displayed here,
You can select the operating system or kernel version,
If you no selected , it will boot the default OS automatically.
Passes control to the kernel.ck3(custom file)

Kernel Initialization

  • The kernel starts execution and mount the root file system read only mode , it runs systemd/init process , start the essential sevices, you can check the Linux os first prosses(pid) is systemd using top command.

    • systemd is system manager it manage sytem services and control the run levels and so on.

*kernel manage the system resource(cpu,memory,device) and hardware components.

System Initialization (systemd/init)

*Systemd starts all required services and daemons (e.g., networking, logging).
*The kernel starts the init system (older Linux) or systemd (modern Linux).
*Systemd is the first process (PID 1) that manages system services.

  • It manages runlevels (SysVinit(older)) or targets (systemd) to start necessary services: 1.Networking 2.Filesystem mounting 3.Daemons (background services) 4.Login services

Runlevel/Target Execution

OldRunlevesl(SYsVinit)

runlevel
0 shutdown
1 singel user mode (resuce mode)
2 multi user mode (no networking)
3 multi user mode (with networking,CLI)
4 unused/custom mode
5 multi user mode with gui
6 reboot

example :
bash
$ runlevel
$ init 0

New Targets (systemd)

poweroff.target => Equivalent to Runlevel 0 (Shutdown)
rescue.target => Equivalent to Runlevel 1 (Single-user mode)
multi-user.target => Equivalent to Runlevel 2 & 3 (CLI, Networking)
graphical.target => Equivalent to Runlevel 5 (GUI mode)
reboot.target => Equivalent to Runlevel 6 (Reboot)

example :
bash
$ systemctl get-default (check runlevel)
$ systemctl isolate poweroff.target
$ systemctl set-default reboot.target
(isolate -temporary)
(set-default - permanent )

*Login Prompt (getty)
*

Displays a CLI login (TTY) or a Graphical Login (GDM/KDM).Allows the user to log in and access the system.
example:
$who
TTY column
tty1 - local terminal
pts/0 - remote ssh sessions1
pts/1 -remote ssh sessions2

Reference
https://medium.com/%40gangulysutapa96/6-stages-of-linux-boot-process-5ee84265d8a0
https://www.thegeekstuff.com/2011/02/linux-boot-process/
https://www.freecodecamp.org/news/the-linux-booting-process-6-steps-described-in-detail/
https://www.geeksforgeeks.org/linux-vs-unix/
https://www.linuxjournal.com/content/unix-vs-linux-what-is-the-difference
https://www.diffen.com/difference/Linux_vs_Unix

Learning Notes #77 – Smoke Testing with K6

16 February 2025 at 07:12

In this blog, i jot down notes on what is smoke test, how it got its name, and how to approach the same in k6.

The term smoke testing originates from hardware testing, where engineers would power on a circuit or device and check if smoke appeared.

If smoke was detected, it indicated a fundamental issue, and further testing was halted. This concept was later adapted to software engineering.

What is Smoke Testing?

Smoke testing is a subset of test cases executed to verify that the major functionalities of an application work as expected. If a smoke test fails, the build is rejected, preventing further testing of a potentially unstable application. This test helps catch major defects early, saving time and effort.

Key Characteristics

  • Ensures that the application is not broken in major areas.
  • Runs quickly and is not exhaustive.
  • Usually automated as part of a CI/CD pipeline.

Writing a Basic Smoke Test with K6

A basic smoke test using K6 typically checks API endpoints for HTTP 200 responses and acceptable response times.

import http from 'k6/http';
import { check } from 'k6';

export let options = {
    vus: 1, // 1 virtual user
    iterations: 5, // Runs the test 5 times
};

export default function () {
    let res = http.get('https://example.com/api/health');
    check(res, {
        'is status 200': (r) => r.status === 200,
        'response time < 500ms': (r) => r.timings.duration < 500,
    });
}

Advanced Smoke Test Example

import http from 'k6/http';
import { check, sleep } from 'k6';

export let options = {
    vus: 2, // 2 virtual users
    iterations: 10, // Runs the test 10 times
};

export default function () {
    let res = http.get('https://example.com/api/login');
    check(res, {
        'status is 200': (r) => r.status === 200,
        'response time < 400ms': (r) => r.timings.duration < 400,
    });
    sleep(1);
}

Running and Analyzing Results

Execute the test using

k6 run smoke-test.js

Sample Output

checks...
βœ” is status 200
βœ” response time < 500ms

If any of the checks fail, K6 will report an error, signaling an issue in the application.

Smoke testing with K6 is an effective way to ensure that key functionalities in your application work as expected. By integrating it into your CI/CD pipeline, you can catch major defects early, improve application stability, and streamline your development workflow.

Golden Feedbacks for Python Sessions 1.0 from last year (2024)

13 February 2025 at 08:49

Many Thanks to Shrini for documenting it last year. This serves as a good reference to improve my skills. Hope it will help many.

πŸ“’ What Participants wanted to improve

πŸšΆβ€β™‚οΈ Go a bit slower so that everyone can understand clearly without feeling rushed.


πŸ“š Provide more basics and examples to make learning easier for beginners.


πŸ–₯ Spend the first week explaining programming basics so that newcomers don’t feel lost.


πŸ“Š Teach flowcharting methods to help participants understand the logic behind coding.


πŸ•Ή Try teaching Scratch as an interactive way to introduce programming concepts.


πŸ—“ Offer weekend batches for those who prefer learning on weekends.


πŸ—£ Encourage more conversations so that participants can actively engage in discussions.


πŸ‘₯ Create sub-groups to allow participants to collaborate and support each other.


πŸŽ‰ Get β€œcheerleaders” within the team to make the classes more fun and interactive.


πŸ“’ Increase promotion efforts to reach a wider audience and get more participants.


πŸ” Provide better examples to make concepts easier to grasp.


❓ Conduct more Q&A sessions so participants can ask and clarify their doubts.


πŸŽ™ Ensure that each participant gets a chance to speak and express their thoughts.


πŸ“Ή Showing your face in videos can help in building a more personal connection with the learners.


πŸ† Organize mini-hackathons to provide hands-on experience and encourage practical learning.


πŸ”— Foster more interactions and connections between participants to build a strong learning community.


✍ Encourage participants to write blogs daily to document their learning and share insights.


🎀 Motivate participants to give talks in class and other communities to build confidence.

πŸ“ Other Learnings & Suggestions

πŸ“΅ Avoid creating WhatsApp groups for communication, as the 1024 member limit makes it difficult to manage multiple groups.


βœ‰ Telegram works fine for now, but explore using mailing lists as an alternative for structured discussions.


πŸ”• Mute groups when necessary to prevent unnecessary messages like β€œHi, Hello, Good Morning.”


πŸ“’ Teach participants how to join mailing lists like ChennaiPy and KanchiLUG and guide them on asking questions in forums like Tamil Linux Community.


πŸ“ Show participants how to create a free blog on platforms like dev.to or WordPress to share their learning journey.


πŸ›  Avoid spending too much time explaining everything in-depth, as participants should start coding a small project by the 5th or 6th class.


πŸ“Œ Present topics as solutions to project ideas or real-world problem statements instead of just theory.


πŸ‘€ Encourage using names when addressing people, rather than calling them β€œSir” or β€œMadam,” to maintain an equal and friendly learning environment.


πŸ’Έ Zoom is costly, and since only around 50 people complete the training, consider alternatives like Jitsi or Google Meet for better cost-effectiveness.

Will try to incorporate these learnings in our upcoming sessions.

πŸš€ Let’s make this learning experience engaging, interactive, and impactful! 🎯

A Step-by-Step Guide to LLM Function Calling inΒ Python

By: angu10
12 February 2025 at 23:06

Function calling allows Claude to interact with external functions and tools in a structured way. This guide will walk you through implementing function calling with Claude using Python, complete with examples and best practices.

Prerequisites

To get started, you'll need:

  • Python 3.7+
  • anthropic Python package
  • A valid API key from Anthropic

Basic Setup

from anthropic import Anthropic
import json
# Initialize the client
anthropic = Anthropic(api_key='your-api-key')

Defining Functions

function_schema = {
    "name": "get_weather",
    "description": "Get the current weather for a specific location",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City name or coordinates"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit"
            }
        },
        "required": ["location"]
    }
}

Making FunctionΒ Calls

A Step-by-Step Guide to LLM Function Calling inΒ Python
Function calling allows Claude to interact with external functions and tools in a structured way. This guide will walk you through implementing function calling with Claude using Python, complete with examples and best practices.
Prerequisites
To get started, you'll need:
Python 3.7+
anthropic Python package
A valid API key from Anthropic

Basic Setup
from anthropic import Anthropic
import json
# Initialize the client
anthropic = Anthropic(api_key='your-api-key')
Defining Functions
function_schema = {
    "name": "get_weather",
    "description": "Get the current weather for a specific location",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City name or coordinates"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit"
            }
        },
        "required": ["location"]
    }
}
Making FunctionΒ Calls
def get_weather(location, unit="celsius"):
    # This is a mock implementation but you can all call your API
    return {
        "location": location,
        "temperature": 22 if unit == "celsius" else 72,
        "conditions": "sunny"
    }
def process_function_call(message):
    try:
        # Parse the function call parameters
        params = json.loads(message.content)
        # Call the appropriate function
        if message.name == "get_weather":
            result = get_weather(**params)
            return json.dumps(result)
        else:
            raise ValueError(f"Unknown function: {message.name}")
    except Exception as e:
        return json.dumps({"error": str(e)})
# Example conversation with function calling
messages = [
    {
        "role": "user",
        "content": "What's the weather like in Paris?"
    }
]
while True:
    response = anthropic.messages.create(
        model="claude-3-5-haiku-latest",
        messages=messages,
        tools=[function_schema]
    )
    # Check if Claude wants to call a function
    if response.tool_calls:
        for tool_call in response.tool_calls:
            # Execute the function
            result = process_function_call(tool_call)
            # Add the function result to the conversation
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "name": tool_call.name,
                "content": result
            })
    else:
        # Normal response - print and break
        print(response.content)
        break

Best Practices

  1. Clear Function Descriptions
  • Write detailed descriptions for your functions
  • Specify parameter types and constraints clearly
  • Include examples in the descriptions when helpful
  1. Input Validation
  • Validate all function inputs before processing
  • Return meaningful error messages
  • Handle edge cases gracefully
  1. Response Formatting
  • Return consistent JSON structures
  • Include status indicators in responses
  • Format error messages uniformly

4Β . Security Considerations

  • Validate and sanitize all inputs
  • Implement rate limiting if needed
  • Use appropriate authentication
  • Don't expose sensitive information in function descriptions

Conclusion

Function calling with Claude enables powerful integrations between the language model and external tools. By following these best practices and implementing proper error handling, you can create robust and reliable function-calling implementations.

Effortless Git Repo Switching with a Simple Bash Function!

By: krishna
12 February 2025 at 10:36

Why I Created This Function

At first, I used an alias

alias gitdir="cd ~/Git/" (This means gitdir switches to the ~/Git/ directory, but I wanted it to switch directly to a repository.)
So, I wrote a Bash function.

Write Code to .bashrc File

The .bashrc file runs when a new terminal window is opened.
So, we need to write the function inside this file.

Code

gitrepo() {
    # Exact Match
    repoList=$(ls $HOME/Git)
    if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1
    else
	# Relevant Match
	getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"
	else
	    echo "Repository Not Founded"
	    cd $HOME/Git
	fi
	
    fi   
}

Code Explanation

The $repoList variable stores the list of directories inside the Git folder.

Function Logic Has Two Parts:

  • Exact Match
  • Relevant Match

Exact Match

if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1

If condition: The $repoList variable parses input for grep.

  • grep -w matches only whole words.
  • $1 is the function’s argument in bash.
  • -n checks if a variable is not empty. Example syntax:
    [ a != "" ] is equivalent to [ -n a ]

Relevant Match

getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"

Relevant search: If no Exact Match is found, this logic is executed next.

getRepoName="$repoList" | grep -i -m 1 $1
  • -i ignores case sensitivity.
  • -m 1 returns only the first match.

Example of -m with grep:
ls | grep i3
It returns i3WM and i3status, but -m 1 ensures only i3WM is selected.

No Match

If no match is found, it simply changes the directory to the Git folder.

	else
	    echo "Repository Not Founded"
	    cd $HOME/Git

What I Learned

  • Basics of Bash functions
  • How to use .bashrc and reload changes.

πŸ“’ Python Learning 2.0 in Tamil – Call for Participants! πŸš€

10 February 2025 at 07:58

After an incredible year of Python learning Watch our journey here, we’re back with an all new approach for 2025!

If you haven’t subscribed to our channel, don’t miss to do it ? Support Us by subscribing

This time, we’re shifting gears from theory to practice with mini projects that will help you build real-world solutions. Study materials will be shared beforehand, and you’ll work hands-on to solve practical problems building actual projects that showcase your skills.

πŸ”‘ What’s New?

βœ… Real-world mini projects
βœ… Task-based shortlisting process
βœ… Limited seats for focused learning
βœ… Dedicated WhatsApp group for discussions & mentorship
βœ… Live streaming of sessions for wider participation
βœ… Study materials, quizzes, surprise gifts, and more!

πŸ“‹ How to Join?

  1. Fill the below RSVP – Open for 20 days (till – March 2) only!
  2. After RSVP closes, shortlisted participants will receive tasks via email.
  3. Complete the tasks to get shortlisted.
  4. Selected students will be added to an exclusive WhatsApp group for intensive training.
  5. It’s a COST-FREE learning. We require your time, effort and support.
  6. Course start date will be announced after RSVP.

πŸ“œ RSVP Form

☎ How to Contact for Queries ?

If you have any queries, feel free to message in whatsapp, telegram, signal on this number 9176409201.

You can also mail me at learnwithjafer@gmail.com

Follow us for more oppurtunities/updates and more…

Don’t miss this chance to level up your Python skills Cost Free with hands-on projects and exciting rewards! RSVP now and be part of Python Learning 2.0! πŸš€

Our Previous Monthly meets – https://www.youtube.com/watch?v=cPtyuSzeaa8&list=PLiutOxBS1MizPGGcdfXF61WP5pNUYvxUl&pp=gAQB

Our Previous Sessions,

Postgres – https://www.youtube.com/watch?v=04pE5bK2-VA&list=PLiutOxBS1Miy3PPwxuvlGRpmNo724mAlt&pp=gAQB

Python – https://www.youtube.com/watch?v=lQquVptFreE&list=PLiutOxBS1Mizte0ehfMrRKHSIQcCImwHL&pp=gAQB

Docker – https://www.youtube.com/watch?v=nXgUBanjZP8&list=PLiutOxBS1Mizi9IRQM-N3BFWXJkb-hQ4U&pp=gAQB

Note: If you wish to support me for this initiative please share this with your friends, students and those who are in need.

Learning Notes #70 – RUFF An extremely fast Python linter and code formatter, written in Rust.

9 February 2025 at 11:00

In the field of Python development, maintaining clean, readable, and efficient code is needed.

The Ruff Python package is a faster linter and code formatter designed to boost code quality and developer productivity. Written in Rust, Ruff stands out for its blazing speed and comprehensive feature set.

This blog will delve into Ruff’s features, usage, and how it compares to other popular Python linters and formatters like flake8, pylint, and black.

What is Ruff?

Ruff is an extremely fast Python linter and code formatter that provides linting, code formatting, and static code analysis in a single package. It supports a wide range of rules out of the box, covering various Python standards and style guides.

Key Features of Ruff

  1. Lightning-fast Performance: Written in Rust, Ruff is significantly faster than traditional Python linters.
  2. All-in-One Tool: Combines linting, formatting, and static analysis.
  3. Extensive Rule Support: Covers rules from flake8, isort, pyflakes, pylint, and more.
  4. Customizable: Allows configuration of rules to fit specific project needs.
  5. Seamless Integration: Works well with CI/CD pipelines and popular code editors.

Installing Ruff


# Using pip
pip install ruff

# Using Homebrew (macOS/Linux)
brew install ruff

# Using UV
uv add ruff

Basic Usage

1. Linting a python file

# Lint a single file
ruff check app.py

# Lint an entire directory
ruff check src/

2. Auto Fixing Issues

ruff check src/ --fix

3. Formatting Code

While Ruff primarily focuses on linting, it also handles some formatting tasks

ruff format src/

Configuration

Ruff can be configured using a pyproject.toml file

[tool.ruff]
line-length = 88
exclude = ["migrations"]
select = ["E", "F", "W"]  # Enable specific rule categories
ignore = ["E501"]          # Ignore specific rules

Examples

import sys
import os

print("Hello World !")


def add(a, b):
    result = a + b
    return a

x= 1
y =2
print(x+y)

def append_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list

def append_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list

  1. Identifying Unused Imports
  2. Auto-fixing Imports
  3. Sorting Imports
  4. Detecting Unused Variables
  5. Enforcing Code Style (PEP 8 Violations)
  6. Detecting Mutable Default Arguments
  7. Fixing Line Length Issues

Integrating Ruff with Pre-commit

To ensure code quality before every commit, integrate Ruff with pre-commit

Step 1: Install Pre-Commit

pip install pre-commit

Step 2: Create a .pre-commit-config.yaml file

repos:
  - repo: https://github.com/charliermarsh/ruff-pre-commit
    rev: v0.1.0  # Use the latest version
    hooks:
      - id: ruff

Step 3: Install the Pre-commit Hook

pre-commit install

Step 4: Test the Hook

pre-commit run --all-files

This setup ensures that Ruff automatically checks your code for linting issues before every commit, maintaining consistent code quality.

When to Use Ruff

  • Large Codebases: Ideal for projects with thousands of files due to its speed.
  • CI/CD Pipelines: Reduces linting time, accelerating build processes.
  • Code Reviews: Ensures consistent coding standards across teams.
  • Open Source Projects: Simplifies code quality management.
  • Pre-commit Hooks: Ensures code quality before committing changes.

Integrating Ruff with CI/CD

name: Lint Code

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.10'
    - name: Install Ruff
      run: pip install ruff
    - name: Lint Code
      run: ruff check .

Ruff is a game-changer in the Python development ecosystem. Its unmatched speed, comprehensive rule set, and ease of use make it a powerful tool for developers aiming to maintain high code quality.

Whether you’re working on small scripts or large-scale applications, Ruff can streamline your linting and formatting processes, ensuring clean, efficient, and consistent code.

Python variable

By: krishna
7 February 2025 at 06:34

This blog explores Python variable usage and functionalities.

Store All Data Types

First, let’s list the data types supported in Python.

Python Supported Data Types

  • Primitive Data Types:
    • Integer
    • Float
    • String
    • Boolean
    • None
  • Non-Primitive Data Types:
    • List
    • Tuple
    • Set
    • Bytes and ByteArray
    • Complex
    • Class Object

Store and Experiment with All Data Types

phone = 1234567890
pi    = 3.14
name  = "python programming"
using_python   = True
example_none   = None
simple_list    = [1,2,3]
simple_dict    = {"name":"python"}
simple_set     = {1,1,1,1,1.0}
simple_tuple   = (1,2,3)
complex_number = 3+5j

print("number     = ",phone)
print("float      = ",pi)
print("boolean    = ",using_python)
print("None       = ",example_none)
print("list       = ",simple_list)
print("dictionary = ",simple_dict)
print("set        = ",simple_set)
print("tuple      = ",simple_tuple)
print("complex    = ",complex_number)

Output

number     =  1234567890
float      =  3.14
boolean    =  True
None       =  None
list       =  [1, 2, 3]
dictionary =  {'name': 'python'}
set        =  {1}
tuple      =  (1, 2, 3)
complex    =  (3+5j)

Type Function

This function is used to print the data type of a variable.

print(type(phone))
print(type(pi))
print(type(using_python))
print(type(simple_list))
print(type(simple_dict))
print(type(simple_set))
print(type(simple_tuple))
print(type(complex_number))
print(type(example_none))

Output

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'set'>
<class 'tuple'>
<class 'complex'>
<class 'NoneType'>

Bytes and ByteArray

These data types help modify large binary datasets like audio and image processing.

The memoryview() function allows modifying this data without zero-copy access to memory.

bytes is immutable, where as bytearray is mutable.

bytes

b1 = bytes([1,2,3,4])
bo = memoryview(b1)
print("byte example :",bo[0])

Output

byte example : 1

bytearray

b2 = bytearray(b"aaaa")
bo = memoryview(b2)
print("byte array :",b2)
bo[1] = 98
bo[2] = 99
bo[3] = 100
print("byte array :",b2)

Output

byte array : bytearray(b'aaaa')
byte array : bytearray(b'abcd')

Other Data Types

Frozenset

A frozenset is similar to a normal set, but it is immutable.

test_frozenset = frozenset([1,2,1])
for i in test_frozenset:
    print("frozen set item :",i)

Output

frozen set item : 1
frozen set item : 2

Range

The range data type specifies a number range (e.g., 1-10).

It is mostly used in loops and mathematical operations.

a = range(3)
print("a = ",a)
print("type = ",type(a))

Output

a =  range(0, 3)
type =  <class 'range'>

Type Casting

Type casting is converting a data type into another. Try explicit type casting to change data types.

value = 1
numbers = [1,2,3]
print("type casting int     : ",type(int(value)))
print("type casting float   : ",type(float(value)))
print("type casting string  : ",type(str(value)))
print("type casting boolean : ",type(bool("True")))
print("type casting list    : ",type(list(numbers)))
print("type casting set     : ",type(set(numbers)))
print("type casting tuple   : ",type(tuple(numbers)))

Output

type casting int     :  <class 'int'>
type casting float   :  <class 'float'>
type casting string  :  <class 'str'>
type casting boolean :  <class 'bool'>
type casting list    :  <class 'list'>
type casting set     :  <class 'set'>
type casting tuple   :  <class 'tuple'>

Delete Variable

Delete an existing variable using Python’s del keyword.

temp = 1
print("temp variable is : ",temp)
del temp
# print(temp)  => throw NameError : temp not defined

Output

temp variable is :  1

Find Variable Memory Address

Use the id() function to find the memory address of a variable.

temp = "hi"
print("address of temp variable : ",id(temp))

Output

address of temp variable :  140710894284672

Constants

Python does not have a direct keyword for constants, but namedtuple can be used to create constants.

from collections import namedtuple
const = namedtuple("const",["PI"])
math = const(3.14)

print("namedtuple PI = ",math.PI)
print("namedtuple type =",type(math))

Output

namedtuple PI =  3.14
namedtuple type = <class '__main__.const'>

Global Keyword

Before understanding global keyword, understand function-scoped variables.

  • Function inside variable are stored in stack memory.
  • A function cannot modify an outside (global) variable directly, but it can access it.
  • To create a reference to a global variable inside a function, use the global keyword.
message = "Hi"
def dummy():
    global message 
    message = message+" all"

dummy()
print(message)

Output

Hi all

Explicit Type Hint

Type hints are mostly used in function parameters and arguments.

They improve code readability and help developers understand variable types.

-> float : It indicates the return data type.

def area_of_circle(radius :float) -> float:
    PI :float = 3.14
    return PI * (radius * radius)

print("calculate area of circle = ",area_of_circle(2))

Output

calculate area of circle =  12.56

20 Essential Git Command-Line Tricks Every Developer Should Know

5 February 2025 at 16:14

Git is a powerful version control system that every developer should master. Whether you’re a beginner or an experienced developer, knowing a few handy Git command-line tricks can save you time and improve your workflow. Here are 20 essential Git tips and tricks to boost your efficiency.

1. Undo the Last Commit (Without Losing Changes)

git reset --soft HEAD~1

If you made a commit but want to undo it while keeping your changes, this command resets the last commit but retains the modified files in your staging area.

This is useful when you realize you need to make more changes before committing.

If you also want to remove the changes from the staging area but keep them in your working directory, use,

git reset HEAD~1

2. Discard Unstaged Changes

git checkout -- <file>

Use this to discard local changes in a file before staging. Be careful, as this cannot be undone! If you want to discard all unstaged changes in your working directory, use,

git reset --hard HEAD

3. Delete a Local Branch

git branch -d branch-name

Removes a local branch safely if it’s already merged. If it’s not merged and you still want to delete it, use -D

git branch -D branch-name

4. Delete a Remote Branch

git push origin --delete branch-name

Deletes a branch from the remote repository, useful for cleaning up old feature branches. If you mistakenly deleted the branch and want to restore it, you can use

git checkout -b branch-name origin/branch-name

if it still exists remotely.

5. Rename a Local Branch

git branch -m old-name new-name

Useful when you want to rename a branch locally without affecting the remote repository. To update the remote reference after renaming, push the renamed branch and delete the old one,

git push origin -u new-name
git push origin --delete old-name

6. See the Commit History in a Compact Format

git log --oneline --graph --decorate --all

A clean and structured way to view Git history, showing branches and commits in a visual format. If you want to see a detailed history with diffs, use

git log -p

7. Stash Your Changes Temporarily

git stash

If you need to switch branches but don’t want to commit yet, stash your changes and retrieve them later with

git stash pop

To see all stashed changes

git stash list

8. Find the Author of a Line in a File

git blame file-name

Shows who made changes to each line in a file. Helpful for debugging or reviewing historical changes. If you want to ignore whitespace changes

git blame -w file-name

9. View a File from a Previous Commit

git show commit-hash:path/to/file

Useful for checking an older version of a file without switching branches. If you want to restore the file from an old commit

git checkout commit-hash -- path/to/file

10. Reset a File to the Last Committed Version

git checkout HEAD -- file-name

Restores the file to the last committed state, removing any local changes. If you want to reset all files

git reset --hard HEAD

11. Clone a Specific Branch

git clone -b branch-name --single-branch repository-url

Instead of cloning the entire repository, this fetches only the specified branch, saving time and space. If you want all branches but don’t want to check them out initially:

git clone --mirror repository-url

12. Change the Last Commit Message

git commit --amend -m "New message"

Use this to correct a typo in your last commit message before pushing. Be cautiousβ€”if you’ve already pushed, use

git push --force-with-lease

13. See the List of Tracked Files

git ls-files

Displays all files being tracked by Git, which is useful for auditing your repository. To see ignored files

git ls-files --others --ignored --exclude-standard

14. Check the Difference Between Two Branches

git diff branch-1..branch-2

Compares changes between two branches, helping you understand what has been modified. To see only file names that changed

git diff --name-only branch-1..branch-2

15. Add a Remote Repository

git remote add origin repository-url

Links a remote repository to your local project, enabling push and pull operations. To verify remote repositories

git remote -v

16. Remove a Remote Repository

git remote remove origin

Unlinks your repository from a remote source, useful when switching remotes.

17. View the Last Commit Details

git show HEAD

Shows detailed information about the most recent commit, including the changes made. To see only the commit message

git log -1 --pretty=%B

18. Check What’s Staged for Commit

git diff --staged

Displays changes that are staged for commit, helping you review before finalizing a commit.

19. Fetch and Rebase from a Remote Branch

git pull --rebase origin main

Combines fetching and rebasing in one step, keeping your branch up-to-date cleanly. If conflicts arise, resolve them manually and continue with

git rebase --continue

20. View All Git Aliases

git config --global --list | grep alias

If you’ve set up aliases, this command helps you see them all. Aliases can make your Git workflow faster by shortening common commands. For example

git config --global alias.co checkout

allows you to use git co instead of git checkout.

Try these tricks in your daily development to level up your Git skills!

❌
❌