Friday, January 17, 2025

Python Dictionaries

 A dictionary in python can contain name value pairs. Like

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
}

where thisdict contains name, gender and age of string, boolean and int data type.

On purpose I have created another dict with a JSON as a value of a name-value pair.

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

I have made use of this dictionary structure in a program which

a. finds the length of the dictionary

b. prints the name, gender and age

c. prints the net-worth of the individual in the dictionary object.


thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

thatdict = {
    "name" : "Harish",
    "gender" : True,
    "age" : 54,
    "assets-json" : {
        "net-worth": 10000000,
        "house-type": "Individual House",
        "address": ["Jayanagar",
                    "Bangalore",
                    "560045"]
    }
}

def length_of_dict(dict_param):
    return len(dict_param)

def display_dict(dict_param):
    print("this dict is of %s" % dict_param["name"])
    gender = "male" if dict_param["gender"] == True else "female"
    print("Age = %s \nGender= %s" %(dict_param["age"], gender))
    print("Net Worth:%s" % dict_param["assets-json"]["net-worth"])

if __name__=="__main__":
    print("Length of thatdict:",length_of_dict(thatdict))
    print("Length of thisdict:",length_of_dict(thisdict))
    display_dict(thatdict)
    display_dict(thisdict)

Output of the program:

Length of thatdict: 4

Length of thisdict: 4

this dict is of Harish

Age = 54

Gender= male

Net Worth:10000000

this dict is of Shiva

Age = 45

Gender= male

Net Worth:1000000

Wednesday, January 1, 2025

Python Lists

 In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.

  • List can contain duplicate items.
  • List in Python are Mutable. Hence, we can modify, replace or delete the items.
  • List are ordered. It maintain the order of elements based on how they are added.
  • Accessing items in List can be done directly using their position (index), starting from 0.

nested lists in python : matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access element at row 2, column 3
print(matrix[1][2])

Another program to find pair of numbers in a sorted array that sum to a value(target):

def pair_sum_sorted_all_pairs(arr, target):

  """

  Finds all pairs in a sorted array that sum to a given target.

  Args:

    arr: A sorted array of integers.

    target: The target sum.

  Returns:

    A list of tuples representing the pairs.

  """

  result = []

  left, right = 0, len(arr) - 1

  while left < right:

    current_sum = arr[left] + arr[right]

    if current_sum == target:

      result.append((arr[left], arr[right]))

      left += 1

      right -= 1

    elif current_sum < target:

      left += 1

    else:

      right -= 1


  return result


if __name__=="__main__":

    arr = [1, 2, 3, 4, 5, 6, 7]

    target = 8

    print(pair_sum_sorted_all_pairs(arr, target))

When we run this program here we get following output:


C:\Users\kamat>python untitled123.py

[(1, 7), (2, 6), (3, 5)]

Friday, December 27, 2024

Python - Basics

I have written three python programs in increasing order of complexity.

First one is:

x=int(input("Enter a number"))
y=int(input("Enter another number"))
z=int(input("Enter third number"))
sum=x + y + z
print(sum)


The program reads three numbers (Integers) and finds their sum

class simple:
    def simple_one():
        print("Hello mukesh")
        print("Hello manjunath")


if __name__=="__main__":
    simple.simple_one()


This next program creates a simple class and calls a method on the class object.
The if statement equates __name__ to "__main__" and executes the method if so.

class simple():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def simple_one(self):
        print("Hello %s %s"%(self.name,self.age))

if __name__=="__main__":
    s = simple("mukesh",45)
    s.simple_one()

This next program above instantiates an object of
class simple by calling its constructor. Then a
method simple_one() on the created object.

Monday, November 18, 2024

Full Stack Development using Python

DJango Web Framework:

It is a free and open source framework for making web applications using python. It is claimed to be a

batteries included framework.

It includes the Admin Site, An Object Relational Mapper(ORM), Authentication, Caching etc.

A Web Application works by having a Front end(Browser/Client) and a Backend(Server).

Recently the trend has been to have the server expose a set of server api endpoints and supply only the data. This data can be either in XML or JSON format.

Front end could be a React/Vue/Angular project.


