Thursday, November 6, 2025

Getting started with Django

So in Python web development, 2 major frameworks stand out: Flask and Django. Flask is very straight forward. Django is a little more involved and "batteries-included". This means it comes with lots of features including an admin page and ORM (with sqlite) built right in. However it is a bit hassle to set it up. The Django Tutorial is a good place to start.

It involves virtual environment. You need to generate a project and then generate an app within.. You run that manage.py to let it generate some files and hand change some stuff (in many places) to get a standard MVC app going.

It knows what you want... a view.py to tweak for your controller objects to give data to your template htmls to show, a urls.py to set up your routing from url to controllers. It even has a models.py that you put your DB objects in.

You have to run some migrations to generate that database behind the scene initially to create your database.

It even has a shell so you can tweak data in there if you like. It even has an admin page where you can see your data! But you have to create a super user first.

https://github.com/josephmaklc/crud_project

Thursday, October 30, 2025

Playing with Vue

Vue is another javascript framework that is worth looking at besides the dominant React and Angular. It is kinda like React in some way. It uses its own extension .vue (not .js). You kinda work with its states with "ref". It likes single file components (SFC). You will need to install Node, then install Vue on your machine to make a new project to make it generate stuff for you to make your own app and components (like React).

The tutorial is fairly straight forward to follow. I like the fact it isn't a (giant) method to returning large html but you mark your code with its <template> tag. You can play in the Vue playground. Here is some simple code I tweaked from the tutorial.

<script setup>
import { ref } from 'vue'

// give each todo a unique id
let id = 0

const newTodo = ref('')
const todos = ref([
  { id: id++, text: 'Learn HTML' },
  { id: id++, text: 'Learn JavaScript' },
  { id: id++, text: 'Learn Vue' }
])

function addTodo() {  
  todos.value.push({ id: id++, text: newTodo.value })
  newTodo.value = ''
}

function removeTodo(todo) {
  todos.value = todos.value.filter((t) => t !== todo)
}
</script>

<template>
  <form @submit.prevent="addTodo">
    <input v-model="newTodo" required placeholder="new todo">
    <button>Add Todo</button>
  </form>
  <table>
    <tr v-for="todo in todos">
      <td>{{todo.text}}</td>      
      <td><button @click="removeTodo(todo)">X</button></td>
    </tr>
  </table>
</template>

Tuesday, September 2, 2025

Using OpenAI in code

AI is everywhere you can't escape. Google search something? AI will want to chip in what it thinks. Every Microsoft thing has Co-Pilots that can help you in various ways in its products. Now how about write your own code using it? OpenAI's ChatGPT is the thing to go to...Python is the preferred language. Just about every example out there uses it. Watch out! Some examples you see from websites, youtube, even generated by AI itself... can be outdated as OpenAI is still constantly evolving.

Using OpenAI in code is isn't free but looks affordable at first glance. Look at its pricing though. A million tokens for a few cents? Well look again, one call can be many tokens as it counts output characters, and image generation is a lot of tokens. Watch your budget.

After you pay up to get a OPEN_API_KEY, do not include it in your code as you don't want that stolen. Put it in a file named .env, and then use load_dotenv after installing with "pip install python-dotenv". Then you have to install the OpenAI library with "pip install openai". After you have the client you can do A LOT of stuff with it. See https://github.com/openai/openai-python to start your adventure.

I did, see it in https://github.com/josephmaklc/openapi/blob/main/openai_experiment.py

I got OpenAI to answer questions, also remember my previous question so I can ask followup questions. I got it to generate an audio file that I cannot tell at all it isn't recorded by human. I even got it to generate code! One cool aspect of ChatGPT is generating images! However, that requires you to "Verify you Organization" which means take a picture of your government ID and send to them... Eew I don't want to do that.

Tuesday, August 26, 2025

curl in Windows

