Showing posts with label Miscellaneous. Show all posts
Showing posts with label Miscellaneous. 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:

Friday, 8 May 2020

Quick Setup for CentOS and Ubuntu Servers

The website toolset.sh provides quick setup scripts for CentOS and Ubuntu with essential software installation. It is useful when in need of setting up multiple servers with the same basic packages.

Install generic tools:
curl toolset.sh | bash

Install classic tools:
curl toolset.sh/classic | bash

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

How to Enable 'Administrator' Account on Windows 10 or Set Its Password

The 'Administrator' account is not enabled by default on Windows 10 but it is necessary sometimes. Use the following steps to enable 'Administrator' account and set a password for it.

1) List out Windows accounts
Right-click on 'cmd', choose 'More' >> 'Run as administrator'

Type this command to see available users:
net user

2) Enable 'Administrator' account on log-on screen
Type this command in cmd:
net user administrator /active:yes

3) See updated info the the user 'Administrator'
Type this command:
net user administrator

4) Set password for 'Administrator' account:
Type this command:
net user administrator *

Note:
Change the 'yes' to 'no' in step 2 to disable 'Administrator' account.

Reference:

How to Disable Windows UAC (User Account Control) Using Registry (Regedit)

The new update from Windows 10 is rather annoying, it enables UAC password prompt every time, eg. when using 'Run as administrator' on right-click on some app, specially Steam Big Picture that needs to be 'administrator' to send keys and mouse signals to games.

Disable UAC using regedit:
1) Win+R
2) Type 'regedit', press Enter
3) Go to: HKEY_LOCAL_MACHINE > SOFTWARE > Microsoft > Windows > CurrentVersion > Policies > System
4) Right-click 'EnableLUA', click 'Modify'
5) Set the value to 0 (zero) instead of 1
6) Windows will prompt to restart to disable UAC
7) Click the notification to restart and enjoy!

Reference (Go to 'Way 2: Disable User Account Control on Windows 10 by Registry Editor', it's the only working one):

Monday, 4 May 2020

CSS nth-child versus nth-of-type

Consider this HTML structure:
<body>
  <div>foobar</div>
  <span>foo</span>
  <span>bar</span>
</body>

To select the last (the second) span using nth-child:
document.querySelector("body >span:nth-child(3)");

To select the last (the second) span using nth-of-type:
document.querySelector("body >span:nth-of-type(2)");

How to Add Custom CSS and JS Code to Any Website

Customise CSS in any website with Stylish

Create custom CSS for website:
1) Click Stylish extension icon on address bar
2) Click the triple-dot button on top-right corner
3) Click 'Create New Style'
4) Type CSS code in the main code box
5) Click 'Specify' button below, choose 'URLs on the domain', enter the website domain
6) On top-left corner, enter style name
7) Click 'Save' button
8) Open the website to see it customised.

Append additional JS to any website with Tampermonkey

Create additional JS for website:
1) Click Tampermonkey extension icon on address bar
2) Click 'Create a new script...'
3) Modify @name to any name
4) Modify @match URL to @include http://domain.name/*
5) Add @license MIT to top
6) Add new JS code into the self-exec function
7) Click Menu >> File >> Save
8) Open the website to see it with additional JS.

Online storage for Stylish:

Online storage for Tampermonkey:

Tuesday, 28 April 2020

Suggested Browsers for 2020

In the old days, the world had Netscape, Internet Explorer (now no more, replaced by Edge Legacy, then Edge), Opera, Mozilla (now as Firefox), some have not been lingering on.

Modern browsers of 2020:
  • Vivaldi (Recommended, with mouse gesture)
  • Chrome (Recommended, very popular)
  • Firefox (Recommended, with tabs in full screen, with 'Switch to New Tab' on mobile)
  • Edge (Recommended, Chromium-based, for downloading other browsers)
  • Edge Legacy (Recommended for downloading other browsers)
Headless browser by popularity:
  • Chrome
  • Chromium

Thursday, 23 April 2020

Tell Doxygen to Skip a Group of Lines

Doxygen documents all lines in a file, however, it's possible to tell Doxygen to ignore some lines when using qdoc commands to make descriptions for items.

Put this before to-be-ignored lines:
/*!\cond SOME_NON_EXISTING_DOXYGEN_VAR*/

Put this after those lines:
/*!\endcond*/

In full:
/*!\cond HIDE*/
CODE LINES HERE...
/*!\endcond*/

