Tuesday, 30 July 2019

Creating Django App and Model

The main purpose of the app is to create the Django app for some specific features within the existing Django based project.

Here we are going to learn how to create a Django app and providing the link with the existing projects so that dedicated features may be available as part of our application.

Adhere with my steps as mentioned below and enjoy the Django Web development patiently!!

Step 1: Create a Django main project. In my case, I have created "openchoicemart" project.


Step 2: Now create a app as "profiles".Go to your project root directory and execute below command
> python ./manage.py startapp profiles
profiles app is created successfully under your Django project now.

Project Structure in Code Editor(Prefer Visual Studio Code)




















Designing Profile Model
Now we are going to learn how to design the models and how it impacts on DB?
1) Open the models.py and develop the code as below
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class profile(models.Model):
name=models.CharField(max_length=120)
description=models.TextField(default='Default profile description')
def __unicode__(self):
return self.name

2)Now make the migration ready
>python .\manage.py makemigrations
>python .\manage.py migrate
  and then run the python server
>python .\manage.py runserver
3)Once migration is successful then verify into your respective DB.
   For me, Let's verify it into MongoDB.
   Just start your MongoDB servers and open DB GUI(MongoDB Compass)

























Note:
There are several commands which you will use to interact with migrations and Django’s handling of database schema:
  • migrate: which is responsible for applying and unapplying migrations.
  • makemigrations: This is responsible for creating new migrations based on the changes you have made to your models.
  • sqlmigrate: which displays the SQL statements for a migration.
  • showmigrations: which lists a project’s migrations and their status.
Registering Profile model into Django Admin
One of the best features of Django is that we can manage our custom models using builtin and predefined functionalities  using the Django admin page.

Then what we need to do so?

As simple as that, we need to register this model into the Django admin app.

1)Just open admin.py and develop the below piece of code.
from django.contrib import admin
from .models import profile
# Register your models here.
class profileAdmin(admin.ModelAdmin):
class Meta:
model = profile
admin.site.register(profile,profileAdmin)
2)Run below commands
>python .\manage.py makemigrations
>python .\manage.py migrate
  and then run the python server
>python .\manage.py runserver

and login into the Django admin page and observer the changes.
http://127.0.0.1:8000/admin















Monday, 22 July 2019

ReactJS: Route using REACT-ROUTER-DOM

Today We are going to understand about the usage of Route using react-route-dom library!


1)We need to install react-route-dom, see the step to install this in below installation link.  REACT_ROUTE_DOM_Installation
2)Develop below component  to see the routing flow
  • /src/pages/Home.js
import React from 'react'
export default function Home() {
return (
<div>
Hello this from Home Page
</div>
)
}


  • /src/pages/Rooms.js

import React from 'react'
const Rooms = () => {
return (
<div>
Hello this is from Rooms page!!!
</div>
)
}
export default Rooms

  • /src/pages/SingleRoom.js-This is class component

import React, { Component } from 'react'
export default class SingleRoom extends Component {
render() {
return (
<div>
Hello this is from Single Room Page!!
</div>
)
}
}

3)Update App.js as below
function App() {
return (
<div>
<Route exact path="/" component={Home}/>
<Route exact path="/rooms" component={Rooms}/>
<Route exact path="/singleroom" component={SingleRoom}/>
</div>
);
}

4)Update Index component of your project as below
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router} from 'react-router-dom'
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root'));
serviceWorker.unregister();
5)start server
npm start

6)Browse as below see the impact of routing to pages
http://localhost:3000/
http://localhost:3000/rooms
http://localhost:3000/singleroom

Requirement: Suppose there is no match of url then render the error page

Implementation:
To do so, we need to create use Switch and Route class.

1)Create one Error component as below

  • /src/pages/Error.js

import React from 'react'
export default function Error() {
return (
<div>
This is an error page!!!!!
</div>
)
}

2)Update App.js as below

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './pages/Home';
import Rooms from './pages/Rooms';
import SingleRoom from './pages/SingleRoom';
import Error from './pages/Error';
import {Route,Switch} from "react-router-dom";
function App() {
return (
<div>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/rooms" component={Rooms}/>
<Route exact path="/singleroom" component={SingleRoom}/>
<Route component={Error}/>
</Switch>
</div>
);
}
export default App;























Sunday, 14 July 2019

MongoDB Setup With Django

SQLITE is default database for Django but if you want to use some different database then need to follow below steps:
I have charted down the steps using no sql db(mongo db).But you can follow below steps as well for other database also.Just you need to be careful about some specific database related stuffs.
1)Install Django
   >pip install django
