Showing posts with label Android development. Show all posts
Showing posts with label Android development. Show all posts

Saturday, April 4, 2020

Tensor flow model that convert temperature in Celsius to Fahrenheit .



Celsius to Fahrenheit convertor



steps involved are:


1) Importing necessary dependencies:


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


2) Set up training data:


celsius_q    = np.array([0, 8, 15, 22,100 ],  dtype=float )
fahrenheit_a = np.array([32, 46.4, 59, 71.6,180],  dtype=float )

for i,c in enumerate(celsius_q):
    print("{} degree Celcius = {}  degree Fahrenhet" .format(c, fahrenheit_a[i]))




3) Defining the layer for CNN:

l0 = tf.keras.layers.Dense(units = 1, input_shape=[1] )




4) Assembling layer into model:

model = tf.keras.Sequential([l0])




5)Compile the model with loss and optimizer function:


model.compile(loss = 'mean_squared_error',
             optimizer = tf.keras.optimizers.Adam(0.1))



6)Training the model:



history = model.fit(celsius_q, fahrenheit_a, epochs = 500, verbose = False )
print("Finished training the model")






7) Displaying trained statistics:

plt.xlabel('Epoch Number')
plt.ylabel('Loss Magnitude')
plt.plot(history.history['loss'])





8)predicting values:


print(model.predict([100]))


print(model.predict([0]))










by running above code in Jupyter notebook step by step you can observe how things are going on. 















Wednesday, March 25, 2020

How to start with React-native application development?



About react native




1)What is React Native ?

->The java script library for building user interface is called React.
->Typically used for web development.
->It is a collection of special react components.
->Componenet compiled to Native widgets.
->Native platform APIs exposed to javascript.
->Connect javascript and native platform code.



2)react-native eg:

const App = props =>{
  return(
       <View>
      <Text>Hay bot</Text>
   </View>
  )





3)Create a new react native app


  a)expo cli/tool(using this approach for this tutorial)

  ->third party service
  ->free
  ->managed app development workflow
  ->lots of convenience and utility features: simplifies development





  b)react native cli

  ->managed by reactnative team
  ->bare bone development
  ->almost no convenience or utility feature
  ->full flaxibility: integrate with any native code






4.1)how expo works?

->goto expo.io
->install Node.js in your PC if not
->get the command line tool(eg:Anaconda powershell prompt)
   npm install expo-cli --global
->Create your first project(navigate to the project directory folder)
    expo init my-new-project
    cd my-new-project
    expo start
->use expo-client app in android mobile and scan qr code yields to app lunch which your going to building.

->this should give up and running output app.
->open the app folder in any text editor to further code.





4.2)how react native cli work?

  (in one cmd)
->npm install -g react-native-cli
->npm install -g yarn
->react-native init myapp
->cd myapp
->react-native start
  (in another cmd and goto myapp folder)
->react-native run-android














a)reactnatibe basics

->core components
  i)built into react native
  ->"translation" to Native UI widgets provided by React Native

  ->eg:
    <View>
<Text>
<Button>/<Touchable...>
<TextInput>
<Image>




   ii)Your UIs/Custom Components

   ->Composed of these "Core" Components and other build-in Components

   ->eg:
     const MyTitle = props=>{
   return(
     <View>
   <Text>{props.title}</Text>
</View>
    );
}


iii)styling

->inline style
->styleSheet objects(prefered)
->written in javascript
->Based on CSS syntax, influenced by CSS




<===============lets build an simple app ======================>

1)initially app.js code :





import React from 'react';
import { StyleSheet, Text, View} from 'react-native';


export default function App() {
  return (
    <View style={styles.container}>
      <Text>hi dude</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});



2)After making app, app.js code:


import React, {useState} from 'react';
import { StyleSheet, Text, View, Button, TextInput} from 'react-native';


export default function App() {
  const [enteredGoal, setEnteredGoal] = useState(' ');
  const [courseGoals, setCourseGoals] = useState([]);



  const goalInputHandler = (enteredText) => {
     setEnteredGoal(enteredText);
  };

  const addGoalHandler= ()=>{
     setCourseGoals(currentGoals =>[...currentGoals, enteredGoal]);
     console.log(enteredGoal);

  };





  return (
    <View style={styles.mainView}>
        <View style={styles.inputContainer}>
           <TextInput 
           placeholder={"Goal to achive"} 
           placeholderTextColor ={"green"}
           style={styles.inputField} 
           onChangeText = {goalInputHandler}
           />
           <Button 
           title={"Add me!"}  
           color={"coral"}
           onPress={addGoalHandler}
           />
        </View> 
        <View style={styles.showdataview}>
          {courseGoals.map((goal) => <Text>{goal}</Text>)}
        </View>
    </View>
  
  );
}




