Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, 11 May 2020

Print Templated String in Python

Python 3.6+ has the new 'f' string prefix to use in place of the .format function for string, it is neat and useful.

Prior to Python 3.6:

Foo = "bar";
print("Foo value is {}".format(Foo));

Python 3.6+:

Foo = "bar";
print(f"Foo value is {Foo}");

Try it on:
https://repl.it/languages/python3

How to Do Coding on Android

Some may say coding on Android is nonsense, but it's wrong. Coding on Android can be done as usual, but not the tiny display on mobile device; install BlueStacks and one of these code editors:

Thursday, 7 May 2020

JavaScript and How It Is Not Much Related to Java

JavaScript was created in 1995 at the beginning of Internet era. It is called JavaScript because it was first created using all Java keywords, but the 2 languages are totally different, one is threaded, one is event-based.

JavaScript has evolved much, and with ES6 (ECMAScript6), JavaScript comes with threading, and classes too.

Example class in ES6 (the file name must be .mjs):
class some_class {
  Some_Property = null;
  
  some_function(Some_Param){
  }

  static some_static_function(Some_Param){
  }

  async some_function2(Some_Param){
  }

  static async some_static_function2(Some_Param){
  }
}

//Static block for static properties
{
  some_class.Some_Static_Prop = null;
}

//ES6 export
export default some_class;
//EOF

Import class to use:
//Static import
import some_class from "./some_class.mjs";

//Dynamic import
(async function(){
  var some_class = await import("./some_class.mjs").default;
})();

Run Node.js with ES6 and multi-threading:
node --experimental-modules --experimental-worker \
app.js

Add the 'require' function to ES6:
npm install mjs-require --save
node --experimental-modules --experimental-worker -r mjs-require \
app.js

Run Node.js ES6 with heredoc in Bash:
node --experimental-modules --experimental-worker \
--input-type module <<'HEREDOC'
  console.log(Date.now());
HEREDOC

Wednesday, 6 May 2020

Get the Selector for Using with Stylish Extension (userstyles.org) to Customise Websites

Many websites may not look suitable with personal style, the Chrome extension called Stylish can help browser users customise any CSS.

Get the CSS selector directly for an HTML element:
1) Right-click on the UI element on web page, choose 'Inspect'
2) DevTools panel is opened, right-click on highlighted tag, choose 'Copy > Copy selector' 
3) Create or edit a Stylish style
4) Paste the selector and enter CSS properties

However, many websites/webapps use generated element ids and class names, the CSS selector above won't work when these websites are built (daily for example) and deployed. Use the XPath solution below.

Get the CSS selector by converting XPath to CSS selector:
1) Right-click on the UI element on web page, choose 'Inspect'
2a) DevTools panel is opened, right-click on highlighted tag, choose 'Copy > Copy full XPath
2b) Open website toolset.sh, there's a tool there to convert XPath to CSS selector
3) Create or edit a Stylish style
4) Paste the selector and enter CSS properties

Thursday, 16 April 2020

Minimal Files for a Proper Progressive Web App (PWA)

All 3 files below must be served from HTTPS.

Web contents
app.html:
<!DOCTYPE html>
<html>
  <head>
    <title>App</title>
    <link rel="manifest" href="manifest.json"/>
  </head>
  <body>
    body-contents
  </body>
</html>
<!--EOF-->

Configurations
manifest.json:
{
  "name":       "My App",
  "short_name": "My App",
  "start_url":  "app.html",
  "display":    "standalone",

  "icons": [
    {
      "src":   "/pwa/icon144.png",
      "type":  "image/png",
      "sizes": "144x144"
    }
  ]
}

At least 1 icon (must be 144 on Vivaldi)
and the real image size must be 144x144 too:
icon144.png

Wednesday, 12 February 2020

Fortran & Lisp: The First High-level Structured Language and Functional Language

Fortran: The first high-level structured language
program bubble_test

  implicit none
  integer, dimension(6) :: vec 
  integer :: temp, bubble, lsup, j

  read *, vec !the user needs to put 6 values on the array
  lsup = 6 !lsup is the size of the array to be used

  do while (lsup > 1)
    bubble = 0 !bubble in the greatest element out of order
    do j = 1, (lsup-1)
      if (vec(j) > vec(j+1)) then
        temp = vec(j)
        vec(j) = vec(j+1)
        vec(j+1) = temp
        bubble = j
      endif 
    enddo
    lsup = bubble   
  enddo   
  print *, vec
end program
Lisp: The  first high-level functional language
(defun bubble-sort (lst)
  (loop repeat (1- (length lst)) do
    (loop for ls on lst while (rest ls) do
      (when (> (first ls) (second ls))
        (rotatef (first ls) (second ls)))))
  lst)