We cannot compare DJango with React or Vue as they both work at the front end and DJango

is a server technology. A better comparison would be between django and ASP.net core or Express.

We could however use DJango to build the server APIs.

Here is a list of Questions you can pose to the students(VTU):

Laboratory Component:

1. Installation of Python, Django and Visual Studio code editors can be demonstrated.

2. Creation of virtual environment, Django project and App should be demonstrated

3. Develop a Django app that displays current date and time in server

4. Develop a Django app that displays date and time four hours ahead and four hours before as an offset of current date and time in server.

5. Develop a simple Django app that displays an unordered list of fruits and ordered list of selected students for an event

6. Develop a layout.html with a suitable header (containing navigation menu) and footer with copyright and developer information. Inherit this layout.html and create 3 additional pages: contact us, About Us and Home page of any website.

7. Develop a Django app that performs student registration to a course. It should also display list of students registered for any selected course. Create students and course as models with enrolment as ManyToMany field.

8. For student and course models created in Lab experiment for Module2, register admin interfaces, perform migrations and illustrate data entry through admin forms.

9. Develop a Model form for student that contains his topic chosen for project, languages used and duration with a model called project. 

10. For students enrolment developed in Module 2, create a generic class view which displays list of students and detailview that displays student details for any selected student in the list.

11. Develop example Django app that performs CSV and PDF generation for any models created in previous laboratory component.

12. Develop a registration page for student enrolment as done in Module 2 but without page refresh using AJAX.

13. Develop a search application in Django using AJAX that displays courses enrolled by a student being searched. 

You can download the Lab Manual (PDF) from Here: https://drive.google.com/file/d/1MtkObE3iD7kD05cTQcnAwDT298rhXTRf/view?usp=sharing

Sunday, September 15, 2024

Sierpinki Gasket in an Android App

This project is a modification of an existing app I created earlier.

~TLDR: clone the repo https://github.com/bmkamath2000/mukBoApps and open in android studio to run. 

Upon creating an android project in android studio there was a MainActivity.java automatically created in the src folder.

I instinctively guessed that I needed to declare a MyGLSurfaceView which extends a GLSurfaceView.

My guess turned true as I got a surface in the app when I created a run configuration and

launched the app using it.

I had some experience with rudimentary android app development over several years in the past.

package com.example.mukesh.seirpinskigasketandroid;

import android.opengl.GLSurfaceView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import java.lang.Runnable;

public class MainActivity extends AppCompatActivity {
    private MyGLSurfaceView mGLView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGLView = new MyGLSurfaceView(this);
        setContentView(mGLView);
    }
}

As you can see onCreate of the MainActivity the view is set as content view.

In MyGLSurfaceView

I created a MyGLRenderer instance which is derived from GLSurfaceView.Renderer.

package com.example.mukesh.seirpinskigasketandroid;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import android.view.KeyEvent;

public class MyGLSurfaceView extends GLSurfaceView {
    private final MyGLRenderer mRenderer;
    //variable for storing the time of first click
    long startTime;
    public MyGLSurfaceView(Context context) {
        super(context);

        // Create an OpenGL ES 2.0 context
        setEGLContextClientVersion(2);

        mRenderer = new MyGLRenderer();

        // Set the Renderer for drawing on the GLSurfaceView
        setRenderer(mRenderer);
        // Render the view only when there is a change in the drawing data
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        // MotionEvent reports input details from the touch screen
        // and other input controls. In this case, you are only
        // interested in events where the touch position changed.

        //constant for defining the time duration between the click that can be
        //considered as double-tap
        final int MAX_DURATION = 200;

        if (e.getAction() == MotionEvent.ACTION_DOWN) {

            startTime = System.currentTimeMillis();
        }
        else if (e.getAction() == MotionEvent.ACTION_UP) {

            if(System.currentTimeMillis() - startTime >= MAX_DURATION)
            {
                //DOUBLE TAP
                mRenderer.mTriangle.n++;
                requestRender();
            }
            else {
                //SINGLE TAP
                if(mRenderer.mTriangle.n>0) {
                    mRenderer.mTriangle.n--;
                    requestRender();
                }
            }
        }
        return true;
    }
}