Developers (on the Mac) has long used curl to test out http calls on the command line. Sure you can use the browser to test out any GET commmands, and use other things such as Postman to test POST. But curl is very handy and it is right on the command line. Now Windows users do not have it previously.. it was a separate download. If you have Windows 10 or 11 you have it pre-installed in your C:\windows\system32 folder. However, the world's example code and documentation are not so fair to developers on Windows. Flatty copy paste what you see will result in errors due to differences in Windows.

For example you are doing a little API with music albums your curl (for Mac) for inserting a record looks like this:

$ curl http://localhost:8080/albums \
    --include \
    --header "Content-Type: application/json" \
    --request "POST" \
    --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
But boom not working for Windows because of the following.
  1. The not-yet-end-of-commmand character for Windows is not \, it is ^.
  2. Don't use single quotes. Json double quotes need to be escaped.

So the command above to run for above is

  curl http://localhost:8080/albums ^
    --include ^
    --header "Content-Type: application/json" ^
    --request "POST" ^
    --data "{\"id\": \"4\",\"title\": \"The Modern Sound of Betty Carter\",\"artist\": \"Betty Carter\",\"price\": 49.99}"
    

Monday, May 5, 2025

Hello Typescript world

Typescript is javascript with type. Waita minute the very reason you use javascript (rather than java) is you want to be quick-and-dirty and not want to use types right? Well if you want to use React with types you will need Typescript. Its syntax is somewhat like Pascal: See https://www.geeksforgeeks.org/hello-world-in-typescript-language/ for a quick introduction. But in React you don't compile and run. It's mostly automatic. and you are likely not going to do a lot of heavy OOP either.

Search for "react typescript hello world" and you will find several ways to do that. I use npm. First you need to install node. Then create skeleton app:

npx create-react-app my-app --template typescript
Then go to the folder
cd my-app
A bunch of things has been generated for you. Go to src/App.tsx. This is where you put your components.

Here is a simple component. Call it MyComponentFC.tsx

import React from 'react';

const MyComponentFC: React.FC<{
  name: string;
  age: number}> = ({name,age}) => {

  return (
    <h1>Hello, {name}! you are {age} years old</h1>
  );
};

export default MyComponentFC;

In React instead of making things public you "export" it so it is known to outside world. Yes, people like returning not a single value these days. People don't mind mixing code with HTML in a giant return statement. You are cranky old school if you think this isn't so elegant.

See this little component (not a class, but a constant function) takes 2 parameters and you can give each a type (and you have to repeat the names in that interesting symtax). The parameters can be much more complex than strings and numbers. The idea is define your own tags and manage states (variables) within.

This simple component generates some simple html with parameters you passed in.

That index.html is what your browser hits... which in turns calls index.tsx, which calls the App component. Here is my tweaked App.tsx to call that component. FC stands for Function Component.

import './App.css';
import MyComponentFC from './MyComponentFC';

function App() {
  return (
      <MyComponentFC name="Johnny" age={20}/>
      )
}

export default App;

Launch the app with

npm start

Monday, February 3, 2025

Hello boto3 world

Boto3 is the library for interacting with AWS via Python. https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

Need to first install:

pip3 install boto3
Lots of examples are out there but they are not yours unless you get it to work for you. So to get started you need an AWS account, and credentials be setup in your local machine. https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

So I have a couple files on S3 in a bucket, and I can retrieve them. Sometimes boto3 is better than other languages because sometimes other languages such as Java may be more clumsy.

import boto3
from botocore.exceptions import ClientError

def getContentInBucket(s3_client, bucketName):
   result = s3_client.list_objects(Bucket = bucketName, Prefix='')
   for o in result.get('Contents'):
      print("fileName: "+o.get('Key'))
      data = s3_client.get_object(Bucket=bucketName, Key=o.get('Key'))
      contents = data['Body'].read()
      print(contents.decode("utf-8"))