Free GPU-enabled General Programming and ML Services

Google Colab:
  • https://colab.research.google.com
  • Pros:
    • Free GPU time
    • Save documents to Google Drive
    • Document outline (headings) available on UI
    • Run any language using %%writefile and %%script bash
    • Install anything with sudo apt install
    • Anything! basically it's a server without public ports
  • Cons:
    • No file manager side panel
    • No opened file tabs
    • Session is not persistent, opening .ipynb files will lead to random environment without previous saved files.
    • No public ports
    • No terminal
Paperspace Gradient:
  • https://paperspace.com
  • Pros:
    • Free GPU time
    • Save documents to the Docker container (or VM?) itself
    • Create/open/run any file, not just %%writefile and %%script bash in .ipynb files
    • Install anything with sudo apt install
    • It's a private server without public ports
    • Persistent saved files, persistent environment, open Gradient again with the same opened file tabs
    • Based on JupyterLab, file manager available, opened file tabs
    • Terminal default in 'sh' but run 'bash' to have Bash terminal
    • Anything! basically it's a persistent server without public ports
  • Cons:
    • No public ports
    • Can't save to Google Drive
    • No .ipynb document outline (headings)

Monday, 3 February 2020

C/C++ Macro Fun

Run on Colab:
https://colab.research.google.com/drive/1yYp77nAn1tFSmehgtLeKcGgx72YNH2Nq

Source Code:
%%writefile test.cpp

#include <iostream>

#define happy     using namespace std;
#define neww      int main(int Argc,char* Args[]){
#define year      cout <<"Happy new year, everybody!" <<endl;
#define everybody }

happy
neww
year
everybody
//EOF

Result:
Happy new year, everybody!

Sunday, 2 February 2020

Google Blockly Visual Programming with Bubble Sort Example

Google Blockly is a visual programming library. It is fun to try with, and fun for kids, but not for production use as developing something with it is slower than typing and not complex enough to make applications.

An example Blockly bubble sort is here:
https://blockly-demo.appspot.com/static/demos/code/index.html#bfen2c

Screenshot:

Generated Python source code:
import random

List  = None
I     = None
J     = None
Left  = None
Right = None

List = [random.randint(1,100),random.randint(1,100),random.randint(1,100)]
I    = 1

while I < len(List):
  J = I + 1

  while J <= len(List):
    Left  = List[int(I - 1)]
    Right = List[int(J - 1)]

    if Left > Right:
      List[int(I - 1)] = Right
      List[int(J - 1)] = Left

    J = J + 1
  #End J

  I = I + 1
#End I

print(List[0])
print(List[1])
print(List[2])

Friday, 31 January 2020

CRLF on Various Systems and Web Programming

Carriage Return (CR) and Line Feed (LF) are common character in computer programming. Different systems use them differently.

CRLF = 0D,0A = 13,10 = \r\n

New line on different systems:
  • Windows: \r\n
  • Mac: \r
  • Linux: \n
  • HTML textarea tag: \n
  • expect: \r
Check JavaScript event Enter key

HTML ('event' is lower case to work in Firefox):
<input onkeyup="check_enter(event);"/>

JS code:
function check_enter(Event){
  if (Event.keyCode==13)
    console.log("Enter key pressed");
}

Wednesday, 22 January 2020

Lambda Expression and Lambda Function in Python, JavaScript (also Node.js)

Lambda expression and lambda function in programming are no-name (anonymous). Both Python and JavaScript (also Node.js) have this feature.

Example utility function:
f = x^2 + x + 1

Example lambda expression in Python:
F = lambda X: f(X);

Example lambda function in Python, note the commas and no 'return':
F = lambda X: (
  statement1,
  statement2,
  Result
);

Example lambda expression in JavaScript:
F = X => f(X);

Example lambda function in JavaScript, note the semicolons and 'return':
F = X => {
  statement1;
  statement2; 
  return Result;
};

Generate a function with constant C in Python:
F = (lambda T: lambda X: f(X)+C)(C);

Generate a function with constant C in JavaScript:
F = (C => X => f(X)+C)(C);

Generate Functions with Different Constants in Python, JS

Source Code (Python):
#Any function
def f(X):
return X**2;

#Constants for generating functions
Ts = [1,2,3];

#Generate functions
Fs = [(lambda X,T=T: f(X)+T) for T in Ts];

#Call generated functions with default constants
print(Fs[0](3));
print(Fs[1](3));
print(Fs[2](3));

#Call generated functions with specific constants
print(Fs[0](3,1));
print(Fs[1](3,2));
print(Fs[2](3,3));
#EOF

