Wednesday, 15 March 2023

React baby Exercises

Ex 1. Simple Displaying A MESSAGE


npm create vite

√ Project name: ... ex1

√ Select a framework: » React

√ Select a variant: » TypeScript

Scaffolding project in C:\Users\rmcme\ex1...

Done. Now run:

cd ex1

npm install

npm run dev

code . to invoke vs code ide


delete the contents of index.css

Replace the contents of App.tsx

with the following

function App() {
  return <h1>Hello React World</h1>;
}
export default App;


in vs code terminal window:

npm install

npm run dev

it will display URL. Open that URL.Will look similar to the given window


Super! We have done the First React !!!


Ex 2. Simple Displaying Array of Names


Replace the contents of App.tsx with


// EX 2
function App() {
  const ceos = [
    { name: "Elon Musk", id: "1" },
    { name: "Bill Gates", id: "2" },
    { name: "Steve Jobs", id: "3" },
  ];

  const ceosNames = ceos.map((ceo) => <li key={ceo.id}>{ceo.name}</li>);

  return (
    <>
      <h3>CEO names</h3>
      <ul>{ceosNames}</ul>
    </>
  );
}

export default App;


You will see browser output similar to the below




Ex 3. Simple Show/Hide DOM Element

Replace the contents of App.tsx with 

//EX 3

import { useState } from "react";
function App() {
  const [show, setShow] = useState(true);
  return (
    <>
      <button onClick={() => setShow(!show)}>
        {show ? "Hide Element below" : "Show Element Below"}
      </button>
      {show && <div>Toggle Challenge </div>}
    </>
  );
}

export default App;



The browser output will be similar to:




once you click the Hide element Button, you can see the browser output similar to:



Ex 4. Data Binding 2 Ways

Replace the contents of App.tsx with 

// EX 4
import { useState } from "react";

function App() {
  const [value, setValue] = useState("");

  return (
    <>
      <input
        type="text"
        placeholder="Enter Text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
      <p>{value}</p>
    </>
  );
}

export default App;

The browser output will be:


 
Once you entered text in text box, the browser output will be 





Ex 5. Enable Button Element 

Replace the contents of App.tsx with 

// EX 5
import { useState } from "react";

function App() {
  const [value, setValue] = useState("");

  return (
    <>
      <h3>No Text No Submit, If "Text" Submit Challenge</h3>
      <input type="text" onChange={(e) => setValue(e.target.value)} />
      <button disabled={value.length < 1}>Submit</button>
    </>
  );
}

export default App;

The browser output will be:




 
Once you entered text in text box, the submit button will be enabled  











React Tutorial Basics

 download node.js and install

check whether it is properly installed by 

node -v

C:\Users\rmcme>node -v

v18.15.0

C:\Users\rmcme>npm create vite

y to proceed

select vite version 4.1

give project name : react-app

select framework: React 

select variant : typescript

C:\Users\rmcme>cd react-app

install vs code

cd react-app

npm i     ----to install

C:\Users\rmcme\react-app\code . to open vs code editor

In VS code Terminal, enter

npm run dev

you will  see similar to this URL: http://localhost:5173/

click the URL to see the webpage to check

Now create a file Meesage.tsx in src folder

add 

/Pascal Casing

function Message() {
    //JSXML

   // const name="RMC";
    if (name)
       return <h1>Hello {name} World</h1>;
    return <h1>Hello World</h1>;
}  
export default Message;


Edit App.tsx file

replace with the following 


import Message from './Message';

function App() {
 
  return <div><Message></Message></div>
 
}

export default App;

You can check in the browser






In terminal window in VS code,

install Bootstrap 

npm i bootstrap@5.2.3


edit App.css

delete the contents and save

edit index.css

delete the contents and save

edit main.tsx

replace

import './index.css'

with 

import 'bootstrap/dist/css/bootstrap.css'


Create a directory components under src

under components create a file ListGroup.tsx

add the following contents:


function ListGroup() {
    return <h1>ListGroup</h1>
}
export default ListGroup;

Edit App.tsx

replace the contents with 

import ListGroup from "./components/ListGroup";
function App() {

  return <div><ListGroup /></div>

}


Replace the contents.


//import {  } from "react";

function ListGroup() {
  // return <h1>ListGroup</h1>

  const items = [
    "Chennai",
    "Bombay",
    "New Delhi",
    "Bangalore",
    "Madurai",
    "Calcutta",
  ];

  return (
    <>
      <h1>List</h1>
      <ul className="list-group">
        {items.map((item) => (
          <li>{item}</li>
        ))}
      </ul>
    </>
  );
}
export default ListGroup;

