Home Blog Page 7

Development with GitHub Copilot – Code Automation AI tool

0
install github copilot in android studio

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s discover how to automate code using GitHub Copilot AI tool.

Below Integrating copilot with IDE for development, Let’s understand:

What is Github Copilot?

  • GitHub Copilat is an AI took developed by GitHub partnering with OpenAI.
  • It assists developers by providing code autocompletion within popular code editor tools or Integrated Development Envirnoments (IDE’s) such as Android Studio, Visual Studio Code, JetBrains, Neovim.
  • This tool is trained on an extensive dataset comparising billions of lines of code that are public and are commonly used by developer.
  • GitHub Copilot uses machine learning & natural language processing to understand context and generate relevant code suggestions.
  • It helps developers save time and stay focused by offering intelligent code completion based on current context effectively.

How to Install Github Copilot?

It’s not hard to install Github Copilot in IDE’s. In this article installing Githuib Copilot into Android Studio IDE.

Follow Below Steps:

In Android Studio IDE just go to Plugin section and search for Github Copilot and click on Install button.

In Android Studio > File > Settings > Plugins

install github copilot in android studio

After Installing it, restart your IDE.

Once you restart your Android Studio IDE you will see “Welcome to GitHub Copilot”.

Just Login with your Github account to use this.

Now your IDE has power to suggest code for you on any language or framework you are working on.

github copilot suggesting code for you

Conclusion

Automated Development AI tools like Githib Copilot helps developer to boost their development speed. Explore the possibilities.

Dart Programs to Calculate mean variance and standard deviation

0
Dart program to calculate mean variance and standard deviation
Dart program to calculate mean variance and standard deviation

Hi Guy’s Welcome to Proto Coders Point. In this flutter dart programming article let’s understand what is mean variance & standard deviation & how to calculate them in dart programming language.

In data analysis, It’s is very crucial to understand the data tendency. mean, variance & standard deviation are main statistical data measures.

What is Mean, Variance & Standard deviation?

Mean:

Mean is calculated by dividing sum of all the numbers in a given set (array)by the total number of numbers. 

Mean = (Sum of all the observations/Total number of observations)


Variance:

Variance is calculated using mean of the squared differences from the average of the data set (array). It is a statistical measure that quantifies the amount of variability or dispersion within a dataset

variance = s^2 = Σ(xi - x̅)^2 / (N - 1);

xi = each value from the data set.
= Mean.
N = Number of value in the data set.


Standard Deviation:

is calculated by square root of variance.

SD = sqrt(variance)


Dart Program to find mean variance and standard deviation

Let’s calculate mean, variance & standard deviation using versatile programming language DART.

import 'dart:math';

void main() {
  List<double> data = [0.6, 1.2, 6, 3, 8, 11, 13, 8, 9.3, 9.4];

  // Calculate the mean
  double mean = data.reduce((a, b) => a + b) / data.length;

  // Calculate the variance
  double variance = data.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) /
      (data.length - 1);

  // Calculate the standard deviation
  double standardDeviation = sqrt(variance);

  print('Mean: $mean');
  print('Variance: $variance');
  print('Standard Deviation: $standardDeviation');
}

Mean: 6.95
Variance: 17.402777777777782
Standard Deviation: 4.171663670261276


Retrieve a list of dates between two given dates in Flutter Dart

0
Return List of Date between two Dates

There might be a need during the dart/flutter app development where you need to write a function that return list of all the dates between two given list. This functionality is useful in such scenarios where you need to work on date range and display it to the user or on calender into your flutter application.

In this article let’s check out 2 ways by which we can get list of dates between given dates

1. Using DateTime() and Simply use For loop to filter data

List<DateTime> getDaysInBetween(DateTime startDate, DateTime endDate) {
  List<DateTime> days = [];
  for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
    days.add(startDate.add(Duration(days: i)));
  }
  return days;
}

// try it out
void main() {
 DateTime startDate = DateTime(2024, 2, 1);
  DateTime endDate = DateTime(2024, 2, 10);

  List<DateTime> days = getDaysInBetween(startDate, endDate);

  // print the result without time
  days.forEach((day) {
    print(day.toString().split(' ')[0]);
  });
}

In above example, We have created a function ‘getDaysInBetween’ that accepts 2 parameter i.e. startDate & endDate. This main task of this function is getting all the date between the given date range.