# To get list of buckets present in AWS using S3 client
def get_buckets_client(s3_client):
   try:
      response = s3_client.list_buckets()
   
      for bucket in response['Buckets']:
         bucketName = bucket["Name"]
         print("bucketName: "+bucketName)
         getContentInBucket(s3_client, bucketName)

   except ClientError:
      print("Couldn't get buckets.")
      raise
   
session = boto3.session.Session()

# User can pass customized access key, secret_key and token as well
# credentials are set in my .aws/credentials file
# See https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
s3_client = session.client('s3')

get_buckets_client(s3_client);

Monday, November 11, 2024

MathJax

HTML is nice but hard to type math stuff like fractions and equations... how can math things be shown on a webpage? Sure people can use powerful equation editors nowadays to generate PDFs. Traditionally math text are typeset by Tex/LaTex. And with MathJax you can now turn that into webpage:
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
becomes $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$ Tex/LaTex however has a bit of learning curve. There are tutorials out there. But now there is WYSIWYG editor too: https://latexeditor.lagrida.com/

You an also use Jupyter Notebook to type equations in similar ways and also run Python right on it too. So if you have math things to tell, now it is easier to display your equations and data charts etc.

Thursday, October 31, 2024

Angular revisited

I haven't looked at Angular in a long time... it is still complex. Requires getting node.js and downloading its CLI to generate skeletons first. Then jam your html into your template section of your components, while making sure you import the right things. If you just look at code, it is hard to tell what is generated and what is to be inserted by hand. Dude, this is too complex to be effective. Even React is a little simpler.

Official tutorials are followable... but not step-by-step from scratch. You start with some existing things or play on the browser in these tutorials. Typescript: If you do want types, why don't you go to Java/C++ and and instead compile into javascript? The "beauty" of javascript is lack of types, less to worry about. It was intended to be quick-and-dirty. Whole Angular is too complex if you ask me, as need to generate so many things. This isn't straight forward enough. It isn't so elegant to integrate javascript and html... HTML entirely within backquotes inside components.

It is almost impossible to use Angular without Visual Studio Code and its plugings. Someone should make an IDE, with a good editor. New->Component, boom, call that "ng generate component" behind the scene. No one needs to learn another CLI.

https://angular.dev/tutorials/learn-angular
https://angular.dev/tutorials/first-app

Good luck if you must use it.

Wednesday, September 18, 2024

Java ScheduledExecutorService

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ConcurrentStuff {

	  public static void main(String[] args) {
	    System.out.println("begin");
	    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

	    System.out.println("scheduling a task to run after 2 seconds");
	    // Schedule a task to run after a delay of 2 seconds
	    executor.schedule(new MyTask(), 2, TimeUnit.SECONDS);

	    System.out.println("scheduling a task to delay 3 seconds then repeat every 5 seconds");
	    // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds
	    executor.scheduleAtFixedRate(new MyTask(), 3, 5, TimeUnit.SECONDS);

	    // Wait for scheduled tasks to complete
	    try {
	      System.out.println("sleeping to demo scheduling at work");
	      Thread.sleep(15000);
	    } catch (InterruptedException e) {
	      e.printStackTrace();
	    }

	    // Shutdown the executor
	    executor.shutdown();
	    System.out.println("end");
	  }

	  static class MyTask implements Runnable {
	    @Override
	    public void run() {
	      System.out.println("Task executed at: " + new java.util.Date());
	    }
	  }
}

Sunday, September 15, 2024

Determinant of a matrix

This little program calculates the determinant of an matrix.. using recursion. You don't even need ad - bc for a 2x2 [[a b][c d]] https://en.wikipedia.org/wiki/Determinant

public class CodeWar {

