code-rag-bench/online-tutorials huggingface dataset:
How many ways are there to initialize a final variable in java?

In Java, final is the access modifier which can be used with a filed, class and a method.
When a method if final it cannot be overridden.
When a variable is final its value cannot be modified further.
When a class is final it cannot be extended.
Once you declare a final variable, it is a must to initialize it. You can initialize the final instance variable −
At the time of declaration as.
public final String name = "Raju";
public final int age = 20;
Within an instance (non-static) block.
{
   this.name = "Raju";
   this.age = 20;
}
Within a default constructor.
public final String name;
public final int age;
public Student(){
   this.name = "Raju";
   this.age = 20;
}
Note − If you try to initialize the final instance variable elsewhere, a compile-time error will be generated.
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them at the time of declaration −
 Live Demo
public class Student {
   public final String name = "Raju";
   public final int age = 20;
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}
Name of the Student: Raju
Age of the Student: 20
In the following Java program, the class Student contains two final variables− name, age and, we are initializing them within an instance block −
 Live Demo
public class Student {
   public final String name;
   public final int age; {
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}
Name of the Student: Raju
Age of the Student: 20
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them within a default constructor −
 Live Demo
public class Student {
   public final String name;
   public final int age;
   public Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}
Name of the Student: Raju
Age of the Student: 20
How to check two numbers are approximately equal in JavaScript ? - GeeksforGeeks

31 Mar, 2021
Given two numbers and the task is to check the given numbers are approximately equal to each other or not. If both numbers are approximately the same then print true otherwise print false.
Example:
Input:  num1 = 10.3
        num2 = 10

Output: true
Approach: To check the numbers are approximately the same or not, first, we have to decide the epsilon value. Epsilon is the maximum difference between two numbers, if the difference of the numbers is less than or equal to epsilon then the numbers are approximately equal to each other. So first we create a function named checkApprox which takes three arguments num1, num2, and epsilon. Now check the absolute difference of num1 and num2 is less than epsilon or not.
Example 1:
Javascript
<script>const checkApprox = (num1, num2, epsilon) => {    // Calculating the absolute difference  // and compare with epsilon  return Math.abs(num1 - num2) < epsilon;}  console.log(checkApprox(10.003, 10.001, 0.005));</script>
Output:
true
Example 2:
Javascript
<script>const checkApprox = (num1, num2, epsilon = 0.004) => {  return Math.abs(num1 - num2) < epsilon;}  console.log(checkApprox(Math.PI / 2.0, 1.5708));</script>
Output:
true
Example 3:
Javascript
<script>const checkApprox = (num1, num2, epsilon = 0.004) => {  return Math.abs(num1 - num2) < epsilon;}  console.log(checkApprox(0.003, 0.03));</script>
Output:
false
ES6
javascript-math
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Bootstrap 4 .border-0 class

Use the border-0 class in Bootstrap to eliminate all borders from an element as shown below −
<div class="mystyle border border-0">
  No border
</div>
We have also set CSS style above −
.mystyle {
  width: 120px;
  height: 100px;
  margin: 10px;
  background: gray;
}
You can try to run the following code to implement the border-0 class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <style>
    .mystyle {
      width: 120px;
      height: 100px;
      margin: 10px;
      background: gray;
    }
    </style>
  </head>
<body>
  <div class="container">
    <h4>Two Rectangles</h4>
    <div class="mystyle border border-success">orange border</div>
    <div class="mystyle border border-0">No border</div>
  </div>
</body>
</html>
jQuery - eq( index ) Method

The eq( index ) method reduces the set of matched elements to a single element.
Here is the simple syntax to use this method −
selector.eq( index )

Here is the description of all the parameters used by this method −
index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1.
index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1.
Following is a simple example which adds the color to second list item.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("li").eq(2).addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li>list item 1</li>
            <li>list item 2</li>
            <li>list item 3</li>
            <li>list item 4</li>
            <li>list item 5</li>
            <li>list item 6</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
Following is an example showing a simple usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("li").eq(2).addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li>list item 1</li>
            <li>list item 2</li>
            <li class = "selected">list item 3</li>
            <li>list item 4</li>
            <li>list item 5</li>
            <li>list item 6</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Add an element to specified index of ArrayList in Java

An element can be added to the specified index of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the specific index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add(0, "Dog");
      aList.add(1, "Cat");
      aList.add(2, "Horse");
      aList.add(2, "Pig");
      aList.add(3, "Cow");
      System.out.println("The ArrayList elements are: " + aList);
   }
}
The ArrayList elements are: [Dog, Cat, Pig, Cow, Horse]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified index in the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add(0, "Dog");
aList.add(1, "Cat");
aList.add(2, "Horse");
aList.add(2, "Pig");
aList.add(3, "Cow");
System.out.println("The ArrayList elements are: " + aList);
MySQL Tutorial