2)Install mongodb module for django which is "djongo".
   >pip install djongo
3)You might have already created Django  project.If not created, create Django project.
4)Create Django App.
5)Add created app to installed app list.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Your_Custom_App'
]
6)Mongo DB configuration in Django
Open Settings.py file and comment out the other databases configuration and update
the database configuration for mongo as below:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'Your Mongo DB name',
}
}
Note:Follow below link for Mongo DB creation
7)Now run migration to see the db effect
>python .\manage.py migrate
8)Let us verify these changes into Mongo db.
To manipulate the Mongodb data, We can use MongoDB Compass GUI which is provided by
MongoDB itself.
MongoDB Compass Download Center

Monday, 8 July 2019

React Component

What is component is React JS?
In react component represents a part of the user interface.A application may have five components header,Side nav,Main content,footer and one root component which
contains other components i.e. Root component is  AppComponent which holds all other components.

Component code can be placed as java script file for example App Component is placed as App.js under your sample react application.
Component basically a code inside the .js file.

Types of component
1)Stateless Functional Component
Functional component is literally a java script functions Which return a html.
Functional component optionally receives of Properties which is refereed to as props and returns as HTML which describe UI.
ie
function Welcome(props){
  return <h1>Hello ,{props.name}</h1>
}

First Functional Component

  • Create one component as Greet.js in src/components folder.

import React from 'react'

function Greet() {
return <h1>Hello Pradeep</h1>
}
export default Greet

  • Import into App.js and Specify Greet Custom tag as below

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from './components/Greet'

function App() {
return (
<div className="App">
<header className="App-header">
<Greet/>
</header>
</div>
);
}

export default App;

2) Stateful Class Component
Class component is a fast component which extends Components class from react library.
Which must render method and  returning HTML.
i.e.
class Welcome extends React.Component{
  render(){
     return <h1>Hello, {this.props.name}</h1>
  }
}
Class components are basically ES6 classes.Similar to a functional component, class component  also can optionally receive props and return html.

Creating a simple class component:
1)Create a file Welcome.js file in component folder as below.
import React,{Component} from 'react'
class Welcome extends Component{
render(){
return <h1>First component class</h1>
}
}
export default Welcome
2)Whenever we are going to create a class component, need to include two imports
one is React and second one is {Component} class from react library.
3)To make a class a react class, there are two simple steps

  • Class should extend Component class from react lib.
  • Class has to implement render method and should return null or some HTML
4)Import class component in App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from './components/Greet'
import Welcome from './components/Welcome'

function App() {
return (
<div className="App">
<header className="App-header">
<Greet/>
<Welcome/>
</header>
</div>
);
}
export default App;

Start the server and feel the impact.



Sunday, 7 July 2019

React JS Installation

React JS Installation
For react we need two things installed
  • Node JS-Go to the official website for node and download the latest one<a href="https://nodejs.org/en/">https://nodejs.org/en/</a>
  • Text Editor-As per yout choice ie Visual Studio Code<a href="https://code.visualstudio.com/">https://code.visualstudio.com</a>
Install create-react-app using npm command
  • npm install create-react-app -g
This command is telling to npm that intall create-react-app package globally on your machine.
Command to check the version
  • create-react-app -version
How to create react app?
  • npx create-react-app myApp-app
Description:Creates new react app.
  • cd myApp-app
  • npm start
Description:To start react app.
Browse Below URL
  • http://localhost:3000/
Installation of some more libraries which will be useful when we start real time websites development.
REACT-ICONS
Include popular icons in your React projects easly with react-icons, which utilizes ES6 imports that allows you to include only the icons that your project is using.
This will be used to render some designed icons from centralized place.But to use them, we need to install this library.
REACT-ROUTER-DOM
This library mainly provides the routing strategies which are very useful in our web development.
Install this library using below command for your project
  • npm install react-router-dom

Tuesday, 29 January 2019

JAVA8:Stream API

Stream API is introduced in JDK 1.8 to support functional-style operations on streams of elements, such as map-reduce transformations on collections. Basically it follows filter-map-reduce operational pipeline technique on streams of elements to produce results.

Why Stream?

Streams differ from collections in several ways:

  • No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.
  • Functional in nature. An operation on a stream produces a result, but does not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
  • Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.
  • Possibly unbounded. While collections have a finite size, streams need not. Short-circuiting operations such as limit(n) or findFirst() can allow computations on infinite streams to complete in finite time. C
  • onsumable. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

Multiple ways to obtain stream:

What is stream Operations and Pipelines?

