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 dyanamic 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.

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.

Monday, December 18, 2023

Surface Area of a Cone

So I recently encountered a challenging math problem intended for an 8th grader. Find the surface area of a frustum. That is, a circus elephant stand or a bucket. Given the circumference of the top and bottom and the height between.

Wow, that's a tough problem for an 8th grader and I am frustrated at this frustum problem because I never learned the formulas needed. It would be relatively straight forward if I know how to find the surface area of a cone but I don't know. Not that I forgot it but just never learned it, although I know how to find the volume of a cone. That 1/3 base * height formula is actually not exactly straight forward to derive either. I know these formulas are not so useful in life, I know. But the spirit of math should be: if there is an answer find the answer.

Nowadays it is easy to look up the formula. Note the cone has the side and the bottom. The formula looks like this:

That looks a little intimidating. A cone is a paper cup. Surface area is the paper cup plus the bottom circle. The area of the paper cup is the "lateral surface area" and it is π r L, where r is the radius, and L is the slanted height. The slanted height L is also square root of h2 + r2, straight from the Pythagorean Theorem. Neat. So the formula above is area of the paper cup plus the area of the bottom circle. But where did this lateral area formula π r L come from. I looked up a few explanations and none provide satisfactory explanation. Allow me explain.

Now look at the paper cup. Imagine flattening it. It is a section of a circle. What is its radius? L.
What's the circumference of the big circle that the paper cup is part of? 2 π L.
What's its area? π L 2.
But we are interested in the section, the paper cup. Geez I'll need the angle but I don't know.
But I do know its rim's length. That would be the circumference of the bottom of the cone: π r2.
Then the paper cup's area is a fraction of the big circle's area π L 2.
The fraction is rim over entire circumference, which is π r2 over 2 π L. Multiply it out, many things cancel, and then you will get π r L. See, if the cone is entirely flat, then r=L it is just π r2.

Armed with this lateral cone area formula π r L, there is still a bit of calculation to find surface area of a frustum, which is top and bottom circle area. Plus the difference of lateral area of bigger cone and smaller cone. First I'll need the height of the cone which takes a bit of work with similar triangles to find out.

But the point is this: Do not ever just tell kids to use formulas, derive them! Deriving formula is learning math. Using the formula is applying math. Plugging in numbers in a formula which you don't know where it came is lowest form of math.