The MyGLRenderer declares a Triangle and draws it onDrawFrame.

package com.example.mukesh.seirpinskigasketandroid;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyGLRenderer implements GLSurfaceView.Renderer {
    public Triangle mTriangle;
    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        // initialize a triangle
        mTriangle = new Triangle();
        // initialize a square
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        mTriangle.draw();
    }
    public static int loadShader(int type, String shaderCode){

        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
        int shader = GLES20.glCreateShader(type);

        // add the source code to the shader and compile it
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }
}

I have Created the Triangle class which is based on the android official site:

https://developer.android.com/develop/ui/views/graphics/opengl/draw

package com.example.mukesh.seirpinskigasketandroid;

import android.opengl.GLES20;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class Triangle {
    private final int mProgram;
    private FloatBuffer vertexBuffer;

    // number of coordinates per vertex in this array
    static final int COORDS_PER_VERTEX = 3;
    static float triangleCoords[] = {   // in counterclockwise order:
            0.0f,  0.622008459f, 0.0f, // top
            -0.5f, -0.311004243f, 0.0f, // bottom left
            0.5f, -0.311004243f, 0.0f  // bottom right
    };
    float v[][]={{-1.0f,-0.5f,0.0f},{1.0f,-0.5f,0.0f},
            {0.0f,1.0f,0.0f}};
    float colors[][]={{1.0f,0.0f,0.0f},{0.0f,1.0f,0.0f},{0.0f,0.0f,1.0f},
    {0.0f,0.0f,0.0f}};
    public int n=4, prevn=0;
    int vc1=0;
    // Set color with red, green, blue and alpha (opacity) values
    float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };

    public Triangle() {
        // create empty OpenGL ES Program
        mProgram = GLES20.glCreateProgram();
    }
    void triangle(FloatBuffer fb,float a[],float b[],float c[])
    {
        fb.put(a);
        fb.put(b);
        fb.put(c);
        vc1+=3;
    }
    public int findnoofnodes(int nt)
    {
        if(nt<=1)
            return 3;
        else return ((findnoofnodes(nt-1) * 3) - 3);
    }


    void divide_tetra(FloatBuffer fb,float a[],float b[],float c[],int m)
    {
        float v1[]=new float[3],v2[]=new float[3],v3[]=new float[3];
        int j;
        if(m>0)
        {    /*compute three midpoints*/
            for(j=0;j<3;j++)
                v1[j]=(a[j]+b[j])/2;

            for(j=0;j<3;j++)
                v2[j]=(a[j]+c[j])/2;

            for(j=0;j<3;j++)
                v3[j]=(c[j]+b[j])/2;

            divide_tetra(fb,a,v2,v1,m-1);
            divide_tetra(fb,c,v3,v2,m-1);
            divide_tetra(fb,b,v1,v3,m-1);

        }
        else
            triangle(fb, a, b, c);      //draw triangle at end of recursion//
    }


    private final String vertexShaderCode =
            "attribute vec4 vPosition;" +
                    "void main() {" +
                    "  gl_Position = vPosition;" +
                    "}";

    private final String fragmentShaderCode =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "  gl_FragColor = vColor;" +
                    "}";
    private int mPositionHandle;
    private int mColorHandle;

    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
    private final int vertexStride = COORDS_PER_VERTEX *4; // 4 bytes per vertex
    public void PopulateVBO()
    {
        final int nodesN = findnoofnodes(n+2);
        // initialize vertex byte buffer for shape coordinates
        ByteBuffer bb = ByteBuffer.allocateDirect(
                // (number of coordinate values * 4 bytes per float)
                (nodesN* 16 ) +100
                //90000
        );
        // use the device hardware's native byte order
        bb.order(ByteOrder.nativeOrder());

        // create a floating point buffer from the ByteBuffer
        vertexBuffer = bb.asFloatBuffer();
        // add the coordinates to the FloatBuffer
        //vertexBuffer.put(triangleCoords);
        // set the buffer to read the first coordinate
        vc1=0;
        divide_tetra(vertexBuffer,v[0],v[1],v[2],n);
        System.out.println("Length of VB"+ vertexBuffer.capacity()+ "VC1"+vc1);
        vertexBuffer.position(0);
        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
                vertexShaderCode);
        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
                fragmentShaderCode);

        // add the vertex shader to program
        GLES20.glAttachShader(mProgram, vertexShader);

        // add the fragment shader to program
        GLES20.glAttachShader(mProgram, fragmentShader);

        // creates OpenGL ES program executables
        GLES20.glLinkProgram(mProgram);
    }
    public void draw() {
        if(prevn != n && n > 0)
        {
            prevn = n;
            PopulateVBO();
        }
        // Add program to OpenGL ES environment
        GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(mPositionHandle);

        // Prepare the triangle coordinate data
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);

        // get handle to fragment shader's vColor member
        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

        // Set color for drawing the triangle
        GLES20.glUniform4fv(mColorHandle, 1, color, 0);

        // Draw the triangle
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,vc1);

        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }
}