Check in the Browser and inspect to check the clicked events































Monday, 13 March 2023

Python Stock : NSE

 Introduction to NSE Tools Module in Python

NSE National Stock Exchange of India Limited is the leading stock exchange of India, located in Mumbai, Maharashtra. NSE was established in 1992 as the first dematerialized electronic exchange in the country.

nsetools is a library for collecting real time data from National Stock Exchange of India. 

It can be used in various types of projects which requires fetching live quotes for a given stock or index or building large data sets for further data analytics. 


In order to install nse tools we have to use the command given below 
 

pip install nsetools

Creating a NSE object and Using

 
 # importing nse from nse tools
from nsetools import Nse
 
# creating a Nse object
nse = Nse()
 
# printing Nse object
print(nse)

# Driver Class for National Stock Exchange (NSE)

# getting quote of the sbin
quote = nse.get_quote('sbin')
q1 = nse.get_quote('TATAMOTORS')
# printing company name
print(quote['companyName'])
 
# printing buy price
print("Buy Price : " + str(quote['buyPrice1']))
print("SBIN open : " + str(quote['open']))


print(q1['companyName'])
print("Tata Motors Open : " + str(q1['open']))

Driver Class for National Stock Exchange (NSE)
State Bank of India
Buy Price : None
SBIN open  : 547.0
Tata Motors Limited
Tata Motors Open : 436.1


print(q1)
"""

{'pricebandupper': 479.4, 'symbol': 'TATAMOTORS', 'applicableMargin': 18.43, 'bcEndDate': '09-AUG-16', 'totalSellQuantity': None, 'adhocMargin': None, 'companyName': 'Tata Motors Limited', 'marketType': 'N',
'exDate': '18-JUL-16', 'bcStartDate': '20-JUL-16', 'css_status_desc': 'Listed', 'dayHigh': 437.0, 'basePrice': 435.85, 'securityVar': 14.93, 'pricebandlower': 392.3, 'sellQuantity5': None, 'sellQuantity4': None, 'sellQuantity3': None, 'cm_adj_high_dt': '17-AUG-22', 'sellQuantity2': None, 'dayLow': 419.1, 'sellQuantity1': None, 'quantityTraded': 8780169.0, 'pChange': '-2.93', 'totalTradedValue': 37481.66, 'deliveryToTradedQuantity': 36.45, 'totalBuyQuantity': 2567.0, 'averagePrice': 426.89, 'indexVar': None, 'cm_ffm': 75757.3, 'purpose': 'DIVIDEND - RE 0.20/- PER SHARE', 'buyPrice2': None, 'secDate': '13-Mar-2023 00:00:00', 'buyPrice1': 422.4, 'high52': 494.4, 'previousClose': 435.85, 'ndEndDate': None, 'low52': 366.2,
'buyPrice4': None, 'buyPrice3': None, 'recordDate':
None, 'deliveryQuantity': 3200108.0, 'buyPrice5': None, 'priceBand': 'No Band', 'extremeLossMargin': 3.5, 'cm_adj_low_dt': '12-MAY-22', 'varMargin': 14.93,
'sellPrice1': None, 'sellPrice2': None, 'totalTradedVolume': 8780169.0, 'sellPrice3': None, 'sellPrice4': None, 'sellPrice5': None, 'change': '-12.75', 'surv_indicator': None, 'ndStartDate': None, 'buyQuantity4': None, 'isExDateFlag': False, 'buyQuantity3': None, 'buyQuantity2': None, 'buyQuantity1': 2567.0, 'series': 'EQ', 'faceValue': 2.0, 'buyQuantity5': None, 'closePrice': 422.4, 'open': 436.1, 'isinCode': 'INE155A01022', 'lastPrice': 423.1} """


Automation with Python #1 - WhatsApp

# WHATSAPP AUTOMATION

Step 1: Install pywhatkit


pip install pywhatkit


Step 2: Send a message to a contact on WhatsApp

Before we start sending messages, you have to log in to your WhatsApp account through WhatsApp Web. 

To send a message to a WhatsApp contact with Python and pywhatkit, we use the .sendwhatmsg method as shown in the code below (insert your contact number instead).


import pywhatkit
pywhatkit.sendwhatmsg('+919790215636', 'Hello Sweet Heart', 11, 56)

What this code means is “Type ‘Message 1’ and send it to contact X at 18:52”

