Wednesday, January 1, 2025

Misc Javascript points

 Nodejs can support multithreading through use of promises

_ is the numeric separator for javascript, that means the numbers 10_000, 11.23_003 etc ar valid numbers in javascript. They will be treated as and displayed as 1000 , 11,23005 etc by  javascript.


You can use & at the end of node command to run the process in background. (may be unix feature)

node xxxx & 

ps  -> list all processes 

kill NNN  kills process with id NNN

CommonJS and ECMAScript

When you are creating express backend, you have two options: to use CommonJS or to use ECMAScript.


CommonJS is default for Node. 


You can specify which one to use in package.json. 

When you want to use CommonJS, you specify "type" : "commonjs". This is added in package.json by default when a new node project is created by using "npm init" command. 

When you want to use ECMAScript, you have to change this type to module: "type" : "module". 


The main difference between ECMAScript and CommonJS is in importing modules: ECMAScript uses "import" statement, while CommonJS uses "require" statement. 


The below project create two different Hello, World projects in Express, one with CommonJS and other with ECMAScript.


======================================================================================

STEP 001 : Creating a new express project with commonjs with API code in separate file

======================================================================================

1. Create a React-Node Ubuntu container, with mounted volume. 

2. Create a folder commonjs and change directory to that folder:

cd commonjs

3. Run the below command to create a new node project:

npm init

   Keep on pressing <Enter> keys on all questions, we are going to use default names and settings only. 

   Next, install express:

npm install express

4. Inspect package.json by using command "cat package.json".  You will find the below line by default: 

"type" : "commonjs"

   Thus, this project will use commonjs ("require" syntax).

5. Create a index.js file:  (because the package.json by default contains the entry "main" : "index.js")

touch index.js

   Open this file for editing:

vi index.js

   Add the following code to this file:

-----------------------------------------------------------------------

index.js

-----------------------------------------------------------------------

const express = require("express");

const hello001 = require("./hello001.js");

const hello002 = require("./hello002.js");


const app = express();



//both index.js and hello001.js, hello002.js should be in same directory

app.use('/hello001', hello001);

app.use('/hello002', hello002);



app.listen(4000);

-----------------------------------------------------------------------

6. Create an hello001.js file in the same folder with below code:

-----------------------------------------------------------------------

hello001.js

-----------------------------------------------------------------------

const express = require("express");

const router = express.Router();


router.get('/', function(req, res){

   res.send('GET route on HELLO 001');

});

router.post('/', function(req, res){

   res.send('POST route on HELLO 001.');

});


//export this router to use in our index.js

module.exports = router;  //this is required for commonjs

//export default router;      //this is required for ECMAScript


-----------------------------------------------------------------------

 

7. Create an hello002.js file in the same folder with below code: 

-----------------------------------------------------------------------

hello002.js

-----------------------------------------------------------------------

const express = require("express");

const router = express.Router();


router.get('/', function(req, res){

   res.send('GET route on HELLO 002');

});

router.post('/', function(req, res){

   res.send('POST route on HELLO 002.');

});


//export this router to use in our index.js

module.exports = router;  //this is required for commonjs

//export default router;      //this is required for ECMAScript

-----------------------------------------------------------------------


8. Run the project. 

node index.js

   The project will start running, but there will be no message displayed since we have not given one. 

9. You can  check the GET methods on the host computer's browser, browse to  (THIS ASSUMES CONTAINER's 4000 port is mapped to 11000 port of host computer)

http://localhost:11000/hello001

and 

http://localhost:11000/hello002


You should see the messages: "GET route on HELLO 001" and "GET route on HELLO 002" respectively on the browser.


10. You can check the POST method calls using POSTMAN. 

In POSTMAN, use the same URLs as above and simply change API type to POST and send the request. (WE are not using any auth and also there are no request parameters/body required).

You should see the messages: "POST route on HELLO 001" and "POST route on HELLO 002" respectively on the browser.


11. Please find below the package.json for ready reference: 

-----------------------------------------------------------------------