MySQL is a widely used relational database management system (RDBMS).
MySQL is free and open-source.
MySQL is ideal for both small and large applications.
With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Insert the missing statement to get all the columns from the Customers table.
 * FROM Customers;

Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All SQL Examples
Test your MySQL skills at W3Schools!
Start MySQL Quiz!
At W3Schools you will find a complete reference of MySQL data types and functions:
MySQL Data Types
MySQL Functions
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Checking for Null or Empty in Java.

We can check whether a particular String is empty or not, using isBlank() method of the StringUtils class. This method accepts an integer as a parameter and returns true if the given string is empty, or false if it is not.
 Live Demo
import org.apache.commons.lang3.StringUtils;

public class Sample {
   public static void main(String args[]) {
      String str = "";
      Boolean bool = StringUtils.isBlank(str);
      System.out.println(bool);
   }
}
true
Add MD5 hash value to MongoDB collection?

To add MD5 hash value, use hex_md5(). Let us first create a collection with documents −
>db.addMd5HashValueDemo.insertOne({"UserName":"Adam","UserPassword":"Adam123456"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6a4c66d78f205348bc619")
}
>db.addMd5HashValueDemo.insertOne({"UserName":"Chris","UserPassword":"Chris_121#"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6a4e46d78f205348bc61a")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.addMd5HashValueDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd6a4c66d78f205348bc619"), "UserName" : "Adam", "UserPassword" : "Adam123456" }
{ "_id" : ObjectId("5cd6a4e46d78f205348bc61a"), "UserName" : "Chris", "UserPassword" : "Chris_121#" }
Following is the query to add md5 hash value to mongo collection −
> db.addMd5HashValueDemo.find().forEach( function(documentPass){
   documentPass.Value = hex_md5(documentPass.UserPassword);
   db.addMd5HashValueDemo.save(documentPass);
});
Let us check the document once again −
> db.addMd5HashValueDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd6a4c66d78f205348bc619"), "UserName" : "Adam", "UserPassword" : "Adam123456", "Value" : "6523857c2bf79b63fd5fa0322575f7be" }

{ "_id" : ObjectId("5cd6a4e46d78f205348bc61a"), "UserName" : "Chris", "UserPassword" : "Chris_121#", "Value" : "3391ccbe33624258cafa23aa50301615" }
Why can I throw null in Java and why does it upcast to a NullPointerException?

In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.
Object obj = null;
But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.
public class Demo {
   String name = "Krishna";
   int age = 25;
   public static void main(String args[]) {
      Demo obj = null;
      System.out.println(obj.age);
      System.out.println(obj.name);
   }
}
Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:11)
You can also throw a NullPointerException in Java using the throw keyword.
public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}
Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6
According to Java documentation a NullPointerException occurs if you try to −
Call the a method (instance) using null object.
Access, modify, print, field of a null value (object).
Trying to access (print/use in statements) the length of null value.
Throw a null value.
Accessing or modifying elements/slots of a null value.
Means if you throw a null value a null pointer exception occurs it is not up casting.
public class Demo {
   public static void main(String args[]) {
      throw null;
   }
}
Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:5)
How to limit text length of EditText in Android?