	public static int[][] buildSubmatrix(int[][] matrix, int r, int c) {
		int size = matrix.length - 1;
		int result[][] = new int[size][size];
		int a = 0, b = 0;

		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix.length; j++) {
				if (i != 0 && j != c) {
					result[a][b] = matrix[i][j];
					b++;
				}
			}
			if (i != r) {
				a++;
				b = 0;
			}
		}
		return result;
	}


	public static int determinant(int[][] matrix) {
		if (matrix.length == 1)
			return matrix[0][0];

		int sign = 1;
		int sum = 0;
		for (int i = 0; i < matrix[0].length; i++) {
			int n = matrix[0][i];
			int submatrix[][] = buildSubmatrix(matrix, 0,i);
			sum += sign * n * determinant(submatrix);

			sign = sign * -1;
		}
		return sum;

	}

	public static void main(String arg[]) {
		int[][] matrix = { 
				{ -2, -1,2 }, 
				{ 2,1,4 }, 
				{ -3,3,1 } };
		System.out.println(determinant(matrix));
	}
}

Tuesday, August 20, 2024

Java: of list and set

There are multiple ways to construct a list in java. (easier in python and other languages). To eliminate duplicates, you can use the stream distinct, or put it in a set (HashSet or LinkedHashSet to retain order) then make it back to a list.
	public static void main(String arg[]) {
		
		String a[] = new String[] { "A", "B", "C", "D", "A", "C", "E" };
        List<String> list = Arrays.asList(a);  // constructed one way
        List<String> list2 = List.of(a); // constructed another way (java 9+)
        List<String> list3 = List.of( "A", "B", "C", "D", "A", "C", "E" ); // yet another way 

        // using stream distinct one way
        List<String> noDups = list.stream().distinct().collect(Collectors.toList());
        // using stream distinct another way
        List<String> noDups2 = list2.stream().distinct().toList();
        
        // put on a set and make a iist out of it
        Set<String> set = new LinkedHashSet<>(); 
        set.addAll(list3); 
        List<String> noDups3 = new ArrayList<>(set);
        
        System.out.println(noDups);
        System.out.println(noDups2);
        System.out.println(noDups3);
	}

Wednesday, July 24, 2024

Python linear 2x2 system

This is a fun tool for any algebra 1 student. Solve a 2x2 linear system, and graph it.
import matplotlib.pyplot as plt
import numpy as np
import math

"""
Simple little 2x2 system example:
 x + 2y = 1
 3x + 5y = 2
 
 This can be written as matrix form [A][x] = [B]:
 
 [1 2][x] =  [1]
 [3 5][y]    [2]
"""
A = np.array([[1, 2], 
              [3, 5]])
B = np.array([1, 2])

XMIN, XMAX = -5, 5
YMIN, YMAX = -5, 5
GRIDSIZE = 1

STEPS = 101


a11 = A[0][0];
a12 = A[0][1];
a21 = A[1][0];
a22 = A[1][1];
b11 = B[0];
b12 = B[1];

def f(x):
    return (-a11*x+b11)/a12

def g(x):
    return (-a21*x+b12)/a22

x = np.linspace(XMIN,XMAX,STEPS)
plt.axis([XMIN,XMAX,YMIN,YMAX]) 

y1v = np.zeros(len(x))
y2v = np.zeros(len(x))
for i in range(len(x)):
    try: 
        y1v[i] = f(x[i])
        y2v[i] = g(x[i])
    except:
        pass

try:
    solution = np.linalg.solve(A, B)
    print("Solution")
    print(solution)
    solutionpoint =  "(${0:.2f}, ${1:.2f})".format(solution[0], solution[1]);
    plt.plot(solution[0],solution[1],'bo'); # blue circle
    plt.annotate( solutionpoint,(solution[0],solution[1]));
except:
    print("No solution")
    
eq1 = "{0}x+{1}y={2}".format(a11,a12,b11);
eq2 = "{0}x+{1}y={2}".format(a21,a22,b12);
plt.plot(x,y1v, color='r',label=eq1)
plt.plot(x,y2v, color='g',label=eq2)


# make axes
plt.axhline(y=0, color='k') # 'k' means black
plt.axvline(x=0, color='k')
# gca is get current axes 
plt.gca().set_aspect('equal')
plt.gca().set_xticks(np.arange(XMIN,XMAX,GRIDSIZE))
plt.gca().set_yticks(np.arange(YMIN,YMAX,GRIDSIZE))
plt.grid(True)
plt.legend() 
plt.show()