This function will have a for loop that will iterate to endDate using difference method to calculate the number of days between the startDate & endDate.

Then this loop will add each date to the List of type DateTime by incrementing day by 1 using Duration.

Then finally pass two dates to the getDaysInBetween and get the list.

but the date list you receive will also contain time in it so we need to split the time, therefore we make use of forEach loop to iterate the list and print it on screen.

Output


2. Using List.generate() method

List<DateTime> getDaysInBetween(DateTime startDate, DateTime endDate) {
  final daysToGenerate = endDate.difference(startDate).inDays + 1;
  return List.generate(daysToGenerate, (i) => startDate.add(Duration(days: i)));
}

// try it out
void main() {
 DateTime startDate = DateTime(2024, 2, 1);
  DateTime endDate = DateTime(2024, 2, 10);

  List<DateTime> days = getDaysInBetween(startDate, endDate);

  // print the result without time
  days.forEach((day) {
    print(day.toString().split(' ')[0]);
  });
}

You can also get list of dates between any two given dates using simply using inbuilt method of dart language i.e. List.generate().


Speech to Text In Flutter – Speech Recognition

0
Speech to Text in Flutter
Speech to Text in Flutter

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Tutorial will learn how to empower your flutter application with Speech Recognition feature using which user can convert his speak in to text in your flutter application.

Video Tutorial

Speech to Text in Flutter

Giving a feature like Speech to Text in flutter gives a ability to users to easily interact with application by just their voice.

To achieve this we are going to making use of a flutter package called speech_to_text .

Steps to Implement Speech to Text in Flutter App

1. Create A Flutter Project

In your favorite IDE Start by creating a new Flutter Project by using below command if you are using VSCode

flutter create project_name 

Skip this step if you want to integrated Speech to text in existing project, Simple Open the Flutter project where to want to add this feature.


2. Add following flutter depencencies in pubspec.yaml file

Open pubspec.yaml and under depencencies: section add the following line

dependencies:
  speech_to_text:

Then hit below command in terminal

flutter pub get

This will download the speech_to_text package into your flutter project as external library.

To use it simple import it where required example in your flutter project main.dart file.


3. Adding Necessary permission

Android:

In Android module of flutter project open AndroidManifest.xml file and add below permission

Flutter Project > android > app > src > main > AndroidManifest.xml

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

Then to make this package work, We need to have minSdkVersion: 24 and targetSdkVersion: 32. To update it goto build.gradle file

Flutter Project > android > app > build.gradle

iOS:

Same in iOS also we need to permission to access iPhone or iPad device microphone.

Open Podfile, and look for flutter_additional_ios_build_settings(target) and below code in it.

target.build_configurations.each do |config|
     config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] || = [
     '$(inherited)',
     # dart: PermissionGroup.microphone
     `PERMISSION_MICROPHONE=1`,
]
end

Then open Info.plist and inside <dict> </dict> block, add below lines

Flutter Project > ios > Runner > Info.plist

<key> NSMicrophoneUsageDescription </key>
<string> microphone </string>

Flutter initState ask user mic permission

Now we need to add user permission to grant access to use Microphone immediately as our flutter app launch.

SpeechToText speechToText = SpeechToText();

The initState() method is overridden to call CheckMic() method and initialize the microphone availabilty.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkMic();

  }
void checkMic() async{
    bool micAvailable = await speechToText.initialize();

    if(micAvailable){
      print("MicroPhone Available");
    }else{
      print("User Denied the use of speech micro");
    }
  }

Flutter Speech listener

SpeechToText speechToText = SpeechToText();

speechToText.listen(
        listenFor: Duration(seconds: 20),
        onResult: (result){
        setState(() {
                   textSpeech = result.recognizedWords;
                    isListening = false;
             });
         }
  );

The above code makes use of listen() method that comes in speech_to_text package and start the recording.

Here we have 2 properties listenFor: Specifies the duration the mic to listen to the speech, then the recording speech is stored in onResult result parameter which we can used as result.recognizedWords to convert the speech to text in flutter.

Complete Source – Flutter Speech to Text

main.dart