After running the code above you’ll get a message like this:

In 10 seconds, web.WhatsApp.com will open, and after 15 seconds, a message will be delivered by Whatsapp.

After some seconds your browser will open and the message will be sent to your contact.

Please Note: When your browser opens, a message to grant access will pop up. You have to accept this message.


Bonus:

import pywhatkit
pywhatkit.sendwhatmsg_to_group("Group-id", "Group Message", 19, 2)


# EXCEL AUTOMATION

pip install openpyxl


Saturday, 10 December 2022

Ionic Angular #1 Simple Demo

IONIC ANGULAR TUTORIAL

Step 1 : Install Ionic

npm install -g ionic

Step 2:

Create an Ionic angular  App by

npm install -g @ionic/cli native-run cordova-res

Step 3:

create an ionic app with tabs

ionic start demo-ionic tabs --type=angular --capacitor

Step 4 

cd demo-ionic

npm install @capacitor/camera @capacitor/preferences @capacitor/filesystem

Step 5

npm install @ionic/pwa-elements

Step 6 : edit in VS studio

Next, import @ionic/pwa-elements by editing src/main.ts.

import { defineCustomElements } from '@ionic/pwa-elements/loader';

defineCustomElements(window);

Step 6:

Run the App by 

ionic serve

Check out the output similar to this browser window



Step 7:

In the file  /src/app/tab2/tab2.page.htm

change both <ion-title> Tab2 to <ion-title> Demo Photo


Append the code  changing icon from ellipse to camera

<ion-content>

  <ion-fab vertical="bottom" horizontal="center" slot="fixed">

    <ion-fab-button>

      <ion-icon name="camera"></ion-icon>

    </ion-fab-button>

  </ion-fab>

</ion-content>

Step 8:

Modify src/app/tabs/tabs.page.html. file  

Change the label to <ion-label> Photos

check the changes made in running browser and clicking Photos icon


Let us learn further Later ....👀👀👀👀


Thursday, 1 December 2022

Angular #8 Forms

Forms

2 - Types namely

1. Template driven

2. Reactive Forms


3 - Building Blocks namely 

FormControl (single Item), 

FormGroup (collection of Form Controls)

FormArray (Array of Form Controls)


Method 1 - TDF

ng new tdf --routing=true --style=css

ng serve -o to check

Open app.module.ts and add FormsModule to it 

import { FormsModule} from '@angular/forms';

add that in imports section

 imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],

add the following in AppComponent class in app.component.ts file

countryList:country[] = [
    new country("1", "India"),
    new country('2', 'USA'),
    new country('3', 'England')
  ];

 Add  the following class country:

export class country {
  id:string;
  name:string;
 
  constructor(id:string, name:string) {
    this.id=id;
    this.name=name;
  }
}

Delete the old contents in app.component.html and add the following contents 


form>
  <table border="2" >
  <tr>
 
    <label for="firstname">First Name :</label>
    <input type="text" id="firstname" name="firstname">
  </tr>
 
  <tr>
    <label for="lastname">Last Name:</label>
    <input type="text" id="lastname" name="lastname">
  </tr>
 
  <tr>
    <label for="email">Email :</label>
    <input type="text" id="email" name="email">
  </tr>
 
  <tr>
    <label for="gender">Gender :</label>
    <input type="radio" value="male" id="gender" name="gender"> Male
    <input type="radio" value="female" id="gender" name="gender"> Female
  </tr>
 
  <tr>
    <label for="isMarried">Married :</label>
    <input type="checkbox" id="isMarried" name="isMarried">
  </tr>
 
  <tr>
  <label for="country">country :</label>
  <select name="country" id="country">
    <option selected="" value=""></option>
    <option [ngValue]="c.id" *ngFor="let c of countryList">
      {{c.name}}
    </option>
  </select>
  </tr>
 
  <tr>
    <button type="submit">Submit</button>
  </tr>
</table>
</form>

change the <form> line as shown below

  <form #contactform="ngForm" (ngSubmit)="onSubmit(contactForm)"></form>

add ngModel to all six form elements: This will be similar to these contents

 <p>Template Driven Form</p>