Monday, July 22, 2024

Python linear algebra

Every algebra 1 student should learn about solving a system of 2 equations and 2 unknowns. Then they will learn about 3 by 3... then gosh n by n. There is gotta be easier way to do this than combining equations, well yes there is, enter linear algebra. But solving a linear system of equation is still hard to do by hand, painful to punch it on your calculator too. Enter computer programming! Python can effortless do this with the Numpy library. Programming this from scratch is not a very pleasant programming task.
import numpy as np
 
"""
Simple little 2x2 system example:
 x + 2y = 1
 3x + 5y = 2
 
 This can be written as matrix form [A][x] = [B]:
 
 [1 2][x] =  [1]
 [3 5][y]    [2]
 
 
 So the solution is inv(A)B
 
 Inverse matrix is painful to do by hand, but numpy can do it easy,
 It even has a solve method
 """
 
A = np.array([[1, 2], 
              [3, 5]])
B = np.array([1, 2])

Ainv = np.linalg.inv(A)
solution = np.matmul(Ainv,B)
print("Solution by multiply inverse: ")
print(solution)

solution2 = np.linalg.solve(A, B)
print("Solution by linalg solve: ")
print(solution2)

Output:
Solution by multiply inverse matrix and right hand side: 
[-1.  1.]
or by linalg solve: 
[-1.  1.]
That means x=-1, y =1.

Wednesday, July 3, 2024

Python Simple Graphing (part 2)

With the little program from my previous post, I thought I could graph any function I passed to it? Let me try something a little more fancy like sin(x). I tried the following and got error
import matplotlib.pyplot as plt
import numpy as np
import math


def f(x):
    return math.sin(x)

# using 101 steps so I know I get to 0
x = np.linspace(-5,5,101)

plt.plot(x,f(x))
plt.show()
Error is "TypeError: only length-1 arrays can be converted to Python scalars". What??

Oh that's because this plt.plot() method really takes 2 arrays, the x values and the y values.

The following works better

import matplotlib.pyplot as plt
import numpy as np
import math


def f(x):
    return math.sin(x)

# using 101 steps so I know I get to 0
x = np.linspace(-5,5,101)

yv = np.zeros(len(x))
for i in range(len(x)):
    yv[i] = f(x[i])

plt.plot(x,yv)

plt.show()
This works a little better but I like axes and grids and properly scaled graph!

Ok after a little researching here we go:

import matplotlib.pyplot as plt
import numpy as np
import math

XMIN, XMAX = -5, 5
YMIN, YMAX = -5, 5
GRIDSIZE = 1

STEPS = 101


def f(x):
    return math.sin(x)


# using odd steps so I know I get to 0
x = np.linspace(XMIN,XMAX,STEPS)
plt.axis([XMIN,XMAX,YMIN,YMAX]) 

plt.title('my graph')

yv = np.zeros(len(x))
for i in range(len(x)):
    yv[i] = f(x[i])

plt.plot(x,yv)

# make axes
plt.axhline(y=0, color='k') # 'k' means black
plt.axvline(x=0, color='k')
# gca is get current axes 
plt.gca().set_aspect('equal')
plt.gca().set_xticks(np.arange(XMIN,XMAX,GRIDSIZE))
plt.gca().set_yticks(np.arange(YMIN,YMAX,GRIDSIZE))
plt.grid(True)

plt.show()

Monday, June 10, 2024

Python simple graphing

Pyplot lets you easily make a graph: https://matplotlib.org/stable/tutorials/pyplot.html. Lots of options here.

You first need to install it:.

pip3 install matplotlib

Here is some simple code. x range from -5,5. plot y=x2+1

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,5,0.1)
y = x*x+1
plt.plot(x,y)
plt.show()
Although this works but it seems wacky scale.