package.json

-----------------------------------------------------------------------

{

  "name": "commonjs",

  "version": "1.0.0",

  "description": "",

  "license": "ISC",

  "author": "",

  "type": "commonjs",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "dependencies": {

    "express": "^4.21.2"

  }

}

-----------------------------------------------------------------------

======================================================================================




========================================================================================

STEP 002 : Creating a new express project with ECMASCript with API code in separate file

========================================================================================

1. Create a React-Node Ubuntu container, with mounted volume. 

2. Create a folder ecmascript and change directory to that folder:

cd ecmascript

3. Run the below command to create a new node project:

npm init

   Keep on pressing <Enter> keys on all questions, we are going to use default names and settings only. 

   ==> THE LAST QUESTION ASKED IS "type", for which the default answer is "(commonjs)". 

You can type "module" here (without double quotes!, it will add double quotes by itself).

If you missed this, DO NOT WORRY, YOU CAN CHANGE IT IN STEP 4 below.

   Next, install express:

npm install express


4. Inspect package.json by using command "cat package.json".  

   If you have already specified "type" as "module" in step 3 above, then you are good to go. 

   If you missed it in step 3 above, you can now edit package.json and change the type to module.


   Open package.json in vi editior, if you find the below line: 

"type" : "commonjs"

   change it to: 

"type" : "module"    [DIFFERENCE 001]

   

5. Create a index.js file:  (because the package.json by default contains the entry "main" : "index.js")

touch index.js

   Open this file for editing:

vi index.js

   Add the following code to this file:

-----------------------------------------------------------------------

index.js

-----------------------------------------------------------------------

import express from "express";              //[DIFFERENCE 002]

import hello001 from "./hello001.js"; //[DIFFERENCE 003]

import hello002 from "./hello002.js"; //[DIFFERENCE 004]


const app = express();



//both index.js and hello001.js, hello002.js should be in same directory

app.use('/hello001', hello001);

app.use('/hello002', hello002);



app.listen(4000);

-----------------------------------------------------------------------

6. Create an hello001.js file in the same folder with below code:

-----------------------------------------------------------------------

hello001.js

-----------------------------------------------------------------------

import express from "express"; //[DIFFERENCE 005]

const router = express.Router();


router.get('/', function(req, res){

   res.send('GET route on HELLO 001');

});

router.post('/', function(req, res){

   res.send('POST route on HELLO 001.');

});


//export this router to use in our index.js

//module.exports = router;  //this is required for commonjs

export default router;      //this is required for ECMAScript //[DIFFERENCE 006]

-----------------------------------------------------------------------

 

7. Create an hello002.js file in the same folder with below code: 

-----------------------------------------------------------------------

hello002.js

-----------------------------------------------------------------------

import express from "express"; //[DIFFERENCE 007]

const router = express.Router();


router.get('/', function(req, res){

   res.send('GET route on HELLO 002');

});

router.post('/', function(req, res){

   res.send('POST route on HELLO 002.');

});


//export this router to use in our index.js

//module.exports = router;  //this is required for commonjs

export default router;      //this is required for ECMAScript //[DIFFERENCE 008]

-----------------------------------------------------------------------


8. Run the project. 

node index.js

   The project will start running, but there will be no message displayed since we have not given one. 

9. You can  check the GET methods on the host computer's browser, browse to  (THIS ASSUMES CONTAINER's 4000 port is mapped to 11000 port of host computer)

http://localhost:11000/hello001

and 

http://localhost:11000/hello002


You should see the messages: "GET route on HELLO 001" and "GET route on HELLO 002" respectively on the browser.


10. You can check the POST method calls using POSTMAN. 

In POSTMAN, use the same URLs as above and simply change API type to POST and send the request. (WE are not using any auth and also there are no request parameters/body required).

You should see the messages: "POST route on HELLO 001" and "POST route on HELLO 002" respectively on the browser.


11. Below is the package.json for ready reference: 

-----------------------------------------------------------------------

package.json

-----------------------------------------------------------------------