Stream operations are divided into intermediate and terminal operations and are combined to form stream pipelines. A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce.

  • Intermediate operations:Returns a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.  
  • Terminal operations:Terminal operations, such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used; if you need to traverse the same data source again, you must return to the data source to get a new stream. In almost all cases, terminal operations are eager, completing their traversal of the data source and processing of the pipeline before returning. Only the terminal operations iterator() and spliterator() are not; these are provided as an "escape hatch" to enable arbitrary client-controlled pipeline traversals in the event that the existing operations are not sufficient to the task.  

Sample pipeline Examples:

Filter-map-sum     

Wednesday, 2 January 2019

Python Data Types



Data Types

Since python is a dynamically typed programming language so no need to define datatype manually instead it will be identified based on value data type implicitly.
Data Type is a Type of value represented by the variable.

Various Data Types defined in Python as below:
1)int
2)float
3)complex
4)bool
5)str
6)bytes
7)bytearray
8)range
9)list
10)tuple
11)set
12)frozenset
13)dict
14)None
Note: In Python every thing is an object even an method also.

Explanation about each Data type:
1) int Data Type:
Python uses int data type to represent Integral values.
Program:
>>> a=10
>>> type(a)
Output:class 'int'
In how many ways we can represent int type:By default Python considers as decimal form only.
1)Decimal Form(Base-10):0 to 9
2)Binary Form(Base-2):0 and 1
Program
a=0b1111
a=0B1111
Output:15
Program:
a=-0b1111
output:-15
3)Octal Form(Base-8):0 to 7
Program:
>>> a=0o777
>>> a
Output:511
Program:
>>> a=0O777
>>> a
Output:511
4)Hexa Decimal(Base-16):0 to 9,a to f,A to F(Here Python is not case sensitive)
Program:
>>> a=0XFace
>>> a
Output:64206
Program:
>>> a=0xBeef
>>> a
Output:48879
Program:
>>> a=0xBeer
Output:SyntaxError: invalid syntax

2) float Data Type
Program:
>>> f=123.4435
>>>
>>> f
123.4435

Note:Exponential form is allowed under float data type.Big benefit of defining into exponential form is any bigger value can be represented into a shorter way.
Program:
>>> x=1.2e3
>>> x
1200.0

3) complex Data Type
If you want to develop scientific/complex program then always recommend to go for complex data type.
Syntax for complex data type is as a+bj
Where a represents Real Part and can be any data type
b represents Imaginary Part and can be only decimal.
j^2=-1 where j is mandatory.
Program:
>>> x=10+20j
>>> x
(10+20j)
>>> type(x)


Program:
>>> p=0b111+10j
>>> p
(7+10j)

Program: Operations with two complex equations
>>> a=10+20j
>>> b=20+10j
>>> a+b
(30+30j)

>>> a-b
(-10+10j)

To know about real and imaginary part using program
>>>a=10+20j
>>> a.real Here real is pre defined attribute/property by Python
10.0
>>> a.imag Here imag is pre defined attribute/property by Python
20.0

4) bool Data Type
Allowed values are True and False for bool data type where T and F always should be in caps.

Program:
>>> a=True
>>> a
True
>>> type(a)

>>> a=true
Traceback (most recent call last):
File "", line 1, in
a=true
NameError: name 'true' is not defined

Program:
>>> a='true'
>>> a
'true'
>>> type(a)


Program:
>>> True+True
2
>>> False+False
0
>>> True+False
1


5) str Data type
Any sequence of character is know as String.
Here we can represent str by using single quote or double quote but single quote is recommended.

Program:
>>> s=pradeep
Traceback (most recent call last):
File "", line 1, in
s=pradeep
NameError: name 'pradeep' is not defined
>>> s='pradeep'
>>> s
'pradeep'
>>> s="pradeep"
>>> s
'pradeep'
Note:For multiple line string literals we always need to use triple single/double quote.

Program:
If we use single quote to print multiple line string literals.
Test.py
s='pradeep
singh'
print(s)
Result:
D:\Python\Programs>py Test.py
File "Test.py", line 1
s='pradeep
^
SyntaxError: EOL while scanning string literal


Use triple single quote
Test.py
s='''pradeep
singh'''
print(s)
Result:
D:\Python\DurgaSir\Programs>py Test.py
pradeep
singh


slice Operator
To get a sub string(piece) of a string you need to use slice operator.
Syntax: s[begin:end]=>Returns substring from begin index to end-1 index.

Program:
>>> s="I am a software engineer"
>>> s[2:5]
'am '
>>> s[1:10]
' am a sof'
>>> s[0:10]
'I am a sof'