import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var textSpeech = "CLICK ON MIC TO RECORD";
  SpeechToText speechToText = SpeechToText();
  var isListening = false;

  void checkMic() async{
    bool micAvailable = await speechToText.initialize();

    if(micAvailable){
      print("MicroPhone Available");
    }else{
      print("User Denied th use of speech micro");
    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkMic();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
                Text(textSpeech),

                GestureDetector(
                  onTap: () async{
                    if(!isListening){
                      bool micAvailable = await speechToText.initialize();

                      if(micAvailable){
                        setState(() {
                          isListening = true;
                        });

                        speechToText.listen(
                          listenFor: Duration(seconds: 20),
                          onResult: (result){
                            setState(() {
                              textSpeech = result.recognizedWords;
                               isListening = false;
                            });
                          }
                        );


                      }
                    }else{
                        setState(() {
                          isListening = false;

                          speechToText.stop();
                        });
                    }
                  },
                  child: CircleAvatar(
                    child: isListening ? Icon(Icons.record_voice_over): Icon(Icons.mic),
                  ),
                )
            ],
          ),
        ),
      ),
    );
  }
}

Similar Tutorials

Text Recognition Using Firebase ML Kit – Text Recognition in Android

Flutter Form Validation – Button State Active or InActive

0
Flutter Form Validation - BUTTON SHOULD NOT BE CLICKABLE UNTIL validated
Flutter Form Validation - BUTTON SHOULD NOT BE CLICKABLE UNTIL validated

Hi Guy’s, Welcome to Proto Coders Point. In this Flutter Tutorial Article, We will Learn how to enhance user experience in your Flutter applications by enabling a feature i.e. A button should be clickable only when form Textfields data are properly validated.

Source Code – Flutter TextField Form Validation – Disable Button Until Form is Valid

As you all know that Form Validation is very important for user input, making sure that submitted form is valid and data is received or submitted is not empty or irrelevant.

In flutter we have 'Form' widget for implementing form validation. This Article is specially for integrating submit button disable or active state depending on validation of form.

Form Validation with GlobalKey

In flutter to validate the data entered into the textfield of the form we can utilize the GlobalKey<FormState>, This contains the functionality to validate the form & manage it state.

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

The _formKey is attached to Form Widget to enable the access to the form state and validate it’s functionality.


Managing Button State – Clickable or Disabled

The Form Widget has a property onChanged() which keep calling then use enter data in form textField.

Here to Control the state of the button, We have use a boolean variable that will be updated to true if _formKey.currentState!.validate() return true.

_formKey.currentState!.validate() => This function check if all the textField in the form meet with validated criteria. if validation is successful, the variable isValid is set to true.

bool isValid = false;

void onChange() {
  setState(() {
    isValid = _formKey.currentState!.validate();
  });
}

Now we can use this isValid variable to make button Clickable or NotClickable.


Button Activation with onPressed

Flutter Buttons onPressed when set to null, It means button is disable or NotClickable and the button color is set to grey automatically.

ElevatedButton(
         onPressed: isValid ? (){
                     // Do something
         } : null,
       child: Text("Submit"),

 ),

Here onPressed function is triggered only when isValid is true, Which ensure that the button remains inactive until the form is valid.

Complete Source Code

TextField InputDecoration Design

Create a File by name ‘input_TextFieldDecoration.dart’, The below code is just for giving stying to TextField

import 'package:flutter/material.dart';

InputDecoration buildInputDecoration(IconData icons,String hinttext) {
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
          color: Colors.green,
          width: 1.5
      ),
    ),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
    enabledBorder:OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
  );
}

FormPage.dart

import 'package:flutter/material.dart';
import 'input_TextFieldDecoration.dart';

class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {

  late String name,email,phone;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool isValid = false;