{

  "name": "ecmascript",

  "version": "1.0.0",

  "description": "",

  "license": "ISC",

  "author": "",

  "type": "module",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "dependencies": {

    "express": "^4.21.2"

  }

}

-----------------------------------------------------------------------


The only change you will notice will be in the "type" line.

========================================================================================

Sunday, June 9, 2024

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to find out the globally installed version of Angular.

Thursday, November 2, 2023

 using Microsoft.AspNetCore.Mvc;

using System.Xml.Linq;

using System.Xml.XPath;

//<table class="common-table medium js-table js-streamable-table">

namespace WebApplication1.Controllers

{

    [ApiController]

    [Route("[controller]")]

    public class WeatherForecastController : ControllerBase

    {

        private static readonly string[] Summaries = new[]

        {

        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

    };


        private readonly ILogger<WeatherForecastController> _logger;


        public WeatherForecastController(ILogger<WeatherForecastController> logger)

        {

            _logger = logger;

        }


        [HttpGet(Name = "GetWeatherForecast")]

        public async Task<string>  Get()

        {

            try

            {

                //HttpClient client = new HttpClient();

                //var uri = new Uri("" , 

                //var x = await client.GetStringAsync()"https://in.investing.com/equities/trending-stocks/technical");

                //https://in.investing.com/stock-screener/?sp=country::14|sector::a|industry::a|equityType::a<eq_market_cap:1

                //https://in.investing.com/stock-screener/?sp=country::14|sector::a|industry::a|equityType::a%3Ceq_market_cap;1

                //var url = "https://in.investing.com/equities/trending-stocks/technical";

                //var url = "https://in.investing.com/stock-screener/?" + Uri.EscapeDataString("sp=country::14|sector::a|industry::a|equityType::a<eq_market_cap:1");

                var url = "https://in.investing.com/equities/trending-stocks/technical";

                using var client = new HttpClient();


                var msg = new HttpRequestMessage(HttpMethod.Get, url);

                msg.Headers.Add("User-Agent", "Mozilla/5.0");

                var res = await client.SendAsync(msg);

                var content = await res.Content.ReadAsStringAsync();

                //XPathDocument xPath = new XPathDocument(content);

                //var nav = xPath.CreateNavigator();

                //var iter = nav.Select("/");


                //StreamReader textReader = new StreamReader(content);

                //XDocument doc = XDocument.Parse(content);

                //XElement xElement = XElement.Parse(content);

                int StartIndex = content.IndexOf("<table class=\"common-table medium js-table js-streamable-table\">");

                int EndIndex = content.IndexOf("</table>", StartIndex);

                string usefulContent = content.Substring(StartIndex, EndIndex+ 8  - StartIndex);

                //XDocument doc = XDocument.Parse(usefulContent);

                //XElement xElement = XElement.Parse(usefulContent);

                var lst = ParseString(usefulContent);

                Console.WriteLine(content);

            }

            catch ( Exception ex)

            {


            }


            return "test";

        }


        private  List<string> ParseString(string inpString)

        {

            string StartPattern = "<tr class=\"common-table-item u-clickable \"";

            string EndPattern = "</tr>";

            

            var lst = ExtractHtmlTags(inpString, StartPattern, EndPattern);

            var titleList = new List<String>();

            var hourList = new List<String>();

            var dayList = new List<String>();

            var weekList = new List<String>();

            var monthList = new List<String>();

            var companyList = new List<Company>();


            foreach (var item in lst)

            {

                Company company = new Company();

                company.Title = ExtractHtmlTags(ExtractHtmlTags(item, "<a", "</a>")[0], ">", "</", true)[0];

                company.Hourly = ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_hour", "</td>")[0], "<span class=\"text\">", "</span>", true)[0];

                company.Daily = ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_day", "</td>")[0], "<span class=\"text\">", "</span>", true)[0];

                company.Weekly = ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_week", "</td>")[0], "<span class=\"text\">", "</span>", true)[0];