const styles = StyleSheet.create({
  mainView:{
    paddingTop:30,
    padding:5,
    
  },

  inputContainer:{
    flexDirection:"row",
    justifyContent:"space-evenly",
    },

  inputField:{
    backgroundColor:"lime",
    paddingStart:20,
    width:"75%",
    borderColor:"cornflowerblue",
    borderWidth: 2,
    },

  showdataview:{
    backgroundColor:"pink",
    height: "100%",
    borderColor: "black",
    borderWidth:2,
  },

});

Brief documentation of React ?




About react





1)Introduction



->It is a javaScript library for building user interfaces.
->It is used to build single page application.
->Allows us to create reusable UI components.
->It is created by facebook.
->It is tool for building UI components.





2)How does react works?

->It creates a VIRTUAL DOM in memory.
->It does necessary manipulation in memory before making change in browser DOM.
->It only changes what needs to be changed.




3)React Components

->components are independent and reusable bitd of code.
->components come in two type.




  a)Class component

  ->components name start with capital letter.
  ->Include the "extends React.Component" statement.
  ->Above statement create an inheritance to React.Component.
  ->Give your component excess to React.
  ->Requires a render() method, this method returns HTML.

  ->eg:
    class Car extends React.Component {
  render(){
    return <h1>I am class components </h1>;
  }
}
    //display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));




  b)function component

  ->similer to class component.
  ->Does not have render() method.
  ->Does not support inheritance.
  ->class component is more preferred.

  ->eg:
    function Car(){
  return <h1>I am function components </h1>;
}
    //display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));




4)Component constructor

->To initiate the component properties called state.
->used in class component.
->To support the inheritance of the parent component "super()" method
  is called in constructor function.
->"super()" method executes the parent components constructor function.
->class components have access to all the function of parent component
  "React.Component".

->eg:
  class Car extends React.Component{
   constructor(){
     super();
this.state = {name: "Ford"};
   }
   render(){
     return <h2>I am class component with constructor:{this.state.name}</h2>
   }
  }  





5)Props

->Way of handling component properties.

->eg:
  class Car extends React.Component{
    render(){
  return <h2>I am a {this.props.name} car </h2>;
}
  }
  ReactDom.render(<Car name={"Ford"}>,document.getElementById('root'));









6)Components in Components

->Can refer to components inside other components.

->eg:
  class Car extends React.Component{
    render(){
  return (
    <h2>I am a Car ! </h2>
  );
}
  }
  
  class Garage extends React.Component{
    render(){
  return(
    <div>
  <h1>Who lives in my Garage? </h1>
  <Car/>
</div>
  );
}
  }
  
  ReactDOM.render(<Garage />, document.getElementById('root'));
  




7)Components in files

->create a new file with a .js file extension and put the code inside it.

->eg:
  //code of a.js file
  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    render() {
      return <h2>Hi, I am a Car!</h2>;
    }
  }

  export default Car;
  
  //code of app.js file
  import React from 'react';
  import ReactDOM from 'react-dom';
  import Car from './App.js';

  ReactDOM.render(<Car />, document.getElementById('root'));








8)React Lifecycle


->Each component in react has a lifecycle.
->The three phases are:

  a)Mounting

  ->process of putting element into the DOM.
  ->react has four build-in methods that gets called,
    in order, when mounting a component.





    i)constructor()

->called by react every time when you make a component

->eg:
  class Header extends React.Component{
    constructor(props){
  super(props);
  this.state = {favoritecolor : "pink"};
}
render(){
  return(
    <h1>My favorite color is {this.state.favoritecolor}</h1>
  );
}
  } 
  ReactDOM.render(<Header/>, document.getElementById('root'));
  





    ii)getDerivedStateFromProps()

->method is called right before rendering the element(s) in the DOM.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        static getDerivedStateFromProps(props, state) {
          return {favoritecolor: props.favcol };
        }

        render() {
          return (
            <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          );
        }
      }

      ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


    iii)render()

->Output the HTML documents in the DOM.

->eg:
  class Header extends React.Component{
    render(){
  return(
    <h1>This is the content of the header component</h1>
  );
}
  }
  
  ReactDom.render(<Header />, document.getElementById('root'));





    iv)componentDidMount()

    ->called after render() method

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }
        componentDidMount() {
          setTimeout(() => {
          this.setState({favoritecolor: "yellow"})
          }, 1000)
        }
        render() {
          return (
            <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          );
        }
      }

      ReactDOM.render(<Header />, document.getElementById('root'));



 


  b)Updating

  ->second phase in which component updated.
  ->five methods are called.



    i)getDerivedStateFromProps()

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        static getDerivedStateFromProps(props, state) {
          return {favoritecolor: props.favcol };
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
     
}

     ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));





ii)shouldComponentUpdate()

->return boolean value, default value is true.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        shouldComponentUpdate() {
          return false;
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
       }

      ReactDOM.render(<Header />, document.getElementById('root'));
  
 


 

iii)render()

->It is always called when components gets updated.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
      }

      ReactDOM.render(<Header />, document.getElementById('root'));









iv)getSnapshotBeforeUpdate()