  void onChange(){
    setState(() {
      isValid = _formKey.currentState!.validate();
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            onChanged: (){
              onChange();
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const CircleAvatar(
                  radius: 70,
                  backgroundColor: Colors.lightGreen,
                  child: Icon(Icons.abc_sharp,size: 120,),
                ),
                const SizedBox(
                  height: 15,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom:15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration: buildInputDecoration(Icons.person,"Full Name"),
                    validator: (value){
                      if(value!.isEmpty){
                        return "Please Enter name";
                      }
                      return null;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.email,"Email"),
                    validator: (value){
                      if(value!.isEmpty){
                        return "Please Enter Email";
                      }
                      // Rajat@gmail.com
                      if(!RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$').hasMatch(value)){
                        return 'Please a valid Email';
                      }



                      return null;
                    },
                  ),
                ),
                SizedBox(
                  width: 200,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: isValid ? (){
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Valid Form")));
                    } : null,
                    child: Text("Submit"),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Conclusion

In this Flutter Code, we illustrated a straightforward implementation of form validation with button state management, dynamically making button active or inactive based on form validation.

NodeJS Data Encryption & Decryption using CryptoJS Module

0
NodeJS Data encryption description using crypto js library
NodeJS Data encryption description using crypto js library

Hi Guys, Welcome to Proto Coders Point, Data Encrypting & Data Decryption is must requirement when it come to data security in any application development may be it Web Application, Mobile Application of any other Application. Especially when data or information that is transmit is sensitive and can’t be directly readable by the app users.

To make the data security high it’s always recommended to better apply an encryption and decryption during data transmission from server to client.

Video Tutorial

NodeJS Data Encryption & Decryption using Crypto-JS NodeJS Module

There are various NodeJS Module by which NodeJS Developer can achieve data encryption & decryption within the application. Will make use of popular and most commonly used module/library called 'crypto-js'.

Below is a simple example how to make use of 'crypto-js' module for encryption & decryption of data in NodeJS. For this example will create a NodeJS Express server and create 2 API routes, one for encryption and another for decryption.

Necessary Packages Required:

We need 4 dependencies modules for Implementation

  1. body-parser: Used as a middleware for parsing incoming request bodies in Express.
  2. cors: Middleware for enabling Cross-Origin Resource Sharing in web applications.
  3. express: Web Application framework of NodeJS used for creating NodeJS Server.
  4. crypto-js: is a JavaScript library used for data encryption & decryption using cryptographic functions.

Install them using below cmd

npm install body-parser cors express crypto-js

How to make use of NodeJS Crypto-JS to encrypt data

function encrypt(data,key){
    const cipherText = CryptoJS.AES.encrypt(data,key).toString();
    return cipherText;
}

The above function accept 2 parameter i.e data & key. Here data is the msg or information that you want to encrypt and key is basically a secret key that is been used by CryptoJS to encrypt that data.

The CryptoJS loibrary in NodeJS making use of Advanced Encryption Standard (AES) algorithm to encrypt the data.

The key is very important as it used for both data encryption & decryption.


How to decrypt data in NodeJS using CryptoJS

To decrypt data in nodeJS we need encrypted format of data and the key that was used to encrypt the data.

function decrypt(cipherText,key){
    try {
        const bytes = CryptoJS.AES.decrypt(cipherText,key);

        if(bytes.sigBytes > 0){
            const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
            return decryptedData;
        }else{
            throw new Error('Decryption Failed Invalid Key')
        }
    } catch (error) {
        throw new Error('Decryption Failed Invalid Key')
    }

}

in above example cipherText means encrypted data and key is used to decrypt the data.


Complete Source Code – NodeJS Data Encryption & Description using CryptoJS library

app.js

Here we have 2 API Routes, encrypt & decrypt and as the make of this API itself says that it can we used for data encryption & decryption.

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const CryptoJS = require('crypto-js');

const app = express();

app.use(cors());

app.use(bodyParser.json({limit:'50mb'}))
app.use(bodyParser.urlencoded({limit:'50mb',extended:true}));


app.get('/',(req,res)=>{
    res.send(" Say Hello To Proto Coders Point, Please Subscribe")
});


function encrypt(data,key){
    const cipherText = CryptoJS.AES.encrypt(data,key).toString();
    return cipherText;
}


function decrypt(cipherText,key){
    try {
        const bytes = CryptoJS.AES.decrypt(cipherText,key);

        if(bytes.sigBytes > 0){
            const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
            return decryptedData;
        }else{
            throw new Error('Decryption Failed Invalid Key')
        }
    } catch (error) {
        throw new Error('Decryption Failed Invalid Key')
    }

}

app.post('/encrypt',(req,res)=>{
    const { data, key} = req.body;
    const encrypted = encrypt(data,key);
    res.json({encrypted});
});

app.post('/decrypt',(req,res)=>{
    const { encryptedData, key } = req.body;

    const decryptedData = decrypt(encryptedData, key);
    res.json({decryptedData});
});


module.exports = app;

index.js

This is the starting point of our NodeJS Project

start the nodeJS server using below cmd

node index.js