The triangle is subdivided and on single or delayed click the number of triangles

triples or divides by a factor of 3.


Here is how it looks:



Thanks

Saturday, September 14, 2024

protobuf.dev getting started with protocol buffer example

 Head over to the site https://protobuf.dev

In that site you will find things to compile a C++ and many other language projects with address book. Now just take a deep breath and dive in.

Warning: This is easy in Linux and verry verry difficult in Windows

If you find the going tough in that site, come here for I will get you some personal touch.

write_to_file.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "./proto/addressbook.pb.h"
using namespace std;

// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
  cout << "Enter person ID number: ";
  int id;
  cin >> id;
  person->set_id(id);
  cin.ignore(256, '\n');

  cout << "Enter name: ";
  getline(cin, *person->mutable_name());

  cout << "Enter email address (blank for none): ";
  string email;
  getline(cin, email);
  if (!email.empty()) {
    person->set_email(email);
  }

  while (true) {
    cout << "Enter a phone number (or leave blank to finish): ";
    string number;
    getline(cin, number);
    if (number.empty()) {
      break;
    }

    tutorial::Person::PhoneNumber* phone_number = person->add_phones();
    phone_number->set_number(number);

    cout << "Is this a mobile, home, or work phone? ";
    string type;
    getline(cin, type);
    if (type == "mobile") {
      phone_number->set_type(tutorial::Person::PHONE_TYPE_MOBILE);
    } else if (type == "home") {
      phone_number->set_type(tutorial::Person::PHONE_TYPE_HOME);
    } else if (type == "work") {
      phone_number->set_type(tutorial::Person::PHONE_TYPE_WORK);
    } else {
      cout << "Unknown phone type.  Using default." << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file,
//   adds one person based on user input, then writes it back out to the same
//   file.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!input) {
      cout << argv[1] << ": File not found.  Creating a new file." << endl;
    } else if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  // Add an address.
  PromptForAddress(address_book.add_people());

  {
    // Write the new address book back to disk.
    fstream output(argv[1], ios::out | ios::trunc | ios::binary);
    if (!address_book.SerializeToOstream(&output)) {
      cerr << "Failed to write address book." << endl;
      return -1;
    }
  }

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

read_from_file.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const tutorial::AddressBook& address_book) {
  for (int i = 0; i < address_book.people_size(); i++) {
    const tutorial::Person& person = address_book.people(i);

    cout << "Person ID: " << person.id() << endl;
    cout << "  Name: " << person.name() << endl;
    if (person.has_email()) {
      cout << "  E-mail address: " << person.email() << endl;
    }

    for (int j = 0; j < person.phones_size(); j++) {
      const tutorial::Person::PhoneNumber& phone_number = person.phones(j);

      switch (phone_number.type()) {
        case tutorial::Person::PHONE_TYPE_MOBILE:
          cout << "  Mobile phone #: ";
          break;
        case tutorial::Person::PHONE_TYPE_HOME:
          cout << "  Home phone #: ";
          break;
        case tutorial::Person::PHONE_TYPE_WORK:
          cout << "  Work phone #: ";
          break;
      }
      cout << phone_number.number() << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  ListPeople(address_book);

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}