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());
	    }
	  }
}