Saturday, 7 March 2020

HTTP Response Codes and Possible Failure Issues

HTTP response codes from 1xx to 5xx and their possible failure issues:

Out-going request:
  • Own server --> ISP proxies --> Customer proxy (Nginx) -->  Customer server
Inward request:
  • Customer server --> ISP proxies --> Own proxy (Nginx) --> Own server
1xx:
  • Exactly a response from server
  • No failures, informational response
2xx:
  • Exactly a response from server
  • Successful response from server
3xx:
  • Response from server or proxies
  • HTTP redirect
  • Possible issues:
    • Bad redirect by server, for example, infinite redirection
    • Bad redirect by proxies, for example, inifinite redirection
4xx:
  • Exactly a response from server
  • Error due to client request data
  • Possible issues:
    • Bad headers
    • Bad parameters in URL
    • Bad data in POST body
5xx:
  • Response from server or proxies
  • Error due to server side
  • Possible issues:
    • Server code error, exception, crash, etc.
    • Proxy (Nginx) fails to proxy_pass to a service
Timeout:
  • Target IP, domain, subdomain don't exist
  • Target machine having firewall that dropouts connections
  • No internet connection
  • Server doesn't respond
Reference:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Saturday, 15 February 2020

SSH Port Tunnelling Example

Run this command to tunnel server port SERVERPORT to localhost port LOCALPORT:
sudo ssh -L LOCALPORT:localhost:SERVERPORT myserver.com

For example, tunnel server port 80 to localhost port 8080:
sudo ssh -L 8080:localhost:80 myserver.com

Now, instead of opening:
http://myserver.com:80

Open:
http://localhost:8080

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)

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

Sunday, 26 January 2020

Minimal Yet Complete Dockerfile

1) Create a project directory
2) Create file 'build.sh' with commands to build Docker image
3) Create file 'start.sh' with commands to exec after image build

Note:
ravik694/c7-systemd-sshd is a good base Docker image to start from. It comes with systemd, sshd.

Dockerfile:
FROM ravik694/c7-systemd-sshd
COPY . /project
RUN  cd /project && bash build.sh
CMD  cd /project && bash start.sh

Saturday, 25 January 2020

Create and View HTML Files in Google Drive

HTML files can be created directly in Google Drive (https://drive.google.com) using these Google Drive apps:
  • Text Editor for Google Drive (Text mode)
  • HTML Editor for Google Drive (WYSIWYG)
Right-click on the HTML file, click 'Get Shareable Link', a link is copied to clipboard similar to this:

However that link is View UI of Google Drive, change to the following to download:

However, HTML files shouldn't be downloaded, should be viewed in browser, use the following URL (Google Drive Toolkit), where XXX is the Id of the file.

Friday, 24 January 2020

Create HTML Files in Google Drive and View in Browser

HTML files can be created in Google Drive using these Google Drive apps:

  • Text Editor for Google Drive
  • HTML Editor for Google Drive
When getting link for the HTML file from Google Drive by clicking 'Get Shareable Link', the URL is:

https://drive.google.com/open?id=XXX

The above link is to View UI of Google Drive. Change it to get the direct link to the file:

https://drive.google.com/uc?id=XXX

Images work okay! but for HTML files, Google purposely deny users from viewing in browser by forcing a download, Google servers set a response header:

Content-Disposition: attachment;

Now, how to view the HTML content in browser anyway? Nginx proxy_pass doesn't work, Google blocks it. Nginx rewrite & return doesn't work as there are multiple HTTP 302 redirects and can't remove the above header.

Solution
Create a web server just to load the HTML files and send to browser!

Source Code:
//Libs
import express from "express";
import request from "request";

//Make a lock
function new_lock(){
  var Unlock,Lock=new Promise((Resolve,Reject)=>{ Unlock=Resolve; });
  return [Lock,Unlock];
}

//PROGRAMME ENTRY POINT=========================================================
var Server = express();

Server.get("/gd/*",async (Req,Res)=>{
  var Url     = Req.url;
  var Id      = Url.replace("/gd/","");
  var Gd_Url  = `https://drive.google.com/uc?id=${Id}`;

  //make request to Google Drive
  var Content       = "no-contents";
  var [Lock,Unlock] = new_lock();

  request(Gd_Url,(Err,Gdres,Body)=>{
    Content = Body;
    Unlock();
  });

  await Lock;
  Res.send(Content);
});

Server.listen(8080);
//EOF