This example demonstrate about How to limit text length of EditText in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   xmlns: tools = "http://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :layout_margin= "16dp"
   tools :context= ".MainActivity" >
   <EditText
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :hint= "Enter something..."
      android :maxLength= "10" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
   }
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <application
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android :label= "@string/app_name"
      android :roundIcon= "@mipmap/ic_launcher_round"
      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>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Scala Collections - ListMap

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements.
The following is the syntax for declaring an ListMap variable.
val colors = ListMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −
var myMap1: ListMap[Char, Int] = colors + ("black" -> "#000000");

Below is an example program of showing how to create, initialize and process ListMap −
import scala.collection.immutable.ListMap

object Demo {
   def main(args: Array[String]) = {
      var myMap: ListMap[String,String] = ListMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: ListMap[String,String] = myMap + ("white" -> "#FFFFFF");
      // Print key values
      myMap.keys.foreach{ 
         i =>  
         print( "Key = " + i )
         println(" Value = " + myMap(i) ) 
      }
      if( myMap.contains( "red" )) {
         println("Red key exists with value :"  + myMap("red"))
      } else {
         println("Red key does not exist")
      }
      if( myMap.contains( "maroon" )) {
         println("Maroon key exists with value :"  + myMap("maroon"))
      } else {
         println("Maroon key does not exist")
      }
      //removing element
      var myMap2: ListMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: ListMap[String,String] = ListMap.empty[String, String];
      println(myMap1);
      println(myMap2);	
      println(myMap3);		  
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Red key exists with value :#FF0000
Maroon key does not exist
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF)
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F)
ListMap()


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to use Chip Component in ReactJS? - GeeksforGeeks