Default value for end index is end of the string if end index is not provided.
Program:
>>> s='pradeep'
>>> s[2:]
'adeep'
Default value for begin index is Start from the string if begin index is not provided.
Program:
>>> s='pradeep'
>>> s[:3]
'pra'
If not begin and end index is provided
Program:
>>> s='pradeep'
>>> s[:]
'pradeep'

How can we achieve jump by steps while getting sub string.
Syntax: s[begin:end:step]

Program:
>>> s='iamasoftwareengineer'
>>> s[1:10:2]
'aaota'
>>> s[1:10:3]
'ast'


Note: Python supports positive(Left to right) and negative(Right to Left) index both.
Program:
>>> s='pradeep'
>>> s[0]
'p'
>>> s[1]
'r'
>>> s[2]
'a'
>>> s[3]
'd'
>>> s[4]
'e'
>>> s[-1]
'p'
>>> s[-2]
'e'
>>> s[-3]
'e'

Repetition Operator:
Syntax: s*n->Repeats s String to n times
Program:
>>> s='pradeep'
>>> s*3
'pradeeppradeeppradeep'
>>> s*10
'pradeeppradeeppradeeppradeeppradeeppradeeppradeeppradeeppradeeppradeep'
Length of string:
Program:
>>> s='pradeep'
>>> len(s)
7


Python's Fundamental datatypes:

1)char ==>str type only
2)long ==>int type only

Type Casting or Type coersion:Python supports data type casting using multiple inbuilt functions
1)int():To convert any other type value to int type.
Program:
>>> int(123.345)
123
Note:Can not convert complex type to int type
Program:
>>> int(10+20j)
Traceback (most recent call last):
File "", line 1, in
int(10+20j)
TypeError: can't convert complex to int

Boolean to int:
>>> int(True)
1
>>> int(False)
0
str to int:String should contain only base 10 value.
Program:
>>> int('10')
10
Program:
>>> int("10.5")
Traceback (most recent call last):
File "", line 1, in
int("10.5")
ValueError: invalid literal for int() with base 10: '10.5'
Program:
>>> int(0b1111)
15
>>> int('0b1111')
Traceback (most recent call last):
File "", line 1, in
int('0b1111')
ValueError: invalid literal for int() with base 10: '0b1111'
2)float()
Program:
>>> float(10)
10.0

Program:
>>> float(10+20j)
Traceback (most recent call last):
File "", line 1, in
float(10+20j)
TypeError: can't convert complex to float
Program:
>>> float(True)
1.0
>>> float(False)
0.0

Program:
>>> float('10')
10.0
>>> float('10.5')
10.5
Program:
>>> float('ten')
Traceback (most recent call last):
File "", line 1, in
float('ten')
ValueError: could not convert string to float: 'ten'

Function:complex()

Will be used to conver other types to complex type.

There  are two forms of complex function found:

1)Form1: complex(x)=>Its implies that x+0j

2)Form 2: complex(x,y)=>x+yj

Programs:

>>> complex(10)
(10+0j)
>>> complex(10,20)
(10+20j)
>>> complex(True)
(1+0j)
>>> complex(True,True)
(1+1j)
>>> complex(False)
0j
>>> complex(False,False)
0j
>>> complex(False,True)
1j
>>> complex("10")
(10+0j)
>>> complex("10.5")
(10.5+0j)
>>> complex("ten")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
complex("ten")
ValueError: complex() arg is a malformed string
>>> complex(0B1111)
(15+0j)

>>> complex("5","10")>>> complex("5","10")     Traceback (most recent call last):  File "<pyshell#12>", line 1, in <module>    complex("5","10")TypeError: complex() can't take second arg if first is a string

 

Function: bool()

To convert other types to boolean.

 

Int Argument:

If we pass non zero value then bool returns always true other wise false.

Program:

>>> bool(1)
True
>>> bool(10)
True
>>> bool(0)
False
>>> bool(12)
True

float Argument:

If we pass except 0.0 value then bool returns always true.

Program:

>>> bool(0.0)
False
>>> bool(0.1)
True

complex Argument:

If both real and imaginary part are 0 then bool returns false other wise true.

Program:

>>> bool(10+20j)
True
>>> bool(0+10j)
True
>>> bool(0+0j)
False

>>> bool(0j)
False
>>> bool(1j)

str Argument:

if argument is empty string then bool returs as false other wise returns true.

>>> bool('')
False
>>> bool("pradeep")
True

>>> bool(' ')
True

Note:bool function never throws error for any data types.