                company.Monthly = ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_month", "</td>")[0], "<span class=\"text\">", "</span>", true)[0];

                companyList.Add(company);


                titleList.Add(ExtractHtmlTags(ExtractHtmlTags(item, "<a", "</a>")[0] , ">" , "</", true)[0]);

                hourList.Add(ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_hour", "</td>")[0] , "<span class=\"text\">" , "</span>", true)[0]);

                dayList.Add(ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_day", "</td>")[0], "<span class=\"text\">", "</span>", true)[0]);

                weekList.Add(ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_week", "</td>")[0], "<span class=\"text\">", "</span>", true)[0]);

                monthList.Add(ExtractHtmlTags(ExtractHtmlTags(item, "<td class=\"col-technical_month", "</td>")[0], "<span class=\"text\">", "</span>", true)[0]);

            }

            return lst;

        }


        private List<string> ExtractHtmlTags(string inpString , string StartPattern, string EndPattern, bool excludePatterns = false)

        {

            List<string> lst = new List<string>();

            int StartIndex = 0; int EndIndex = 0;


            StartIndex = inpString.IndexOf(StartPattern);

            EndIndex = inpString.IndexOf(EndPattern, StartIndex + 1);

            while (StartIndex > 0 && EndIndex > 0)

            {

                int substringStartIndex = StartIndex;

                int substringEndIndex = EndIndex - StartIndex + EndPattern.Length;

                if ( excludePatterns)

                {

                    substringStartIndex = StartIndex + StartPattern.Length;

                    substringEndIndex = EndIndex - substringStartIndex;

                }

                string trString = inpString.Substring(substringStartIndex, substringEndIndex);

                lst.Add(trString);

                if (EndIndex + EndPattern.Length + 1 >= inpString.Length) break;

                StartIndex = inpString.IndexOf(StartPattern, EndIndex);

                EndIndex = inpString.IndexOf(EndPattern, StartIndex + 1);

            }

            return lst;

        }

    }


    public class Company

    {

        public string? Title {  get; set; }

        public string? Hourly { get; set; }

        public string? Daily { get; set; }

        public string? Weekly { get; set; }

        public string? Monthly { get; set; }


    }

}

Wednesday, August 30, 2023

Non Technical- MF SIP Advice

small cap 


Nippon India small cap direct growth 

SBI small cap  500

kotak small cap 1000

hdfc small cap  500

quant small cap 1000

icici small cap  500


4000


balanced funds 

*hdfc balanced advantage 1500

icici pru balanced advantage 500

nippon 500

kotak 500


3000



FoF

Kotak multi assest allocator FoF dynamic 2500

icici pru asset allocator 1000


3500


ICICI


icici pru value discovery fund  500

icici pru equity and debt fund  500

icici pru multi asset fund      500

icici pru blue chip fund        500

2000


bank nifty   (could not be done)

hdfc bank nifty       500

kotak nifty bank etf  500


1000

Saturday, July 8, 2023

Difference between axios and fetch - a detailed article

 https://codilime.com/blog/axios-vs-fetch/#:~:text=Different%20properties%20are%20used%20for,API%20using%20the%20POST%20method.


35 mins read! here

Saturday, June 24, 2023

CSS border shadow for input box taken from https://stackoverflow.com/questions/14820952/change-bootstrap-input-focus-blue-glow

<!DOCTYPE html>
<html>
<head>
<style> 
input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 1px solid #555;
  outline: none;
  border-radius: 5px;
}

input[type=text]:focus {
  border-color: #28a745;
  box-shadow: 0 0 0 0.1rem rgba(40, 167, 69, 0.25);
}
</style>
</head>
<body>

<h2>Input fields with color on :focus</h2>

<p>Here, the input field gets a color when it gets focus (clicked on):</p>

<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" value="John">
  <label for="lname">Last Name</label>
  <input type="text" id="lname" name="lname" value="Doe">
</form>

</body>
</html>


Misc Javascript points

 Nodejs can support multithreading through use of promises _ is the numeric separator for javascript, that means the numbers 10_000, 11.23_0...