Result:
10
11
12
10
11
12

Source Code (JavaScript, Node.js):
//Shortcuts
log = console.log;

//Any function
function f(X){
return X*X;
}

//Constants to generate functions
Ts = [1,2,3];
Fs = [];

//Function generator loop
for (I in Ts) { //Get index list
..T = Ts[I];
..F = (T => { //A function instance
....return function(X){
......return f(X)+T;
....}
..})(T);
..Fs.push(F);
}

//Test generated functions
log(Fs[0](3));
log(Fs[1](3));
log(Fs[2](3));
//EOF

Result:
The same

Wednesday, 8 January 2020

3D Programming in Web Browser

Modern browsers support WebGL and WebAssembly. These new technologies enable 3D embeds in HTML5 canvas.

3D applications, games in browser canvas:
  • Solution 1:
    • Programming language: JavaScript
    • Graphics technology: WebGL
    • Draw into canvas
  • Solution 2:
    • Programming language: C++ (compile to WebAssembly)
    • Graphics technology: OpenGL
    • Draw into canvas

Friday, 3 January 2020

History of Types in C/C++

16-bit Machines (Max 32-bit):
Note: short and int are the same, float is 16-bit
  • char        8-bit
  • short       16-bit
  • int         16-bit
  • long        32-bit (Max)
  • long long   No such type
  • float       16-bit
  • double      32-bit (Max)
  • long double No such type
32-bit Machines (Max 64-bit):
Note: int and long are the same, float is 32-bit
  • char        8-bit
  • short       16-bit
  • int         32-bit
  • long        32-bit
  • long long   64-bit (Max)
  • float       32-bit
  • double      64-bit (Max)
  • long double No such type
64-bit Machines (Max 128 bit):
Note: int is 32-bit, long is 64-bit, long double is added
  • char        8-bit
  • short       16-bit
  • int         32-bit
  • long        64-bit
  • long long   128-bit (Max)
  • float       32-bit
  • double      64-bit
  • long double 128-bit (Max)

Wednesday, 25 December 2019

Embed Programming for Browser

Browser embed programming (not embedded programming that is ASIC programming) for browser can be these presently:
  • ActiveX (Windows only, dead technology)
  • Java Applet (disabled by all browsers, dead technology)
  • Flash (disabled by all browsers, dead technology)
  • Canvas (programmed with JavaScript, recommended technology)
  • WebAssembly (programmed with any programming language)
Canvas is recommended, WebAssembly is useful when porting applications from mobile, desktop to browser by compiling C/C++ into WebAssembly so the apps won't need to be coded twice.

How Should Google V8 JIT Compiler Compile Better

Node.js (JavaScript) is a very convenient programming language but it has a drawback: It's a non-typed language.

Google V8 is a JIT (Just-in-Time) compiler that compiles JS code to native code. However, JS is non-typed language so for primitive variables, the compiled code has to look-up for variables all the times as primitive variables are stored as pointers instead of direct values.

How to solve the primitive pointer problem?
Google V8 should compile to typed binary code by automatically assign the types for variables when their values first set.

Automatic type assignment will lead to run-time error (not compile-time error) when changing the variable value to another type, but for good practice in programming, a variable should keep its type through out the programme.

With automatic type assignment, the compiled Node.js/Cython code will be as fast as C/C++. Oh mum, why hasn't Google done this?

Performance of Programming Languages

Generations of programming languages:
  1. Generation 1(A): Punched card (Binary)
  2. Generation 2(B): Assembly (Text)
  3. Generation 3(C): High-level (Text, eg. C, Pascal)
  4. Generation 4(D): High-level with OOP (Text, eg. C++, Pascal)
  5. Generation 5(E): High-level with OOP and markup (Text, eg. Qt-over-C++)
Performance of programming languages, the later the slower:
  1. Assembly (top performance, but labourious development)
  2. Typed languages, run natively on CPU (eg. C/C++) - Performance
    1. Compiler/JIT compiler (faster)
    2. Interpreter (slower)
  3. Typed languages, run on VM (eg. Java) - No points
    1. Compiler/JIT compiler (faster)
    2. Interpreter (slower)
  4. No-type languages, run natively on CPU (eg. Node.js, Cython) - Convenient
    1. Compiler/JIT compiler (faster)
    2. Interpreter (slower)
  5. No-type languages, run on VM (eg. Python) - AI and ML
    1. Compiler/JIT compiler (faster)
    2. Interpreter (slower)
There's most likely no languages nowadays that has interpreter to process code files directly; interpreters compile code files to bytecode, for example: .pyc is Python compiled bytecode to be run in Python virtual machine.