And let me try some other function, let's give it tricky function y=1/x: Eeew this is ugly (and wrong)

This can be fixed if I change x to x = np.linspace(-5,5,100). See documentation here: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

But eew, it is not what I expect it to do at x=0? First do a step with odd number so you know 0 gets evaluated, then make your function a little method, and have an extra with statement to ignore bad output

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    with np.errstate(divide='ignore', invalid='ignore'):
        return 1/x

# using 101 steps so I know I get to 0
x = np.linspace(-5,5,101)

plt.plot(x,f(x))
plt.show()

Ok a few lines give you much functionality... but less than super smooth if you ask me... There are many ways to supply that x range. and many ways to tweak graph like add axes, colors, labels, etc.

Monday, May 20, 2024

Python OOP: a quick look

Ok let's make a simple class in Python... a constructor with a couple fields. A car with a couple attributes.
class Car:
    def __init__(self, name):
        self.name=name
    make=""
    model=""
Do I need to define some private fields first and do some get/set stuff, and then get tired of it and use lombok? No you don't. Do I even need pre-define my variables in constructor? No I don't because you define variables on the fly in Python. Ok I put it in a file Car.py. How do I load it in the prompt?
import Car
. Ok it let me. but how about
 mycar = Car("mycar") 
boom get an error. I need to do
from Car import *
Ok did that now I can do mycar("mycar"). Ok let's set some make and models.
mycar.make="Toyota"
mycar.model="Corolla"
So far so good. What about setting an undefined field like this?
 mycar.year=2020
Oh no errors, it let you do it! I guess I have to get used to the define variables and even fields on the fly. So you better make sure you type correctly. Waita minute, no public, private, protected? Did any OO aficiondos jump forward to blast Python? Is there things like reflective api to figure out what fields you have? There is this
dir(mycar)
to tells me what fields I have. "dir" is so DOS! There is a neato
vars(mycar)
to tell me what fields and values I got so far.

Ok, inheritance, no interface and "implements" vs "extends" differences as in Java. How about "abstract" as in C++? (There is. It is called the ABC) Oh you can even do multiple inheritance! (not worrying about the diamond problem here). What about static (instance) stuff? Yes there is. The variables on the constructor are instance attributes and those outside are class attributes. This is like a lot simpler (but is it better?) than other languages. Typos can be hairpulling as you can define variables on the fly.

Let me add a little method to make it tell me what we have

def showinfo() :
        print ("Car "+ name+" is a "+make+" "+model)
Boom it does not work!
>>> mycar.showinfo()
Traceback (most recent call last):
  File "<stdin>", line 1, in 
TypeError: showinfo() takes 0 positional arguments but 1 was given
What do you mean 1 was given, I didn't give you any arguments! (now that's an argument with the intepreter). and it turns out it needs a "self" argument. It does not know about itself! This worked:
def showinfo(self):
    print ("Car "+self.name+" is a "+self.make+" "+self.model)
Now to call it it is still mycar.showinfo(), no argument passed. Also, "self" is not a reserved word like "this" in C++/java, (or "self" or "me" like other languages). Anything goes but required. This also worked:
def showinfo(foofoo):
    print ("Car "+foofoo.name+" is a "+foofoo.make+" "+foofoo.model)
You just have to provide a dummy variable here. Jeez now that's wacky. I already tolerated the required tabs instead of blocks.

Plenty of tutorials about OOP out there such as this https://realpython.com/python3-object-oriented-programming/.

Thursday, May 9, 2024

Python revisited: a little web app

Python interpreter is a little read-eval-print loop. You can play with it without downloading anything, such as https://www.online-python.com/. But all you do is console stuff... Every tutorial just tells you how to use its data types, how do do loops and lists/tuples and so on... How about something more exciting like web app? BTW, nobody seems to be concerned about tab exactness or declaring your variables before use (like most other languages). Every programmer needs to know a thing or two about Python these days. You will need a little more than the interpreter to do a web app.