<!-- <form> -->
<form #contactForm="ngForm" (ngSubmit) = "onSubmit(contactForm)">
<table border="2" >
  <tr>
 
    <label for="firstname">First Name :</label>
    <input type="text" id="firstname" name="firstname" ngModel>
  </tr>
 
  <tr>
    <label for="lastname">Last Name:</label>
    <input type="text" id="lastname" name="lastname" ngModel>
  </tr>
 
  <tr>
    <label for="email">Email :</label>
    <input type="text" id="email" name="email" ngModel>
  </tr>
 
  <tr>
    <label for="gender">Gender :</label>
    <input type="radio" value="male" id="gender" name="gender" ngModel> Male
    <input type="radio" value="female" id="gender" name="gender" ngModel> Female
  </tr>
 
  <tr>
    <label for="isMarried">Married :</label>
    <input type="checkbox" id="isMarried" name="isMarried" ngModel>
  </tr>
 
  <tr>
  <label for="country">country :</label>
  <select name="country" id="country" ngModel>
     <option [ngValue]="c.id" *ngFor="let c of countryList">
      {{c.name}}
    </option>
  </select>
  </tr>
 
  <tr>
    <button type="submit">Submit</button>
  </tr>
</table>
</form>

app.component.ts will have these contents

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'tdf';

  countryList:country[]=[
    new country("1", "india"),
    new country("2", "indonesia"),
    new country("3", "usa"),
    new country("4", "uk")
  ]
 
  onSubmit(contactForm: { value: any; }){
    console.log(contactForm.value);
  }
}

export class country {
  id: string;
  name: string;

  constructor(id:string,name:string){
    this.id=id;
    this.name=name;
  }
}

Now run by

ng serve -o and check the browser window output(similar to the following) with console output checking the entered values after submit button pressed.


Add the following contents in the app.component.ts

Entered Values:
<table>
  <tr>
    <td>
      Value : {{contactForm.value | json }}
    </td>
  </tr>
  <tr>
    <td>
      Touched : {{contactForm.touched  }}
    </td>
  </tr>
  <tr>
    <td>
      Submitted : {{contactForm.submitted  }}
    </td>
  </tr>
  </table>
 

Check the browser output similar to after you entered form and submitted:


Try this exercise to understand th values:

In app.component.html try commenting (by marking all and ctrl+/ ) the old contents add the following

 <form>
    <input type="text" name="firstname" #fname="ngModel" ngModel>
  </form>
<pre>
Value    : {{fname.value}} <br>
valid    : {{fname.valid}} <br>
invalid  : {{fname.invalid}} <br>
touched  : {{fname.touched}}
</pre>

Check the browser output 

before entering


after entering



In app.component..html add the following contents  commenting the old:
 

<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)"></form>
<div ngModelGroup="address">
  <p>
    <label for="city">City</label>
    <input type="text" name="city" ngModel>
  </p>
  <p>
    <label for="street">Street</label>
    <input type="text" name="street" ngModel>
  </p>
  <p>
    <label for="pincode">Pin Code</label>
    <input type="text" name="pincode" ngModel>
  </p>
</div>
</form>

Check the output values (similar to the one shown below) for address in browser :

I think you catch some basic points in form handling 



Method 2. Reactive Forms

Step 1:

Create a project reactive-demo by

ng new demo-react

Step 2:

Open app.module.ts and  add in the beginning 

import { ReactiveFormsModule } from '@angular/forms';  

and add the following in import section

imports: [
    ...  
    ReactiveFormsModule

Step 3:

Modify app.component.html, deleting the all the old  contents and add these following code:


 <h1> {{title}} </h1>
 <hr color="red">
 <form [formGroup] = "loginForm" (ngSubmit)="loginUser()">
    <label>Name : </label><input type="text" place holder="enter name" formControlName="user">
    <br><br>
    <label>Password : </label>
    <input type="password" place holder="enter password" formControlName="password"> <br>

    <button>Login</button>
 </form>


Please note 

1. Form with [formGroup] and (ngSubmit)="loginUser()" function

2. formControleName = user and formControleName=password attributes in <input> tag

Step 4:

Modify the app.component.ts by adding the following as shown below

import { Component } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Demo-React-Form';
  loginForm = new FormGroup({
    user: new FormControl(''),
    password: new FormControl(''),
  })
  loginUser(){
   console.log(this.loginForm.value)
  }
}

Step 5:

Now run by 

ng serve -o

Check console output after clicking login Button to see the o/p similar to the following:

before entering user name and password



After Entering and clicking the button Login. see in console, the o/p will be similar to this.

Happy Angular Forms....☺☺☺.!!!




Making Prompts for Profile Web Site

  Prompt: Can you create prompt to craft better draft in a given topic. Response: Sure! Could you please specify the topic for which you...