05 Mar, 2021
Chips are compact elements that represent an input, attribute, or action. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Chip Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Chip from "@material-ui/core/Chip";import Avatar from "@material-ui/core/Avatar";  export default function App() {  const handleClick = () => {    alert("Clicked!!");  };    return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to use Chip Component in ReactJS?</h4>      <Chip label="Simple Basic Chip" />      <Chip label="Disabled Chip" disabled />      <Chip        avatar={<Avatar>M</Avatar>}        label="Simple Clickable Chip"        onClick={handleClick}      />    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/chips/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How can Keras be used with a pre-trained model using Python?

Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications, and much more. It is used in research and for production purposes.
Keras means ‘horn’ in Greek. Keras was developed as a part of the research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems.
It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions.
It is highly scalable and comes with cross-platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well.
Keras is already present within the Tensorflow package. It can be accessed using the below line of code.
import tensorflow
from tensorflow import keras
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −
print("A convolutional model with pre-trained weights is loaded")
base_model = keras.applications.Xception(
   weights='imagenet',
   include_top=False,
   pooling='avg')
print("This model is freezed")
base_model.trainable = False
print("A sequential model is used to add a trainable classifier on top of the base")
model = keras.Sequential([
   base_model,
   layers.Dense(1000),
])
print("Compile the model")
print("Fit the model to the test data")
model.compile(...)
model.fit(...)
Code credit − https://www.tensorflow.org/guide/keras/sequential_model
A convolutional model with pre-trained weights is loaded
Downloading data from https://storage.googleapis.com/tensorflow/kerasapplications/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h583689472/83683744 [==============================] - 1s 0us/step
This model is freezed
A sequential model is used to add a trainable classifier on top of the base
Compile the model
Fit the model to the test data
A sequential model stack can be used, along with the help of a pre-trained model to initialize
classification layers.
A sequential model stack can be used, along with the help of a pre-trained model to initialize
classification layers.
Once this model has been built, it is compiled.
Once this model has been built, it is compiled.
Once the compilation is complete, this model can be fit to the training data.
Once the compilation is complete, this model can be fit to the training data.
Java program to print the fibonacci series of a given number using while loop

Fibonacci Series generates subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 &amp; F1. The initial values of F0 &amp; F1 can be taken 0, 1 or 1, 1 respectively.
Live Demo
public class FibonacciSeriesWithWhileLoop{
   public static void main(String args[]) {
      int a, b, c, i = 1, n;
      n = 10;
      a = b = 1; System.out.print(a+" "+b);

      while(i<n) {
         c = a + b; System.out.print(" ");
         System.out.print(c);
         a = b;
         b = c;
         i++;
      }
   }
}
1 1 2 3 5 8 13 21 34 55 89
HTML - <form> Tag

The HTML <form> tag is used for creating a form for user input. A form can contain textfields, checkboxes, radio-buttons and more. Forms are used to pass user-data to a specified URL.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML form Tag</title>
   </head>

   <body>
      <form action = "/cgi-bin/hello_get.cgi" method = "get">
         First name: 
            <input type = "text" name = "first_name" value = "" maxlength = "100" />
         <br />
         
         Last name: 
            <input type = "text" name = "last_name" value = "" maxlength = "100" />
         <input type = "submit" value ="Submit" />
      </form>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <form> tag also supports the following  additional attributes −
get (the form data is appended to the URL when submitted)
post (the form data is not appended to the URL)
Target to open the given URL.
_blank − the target URL will open in a new window.
_self − the target URL will open in the same frame as it was clicked.
_parent − the target URL will open in the parent frameset.
_top − the target URL will open in the full body of the window.
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Count top 10 most occurring values in a column in MySQL?

To count the top 10 most occurring values in a column in MySQL, The syntax is as follows −
SELECT yourColumnName, count(*)
   FROM yourTableName
   GROUP BY yourColumnName
   ORDER BY count(*) DESC
   LIMIT 10;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table countTop10Demo
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.74 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into countTop10Demo values(10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(1100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(200);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(1100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(450);
Query OK, 1 row affected (0.28 sec)
mysql> insert into countTop10Demo values(600);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countTop10Demo values(150);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countTop10Demo values(16454);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(450);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(2350);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(1780);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countTop10Demo values(1345);
Query OK, 1 row affected (0.22 sec)
mysql> insert into countTop10Demo values(34);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.08 sec)
mysql> insert into countTop10Demo values(19034);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(1844);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(34);
Query OK, 1 row affected (0.08 sec)
mysql> insert into countTop10Demo values(16454);
Query OK, 1 row affected (0.19 sec)
Now you can Display all records from the table using select statement. The query is as follows −
mysql> select *from countTop10Demo;
Here is the output −
+-------+
| Value |
+-------+
| 10    |
| 1100  |
| 200   |
| 2100  |
| 1100  |
| 450   |
| 600   |
| 2100  |
| 150   |
| 16454 |
| 450   |
| 2350  |
| 1780  |
| 1345  |
| 34    |
| 2100  |
| 19034 |
| 1844  |
| 34    |
| 16454 |
+-------+
20 rows in set (0.00 sec)
The following is the query to select top 10 most occurring values in a column in MySQL −
mysql> SELECT Value, count(*)
   -> FROM countTop10Demo
   -> GROUP BY Value
   -> ORDER BY count(*) DESC
   -> LIMIT 10;
Here is the output −
+-------+----------+
| Value | count(*) |
+-------+----------+
| 2100  | 3        |
| 1100  | 2        |
| 34    | 2        |
| 450   | 2        |
| 16454 | 2        |
| 1780  | 1        |
| 200   | 1        |
| 1345  | 1        |
| 19034 | 1        |
| 600   | 1        |
+-------+----------+
10 rows in set (0.00 sec)
Replace the Elements of a Vector in R Programming - replace() Function - GeeksforGeeks

01 Jun, 2020
replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.
Syntax: replace(x, list, values)
Parameters:x: vectorlist: indicesvalues: replacement values
Example 1:
# R program to illustrate# replace function  # Initializing a string vectorx <- c("GFG", "gfg", "Geeks")  # Getting the stringsx  # Calling replace() function to replace# the word gfg at index 2 with the # GeeksforGeeks elementy <- replace(x, 2, "GeeksforGeeks")  # Getting the new replaced stringsy
Output :
[1] "GFG"   "gfg"   "Geeks"
[1] "GFG"   "GeeksforGeeks" "Geeks"  

Example 2:
# R program to illustrate# replace function  # Initializing a string vectorx <- c("GFG", "gfg", "Geeks")  # Getting the stringsx  # Calling replace() function to replace# the word GFG at index 1 and Geeks at# index 3 with the A and B elements# respectivelyy <- replace(x, c(1, 3), c("A", "B"))  # Getting the new replaced stringsy
Output:
[1] "GFG"   "gfg"   "Geeks"
[1] "A"   "gfg" "B"  

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
How can we get the total number of rows affected by MySQL query?

MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.
mysql> Delimiter //
mysql> CREATE PROCEDURE `query`.`row_cnt` (IN command VarChar(60000))
    -> BEGIN
    ->    SET @query = command;
    ->    PREPARE stmt FROM @query;
    ->    EXECUTE stmt;
    ->    SELECT ROW_COUNT() AS 'Affected rows';
    -> END //
Query OK, 0 rows affected (0.00 sec)

mysql> Delimiter ;
mysql> Create table Testing123(First Varchar(20), Second Varchar(20));
Query OK, 0 rows affected (0.48 sec)

mysql> CALL row_cnt("INSERT INTO testing123(First,Second) Values('Testing First','Testing Second');");
+---------------+
| Affected rows |
+---------------+
|             1 |
+---------------+
1 row in set (0.10 sec)

Query OK, 0 rows affected (0.11 sec)
The above result set shows that I row is affected after inserting the data into the ‘testing123’ table.
How to disable mouse event on certain elements using JavaScript?

Following is the code for disabling mouse event on certain elements using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .size {
      font-size: 30px;
   }
</style>
</head>
<body>
<h1>Disable Mouse events using JavaScript</h1>
<div class="result">This is some text inside a div</div>
<button class="Btn">DISABLE</button>
<button class="Btn">ENABLE</button>
<h3>
Click on the above button to enable or disable mouse events
</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let BtnEle = document.querySelectorAll(".Btn");
   resEle.addEventListener("click", () => {
      resEle.classList.toggle("size");
   });
   BtnEle[0].addEventListener("click", () => {
      resEle.style.pointerEvents = "none";
   });
   BtnEle[1].addEventListener("click", () => {
      resEle.style.pointerEvents = "auto";
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the text in purple above −
On clicking the ‘DISABLE’ button and then clicking the text −
On clicking the ‘ENABLE’ button and then clicking on the text −
Setting custom splash screen in Kivy android app - GeeksforGeeks

06 Jun, 2021
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also.  It is an open-source Python library for the rapid development of multitouch applications. Its graphic engine is built over OpenGL, and it also supports a fast graphics pipeline.
In this article, we will see how we can add a custom splashscreen in kivy android app!
Basically, our motive is to show you how you add a custom splash screen that’s why we haven’t added anything thing on the main screen of the app except a center green box which denotes the app is working properly. And we are using our geeksforgeeks logo as a custom splash screen for this application.
Python3
# importing Kivy Appfrom kivy.app import App  # importing builder from kivyfrom kivy.lang import Builder    # this is the main class which # will render the whole applicationclass uiApp(App):      # method which will render our application    def build(self):        return Builder.load_string("""BoxLayout:    BoxLayout:    BoxLayout:        canvas.before:            Color:                rgba:[0,1,0,1]            Rectangle:                pos:self.pos                size:self.size    BoxLayout:                                   """)    # running the applicationuiApp().run()
Step 1: Connect USB with your phone and pc and allow Transfer Files in the phone’s generated popup.
Step 2: Then go to the phone’s setting and unlock developers mode in your device (if you haven’t) you can make yourself a developer by clicking several times on the build number in your phone.
Step 3: Then goes to the developer option that you have unlocked recently allow the USB debugging option.
Now you can successfully transfer files from pc to android phone.
Step 1: create a .spec file using a bulldozer, you can create your .spec file using the command ‘buildozer init’.
Step 2: open that .spec file in the text editor, after opening that file remove # from the beginning of this line.
Step 3: Pass the image path in this line
Step 4: Now attach USB cable to your android device and pc
Make sure that you have turned on USB debugging mode in the android device, now run the command ‘buildozer android debug deploy run’
Now check the app icon in your device:
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
How to find the currently running applications programmatically in Android?

This example demonstrates how do I find the currently running applications programmatically in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="16dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textAlignment="center"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      final ActivityManager activityManager = (ActivityManager)
      getSystemService(Context.ACTIVITY_SERVICE);
      final List<ActivityManager.RunningTaskInfo> recentTasks = Objects.requireNonNull(activityManager).getRunningTasks(Integer.MAX_VALUE);
      for (int i = 0; i < recentTasks.size(); i++) {
         textView.setText("Application executed: " + recentTasks.get(i).baseActivity.toShortString() + "\n\n ID: " + recentTasks.get(i).id + "");
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      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>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Find Mean of a List of Numpy Array in Python

Numpy is a very powerful python library for numerical data processing. It mostly takes in the data in form of arrays and applies various functions including statistical functions to get the result out of the array. In this article we will see how to get the mean value of a given array.
The mean function can take in an array and give the mathematical mean value of all the elements in it. So we design a for loop to keep track of the length of the input and go through each array calculating its mean.
 Live Demo
import numpy as np

# GIven Array
Arrays_In = [np.array([11, 5, 41]),
         np.array([12, 13, 26]),
         np.array([56, 20, 51])]

# Resultihg Array
Arrays_res = []

# With np.mean()
for x in range(len(Arrays_In)):
   Arrays_res.append(np.mean(Arrays_In[x]))

# Result
print("The means of the arrays: \n",Arrays_res)
Running the above code gives us the following result −
The means of the arrays:
[19.0, 17.0, 42.333333333333336]
It is a very similar approach as above except that we use the average function instead of mean function. It gives the exact same result.
 Live Demo
import numpy as np

# GIven Array
Arrays_In = [np.array([11, 5, 41]),
         np.array([12, 13, 26]),
         np.array([56, 20, 51])]

# Resultihg Array
Arrays_res = []

# With np.average()
for x in range(len(Arrays_In)):
   Arrays_res.append(np.average(Arrays_In[x]))

# Result
print("The means of the arrays: \n",Arrays_res)
Running the above code gives us the following result −
The means of the arrays:
[19.0, 17.0, 42.333333333333336]
What is the difference between a variable and StringVar() of Tkinter?

A variable in Tkinter is used to store the values of any data. For a Tkinter application, we can store the values in two ways −
by defining the value programmatically, or
by defining the value programmatically, or
by storing the value through user Input.
by storing the value through user Input.
A normal variable can be used to set the value for any application whenever it is required. However, we can take the user input by creating an instance of the StringVar() object. When we specify a Tkinter variable such as textvariable, for a widget (textvariable = myvar), the widget automatically gets updated whenever the value of the variable changes. However, there might be times when we want to modify the value of the widget through the variable.
In this program, we will update the Label Widget from the StringVar(value). Whenever we want to update the value of Tkinter StringVar(), we have to change its value.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")

#Create a StringVar to accept user input
var= StringVar(value= "Hello World!")

#Create a Label
label= Label(win,textvariable=var, font= ('Mistral 28 bold'), background= 'blue', foreground="white")
label.pack(pady=20)

win.mainloop()
Running the above code will display a label text which has the same value as defined in StringVar().
Sending an Intent to browser to open specific URL in Android?

This example demonstrates how do I send an Intent to browser to open specific URL in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
   <Button
      android:onClick="GetUrlFromIntent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Get URL from Intent"
      android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void GetUrlFromIntent(View view) {
      String url = "http://www.google.com";
      Intent i = new Intent(Intent.ACTION_VIEW);
      i.setData(Uri.parse(url));
      startActivity(i);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      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>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
How to limit the number of characters allowed in form input text field?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively.
To limit the number of characters, use the maxlength attribute. The max and min attributes are used with number, range, date, datetime, datetime-local, month, time and week input types.
You can try to run the following code to limit the number of characters allowed in form input text field:
<!DOCTYPE html>
<html>
   <head>
      <title>HTML maxlength attribute</title>
   </head>
   <body>
      <form action = "/cgi-bin/hello_get.cgi" method = "get">
         Student Name:
         <br>
         <input type = "text" name = "first_name" value = "" maxlength = "40" />
         <br>
         Student Subject: <br>
         <input type = "text" name = "last_name" value = "" maxlength = "30" />
         <br>
         <input type = "submit" value ="Submit" />
      </form>
   </body>
</html>