Enter Flask. Plenty of tutorials out there and many give you full-blown apps. I'm like come on, start with basics first?

First it needs to be installed.

On my computer (Mac), I have "pip3" (package installer for python) so I ran

pip3 install flask --upgrade
Then I have a little code like this:

from flask import Flask, render_template
app = Flask(__name__)

@app.get("/")
def index():
    return "this is home"

@app.get("/page1")
def page1():
   return "<h1>hello</h1><br/>This is like a <i>servlet</i>"
   
@app.get("/page2")
def page2():
    return render_template("mypage.html",name="Johnny")

if __name__=="__main__":
    app.run()

This gives you 3 pages, the main page "/", "/page1", and "/page2"

This is the local url: http://127.0.0.1:5000/

And python warned me this is just a development server, a toy.

The first two methods are straightforward... you have to punch in html that you are returning. Mixing html and code is nightmare from the original java servlet days like 1990s. It is hard to do a full blown web page even with the triple quote Python string isn't it?

The 3rd method is loading a templated file, which resides in my "templates" folder, it can take variables from the caller too:

mypage.html looks like this:

<h1>Hi {{name}}</h1>

This is a <i>simple</i>, but dynamic HTML page.
<p/>
{% for i in range(5) %}
  This is like jsp<br/>
{% endfor %}

This template file is html intermixed with code. and you can have loops and stuff too! Intermixing html and code can be difficult to maintain. This reminds me of Java Server Pages (which I think nobody uses nowadays)

This is a very simple example. Simple examples work better than complex examples for beginners. And that endfor above tells you that blocks are actually good thing.

Wednesday, May 1, 2024

Math Notes: Parabola

When you graph a quadratic equation in the standard form of y = ax2 + bx + c, where a, b, c are constants and a ≠ 0. You will get a parabola. When you throw a basketball up in the air its path is also a parabola as gravity formula work that way. The simplest parabola is y = x2

The graph looks like this. You can simply plug some points to see the curve of the graph. Or pull out your graphing calculator:

There is a minimum or maximum y value for a parabola, at a point called the vertex. In this parabola the vertex at (0,0). If a is negative you have a upside-down parabola.

If you rewrite the equation in this vertex form: y = a(x-h)2+k, you have a parabola with vertex on (h,k).

Finding the vertex

Given the standard form, the x-coordinate of the vertex is given by

x = -b/2a

This is a result of the quadratic formula. x = -b/2a is exactly in the middle of the 2 solutions and is the x-coordinate of the vertex. For the y-coordinate, just plug the x coordinate in and solve for y.

[Insert Example]

The parabola actually has an geometric definition, defined based on a straight line (called the directrix) and a point (called the focus).

Definition A parabola is the set of all the points equal distant from a focus point to the directrix line.

Let d be the common distance from the focus to the parabola and from the parabola to the directrix line. The vertex is an obvious point on the parabola, on the line of symmetry, exactly in the middle between the focus and the directrix with d here being the smallest. Let's call this distance f, the focal length.

The focal length determines the shape of the parabola. The distance from the vertex to the focus is f. From the vertex to the directrix is also f.

For simplicity, let the directrix be at y = -f and focus at (0,f). and freeze one frame for a moment at any P at (x,y).

[insert picture]

Then the vertical red line has length of y + f. Then from P to the Focus, by the distance formula, the length is sqrt( (y - a)2 + x2). They must be equal:

sqrt( (y - f)2 + x2) = y + f
(y - f)2 + x2 = (y + f)2
y2 - 2fy + f 2 + x2 = y2 + 2fy + f 2

The y2 and f 2 cancel, bring the - 2fy to the right hand side, leaving:

x2 = 4 f y

Or
y = 1/(4f) x2

in form of y=f(x). You can find the focal length f given the a in the standard form.

Latus Rectum

The latus rectum is the line segment parallel to the directrix that goes through the focus with endpoints on the parabola.

And the length of the latus rectum is 4f. Here is why:

At the right endpoint of the latus rectum, y = f. Let's solve for x so we know half the length of the latus rectum. Plug that in: x2 = 4f 2. So x = 2f. The right endpoint is (2f,f). The left endpoint is (-2f, f). So length of the latus rectum is 4f.

Vertex-Focal Length Form

The equation y = 1/(4f) x2 is the simple case where the vertex at (0,0). For general case, the vertex at (h,k) form is:

(x - h)2 = ± 4 f (y - k)
This is a parabola that opens up or down. Parabola that opens sideways (not a function!) you just switch the x and y.
(y - h)2 = ± 4 f (x - k)
In the top form, the ± sign is there to differentiate between parabola that opens up (positive) or opens down (negative). In the bottom form, parabola opens to the right is positive, and to the left it is negative.

When you are given a parabola in standard form, it is only straight forward to find the x-coordinate of the vertex which is x = -b/2a. It is not so straight forward to find the focus or the directrix.

However, you can rewrite the standard form into the vertex form (by completing square), so you can read off both coordinates of the vertex (h, k) and calculate the focal length f. With the focal length, you can find the directrix line and the focus point, which is just a focal length away from the vertex. The x-coordinate of the focus will be same as the vertex's x-coordinate. Each end of the latus rectum is 2 focal lengths away from the focus, with same y-coordinate as the focus.

[Insert Example]

Monday, March 25, 2024

java Timer

A simple program to schedule sonething in the future.
import java.util.TimerTask;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Timer;

class HelloWorld {

	private static class MyTimerTask extends TimerTask {

		String someValue;

		MyTimerTask(String someValue) {
			this.someValue = someValue;
		}

		@Override
		public void run() {
			System.out.println("Timer run " + someValue);
		}
	}

	public static void main(String[] args) {

		HelloWorld me = new HelloWorld();
		LocalDateTime someTimeLater = LocalDateTime.now().plusSeconds(3);

		Date futureDate1 = Date.from(someTimeLater.atZone(ZoneId.systemDefault()).toInstant());

		System.out.println("Scheduling something to be run in future...");

		new Timer().schedule(new MyTimerTask("hello my friend"), futureDate1);

		System.out.println("going on with my life");

	}

}

Saturday, January 27, 2024

How many diagonals does a polygon have?

I came across another problem I never learned how to solve... how many diagonals does a 13-gon have?

Geez, I nerver learned the formula of how many diagonals in a polygon, let's see if I can derive on the fly.. Start with the triangle. nope, no diagonals. The square: 2. The pentagon: 5. The hexagon: 9. It is kinda hard to draw and count bigger ones. So I have a f(3)=0, f(4)=2, f(5)=5, f(6)=9.. and yikes I can't easily obsere a pattern and derive this formula on the fly.

But I kinda observe, something to do with n-2... because can't connect a point to its neighbors and call it diagonal... and sadly I have to give up and look the formula up. Yes I admit.

And it takes I think a bit genius to reach this observation:

The nunber of diagonals is simply number of segments connecting every pair of points, EXCEPT the edges of the polygon.

So it is the Combination n choose 2, minus n: nC2 - n

    n! 
---------  - n
 2! (n-2)!


  n (n-1)
= ------- - n
    2

= n^2-n - 2n
  ----------
     2

= n^2 - 3n
  --------
     2
     
= n(n-3)
  ------
    2
So there are 13(13-3)/2 = 65 diagonals for the 13-gon.

This formula n(n-3)/2 I'd keep it in my treasure chest where I put other not-so-obvious formulas like volumne/surface area of a sphere, volume of a pyramid, etc.

Waita minute, although my initial observation is not going anywhere but somewhat of a good start. For each point on the polygon, do not count the 2 neighbors including the point itself, so n-3 diagonals for each point. Go around each point of the polygon, so it is n(n-3), but by that time you would have counted twice the number of diagonals, so divide by 2. There you are: n(n-3)/2.