->have access to the props and state before the update.
->to use this method, you should also include the componentDidUpdate()

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        componentDidMount() {
          setTimeout(() => {
            this.setState({favoritecolor: "yellow"})
          }, 1000)
        }

        getSnapshotBeforeUpdate(prevProps, prevState) {
          document.getElementById("div1").innerHTML =
          "Before the update, the favorite was " + prevState.favoritecolor;
        }

        componentDidUpdate() {
          document.getElementById("div2").innerHTML =
          "The updated favorite is " + this.state.favoritecolor;
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <div id="div1"></div>
              <div id="div2"></div>
            </div>
           );
        }
      }


     ReactDOM.render(<Header />, document.getElementById('root'));






v)componentDidUpdate()

->called after the component is updated in the DOM.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        componentDidMount() {
          setTimeout(() => {
            this.setState({favoritecolor: "yellow"})
          }, 1000)
        }


        componentDidUpdate() {
          document.getElementById("mydiv").innerHTML =
          "The updated favorite is " + this.state.favoritecolor;
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <div id="mydiv"></div>
            </div>
          );
        }
     }

     ReactDOM.render(<Header />, document.getElementById('root'));
  
 
 

 

  c)Unmounting

  ->phase when the component is removed from DOM.
  ->one method only.


    i)componentWillUnmount()

    ->called when component is about to remove

->eg:
  class Container extends React.Component {
        constructor(props) {
          super(props);
          this.state = {show: true};
        }

        delHeader = () => {
          this.setState({show: false});
        }

        render() {
          let myheader;
          if (this.state.show) {
            myheader = <Child />;
           };
          return (
            <div>
              {myheader}
              <button type="button" onClick={this.delHeader}>Delete Header</button>
            </div>
          );
        }
     }

    class Child extends React.Component {
      componentWillUnmount() {
        alert("The component named Header is about to be unmounted.");
      }
      
  render() {
        return (
          <h1>Hello World!</h1>
        );
      }
    }

    ReactDOM.render(<Container />, document.getElementById('root'));
 
 











Saturday, December 8, 2018

flashlight application for android, code

Description:
          This is android application developed in android studio using java and XML programming language.Here is ImageView which is used to get device camera permission after on click and a button which is used to ON/OFF the flash of device. 





  1. IDE used => Android studio 3.1.0
  2. photo used:
drawable

(i)photo
name =btn_switch_off.PNG


button off


(ii)photo
name =btn_switch_on.PNG
button on


(iii)photo
name =icon.PNG




(iv)photo
name =wall.PNG



  1. AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dell.flashlight">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:roundIcon="@drawable/icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Java class

class 1 :MainActivity.class :

package com.example.dell.flashlight;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button buttonEnable;
    private ImageView imageFlashlight;
    private static final int CAMERA_REQUEST = 50;
    private boolean flashLightStatus = false;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonEnable =(Button)findViewById(R.id.buttonEnable);
        imageFlashlight =(ImageView)findViewById(R.id.imageFlashlight);


        final boolean hasCameraFlash = getPackageManager().
                hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        boolean isEnabled = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;

        buttonEnable.setEnabled(!isEnabled);
        imageFlashlight.setEnabled(isEnabled);

        buttonEnable.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, CAMERA_REQUEST);
            }
        });



        imageFlashlight.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                if (hasCameraFlash) {
                    if (flashLightStatus)
                        flashLightOff();
                    else                        flashLightOn();
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    private void flashLightOn() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
            flashLightStatus = true;
            imageFlashlight.setImageResource(R.drawable.btn_switch_on);
        } catch (CameraAccessException e) {
        }
    }



    private void flashLightOff() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, false);
            flashLightStatus = false;
            imageFlashlight.setImageResource(R.drawable.btn_switch_off);
        } catch (CameraAccessException e) {
        }
    }


    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode) {
            case CAMERA_REQUEST :
                if (grantResults.length > 0  &&  grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    buttonEnable.setEnabled(false);
                    buttonEnable.setText("Camera Enabled");
                    imageFlashlight.setEnabled(true);
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

layout

layout 1:activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/wall"
    tools:context=".MainActivity">
    <ImageView        android:id="@+id/imageFlashlight"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/btn_switch_off"
        android:contentDescription="@string/todo" />
    <Button        android:id="@+id/buttonEnable"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
        android:textSize="20sp"
        android:text="@string/enable_camera"
        android:textStyle="bold|italic"
        android:background="#000000"
       android:textColor="#ffffff"
        android:layout_above="@id/imageFlashlight"
        android:layout_marginBottom="40dp"/>

</RelativeLayout>


values

1.color.xml

<?xml version="1.0" encoding="utf-8"?><resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>


2.strings.xml

<resources>
    <string name="app_name">flashlight</string>
    <string name="enable_camera">Enable Camera</string>
    <string name="todo">TODO</string>
</resources>

3.styles.xml

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>


dependencies

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'