code-rag-bench/online-tutorials huggingface dataset:
Python Program to convert Kilometers to Miles

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given distance in kilometers and we need to convert it into miles
As we know that 1 kilometer equals 0.62137 miles.
Miles = kilometer * 0.62137
Now let’s observe the concept in the implementation below−
 Live Demo
kilometers = 5.5
# conversion factor as 1 km = 0.621371 miles
conv = 0.621371
# calculation
miles = kilometers * conv
print(kilometers,"kilometers is equal to ",miles,"miles")
5.5 kilometers is equal to 3.4175405 miles
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about the conversion of distance given in kilometers into miles.
Batch Script - START

This batch command starts a program in new window, or opens a document.
START “programname”

@echo off
start notepad.exe
When the batch file is executed, a new notepad windows will start.
 Print
 Add Notes
 Bookmark this page
C Program to list all files and sub-directories in a directory

Here, we are given a directory. Our task is to create a C program to list all files and sub-directories in a directory.
The directory is a place/area/location where a set of the file(s) will be stored.
Subdirectory is a directory inside the root directory, in turn, it can have another sub-directory in it.
In C programming language you can list all files and sub-directories of a directory easily. The below program will illustrate how to list all files and sub-directories in a directory.
//C program to list all files and sub-directories in a directory
 Live Demo
#include <stdio.h>
#include <dirent.h>
int main(void){
   struct dirent *files;
   DIR *dir = opendir(".");
   if (dir == NULL){
      printf("Directory cannot be opened!" );
      return 0;
   }
   while ((files = readdir(dir)) != NULL)
   printf("%s\n", files->d_name);
   closedir(dir);
   return 0;
}
cprograms
..
prog1.c
prog2.c
prog3.c
...
prog41.c
This will return all files and sub-directory of the current directory.
Python 3 - String replace() Method

The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Following is the syntax for replace() method −
str.replace(old, new[, max])

old − This is old substring to be replaced.
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
max − If this optional argument max is given, only the first count occurrences are replaced.
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced.
The following example shows the usage of replace() method.
#!/usr/bin/python3

str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
When we run above program, it produces the following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to create a Tkinter error message box?

The Tkinter library has many built-in functions and methods which can be used to implement the functional part of an application. We can use messagebox module in Tkinter to create various popup dialog boxes. The messagebox property has different types of built-in popup windows that the users can use in their applications.
If you need to display the error messagebox in your application, you can use showerror("Title", "Error Message") method. This method can be invoked with the messagebox itself.
# Import the required libraries
from tkinter import *
from tkinter import messagebox

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to show the error message
def on_click():
   messagebox.showerror('Python Error', 'Error: This is an Error Message!')

# Create a label widget
label = Label(win, text="Click the button to show the message ",
font=('Calibri 15 bold'))
label.pack(pady=20)


# Create a button to delete the button
b = Button(win, text="Click Me", command=on_click)
b.pack(pady=20)

win.mainloop()
When you run the above code, it will show a button widget and a label in the window. Click the button to show the error message.
What happens when a function is called before its declaration in C?

If we do not use some function prototypes, and the function body is declared in some section which is present after the calling statement of that function. In such a case, the compiler thinks that the default return type is an integer. But if the function returns some other type of value, it returns an error. If the return type is also an integer, then it will work fine, sometimes this may generate some warnings.
#include<stdio.h>
main() {
   printf("The returned value: %d\n", function);
}
char function() {
   return 'T'; //return T as character
}
[Error] conflicting types for 'function'
[Note] previous implicit declaration of 'function' was here
Now if the return type is an integer, then it will work.
#include<stdio.h>
main() {
   printf("The returned value: %d\n", function());
}
int function() {
   return 86; //return an integer value
}
The returned value: 86
Write a Golang program to reverse an array

Input arr = [3, 5, 7, 9, 10, 4] => [4, 10, 9, 7, 5, 3]
Input arr = [1, 2, 3, 4, 5] => [5, 4, 3, 2, 1]
Step 1: Define a function that accepts an array.
Step 2: Start iterating the input array.
Step 3: Swap first element with last element of the given array.
Step 4: Return array.
Live Demo
package main
import "fmt"

func reverseArray(arr []int) []int{
   for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 {
      arr[i], arr[j] = arr[j], arr[i]
   }
   return arr
}

func main(){
   fmt.Println(reverseArray([]int{1, 2, 3, 4, 5}))
   fmt.Println(reverseArray([]int{3, 5, 7, 2, 1}))
   fmt.Println(reverseArray([]int{9, 8, 6, 1, 0}))
}
[5 4 3 2 1]
[1 2 7 5 3]
[0 1 6 8 9]
Increase and decrease row value by 1 in MySQL with Stored Procedure?

Let us first create a table to increase and adecrease row value by 1. The following is the query −
mysql> create table IncrementAndDecrementValue
   −> (
   −> UserId int,
   −> UserScores int
   −> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into IncrementAndDecrementValue values(101,20000);
Query OK, 1 row affected (0.13 sec)

mysql> insert into IncrementAndDecrementValue values(102,30000);
Query OK, 1 row affected (0.20 sec)

mysql> insert into IncrementAndDecrementValue values(103,40000);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from IncrementAndDecrementValue;
The following is the output −
+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 |      20000 |
|    102 |      30000 |
|    103 |      40000 |
+--------+------------+
3 rows in set (0.00 sec)
Here is my stored procedure to increase and decrease row value by 1.
mysql> delimiter //

mysql> create procedure IncrementAndDecrementRowValueByOne()
   −> begin
   −> declare first int;
   −> declare second int;
   −> set first = (select UserScores from IncrementAndDecrementValue where UserId = 101);
   −> set second = (select UserScores from IncrementAndDecrementValue where UserId = 102);
   −> update IncrementAndDecrementValue set UserScores = first-1 where UserId = 101;
   −> update IncrementAndDecrementValue set UserScores = second+1 where UserId = 102;
   −> end //
Query OK, 0 rows affected (0.17 sec)

mysql> delimiter ;
Call the stored procedure using CALL command. The query is as follows −
mysql> call IncrementAndDecrementRowValueByOne();
Query OK, 1 row affected (0.24 sec)
Check the row value is updated or not using select statement. The query is as follows −
mysql> select *from IncrementAndDecrementValue;
The following is the output −
+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 |      19999 |
|    102 |      30001 |
|    103 |      40000 |
+--------+------------+
3 rows in set (0.00 sec)
We have decremented the value 20000 to 19999 and incremented 30000 to 30001.
Java Program to Check if a given matrix is sparse or not - GeeksforGeeks

13 Jan, 2022
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix,
Examples: 
Input : 1 0 3
        0 0 4
        6 0 0
Output : Yes
There are 5 zeros. This count
is more than half of matrix
size.

Input : 1 2 3
        0 7 8
        5 0 7 
Output: No 
To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. 
Java
// Java code to check // if a matrix is// sparse.  import java.io.*;  class GFG {          static int MAX = 100;           static boolean isSparse(int array[][], int m, int n)    {        int counter = 0;               // Count number of zeros in the matrix        for (int i = 0; i < m; ++i)            for (int j = 0; j < n; ++j)                if (array[i][j] == 0)                    ++counter;               return (counter > ((m * n) / 2));    }           // Driver Function    public static void main(String args[])    {        int array[][] = { { 1, 0, 3 },                             { 0, 0, 4 },                             { 6, 0, 0 } };               int m = 3,            n = 3;        if (isSparse(array, m, n))            System.out.println("Yes");        else            System.out.println("No");    }}  // This code is contributed by// Nikita Tiwari.
Output:  
Yes
Please refer complete article on Check if a given matrix is sparse or not for more details!
Java
Java Programs
Matrix
Matrix
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Tk - Canvas Widgets

Canvas is used for providing drawing areas. The syntax for canvas widget is shown below −
canvas canvasName options

The options available for the canvas widget are listed below in the following table −
-background color
Used to set background color for widget.
-closeenough distance
Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value may be a fraction and must be positive.
-scrollregion boundingBox
The bounding box for the total area of this canvas.
-height number
Used to set height for widget.
-width number
Sets the width for widget.
-xscrollincrement size
The amount to scroll horizontally  when scrolling is requested.
-yscrollincrement size
The amount to scroll vertically when scrolling is requested.
A simple example for canvas widget is shown below −
#!/usr/bin/wish

canvas .myCanvas -background red -width 100 -height 100 
pack .myCanvas
When we run the above program, we will get the following output −
The list of the available widgets for drawing in canvas is listed below −
Draws a line.
Draws an arc.
Draws a rectangle.
Draws an oval.
Draws a polygon.
Draws a text.
Draws a bitmap.
Draws an image.
An example using different canvas widgets is shown below −
#!/usr/bin/wish

canvas .myCanvas -background red -width 200 -height 200 
pack .myCanvas
.myCanvas create arc 10 10 50 50 -fill yellow
.myCanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true
   -splinesteps 2
.myCanvas create oval 50 50 100 80 -fill yellow
.myCanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green
.myCanvas create rectangle 150 150 170 170  -fill yellow
.myCanvas create text 170 20 -fill yellow -text "Hello" -font {Helvetica -18 bold}
.myCanvas create bitmap 180 50 -bitmap info
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

16 Nov, 2020
Given the following statements:
    S1: A foreign key declaration can always 
        be replaced by an equivalent check
        assertion in SQL.
    S2: Given the table R(a,b,c) where a and
        b together form the primary key, the 
        following is a valid table definition.
        CREATE TABLE S (
            a INTEGER,
            d INTEGER,
            e INTEGER,
            PRIMARY KEY (d),
            FOREIGN KEY (a) references R) 
Which one of the following statements is CORRECT?(A) S1 is TRUE and S2 is FALSE.(B) Both S1 and S2 are TRUE.(C) S1 is FALSE and S2 is TRUE.(D) Both S1 and S2 are FALSE.Answer: (D)Explanation: Check assertions are not sufficient to replace foreign key. Foreign key declaration may have cascade delete which is not possible by just check insertion. 
Using a check condition we can have the same effect as Foreign key while adding elements to the child table. But when we delete an element from the parent table the referential integrity constraint is no longer valid. So, a check constraint cannot replace a foreign key.
So, we cannot replace it with a single check.
 
    S2: Given the table R(a,b,c) where a and
        b together form the primary key, the
        following is a valid table definition.
        CREATE TABLE S (
            a INTEGER,
            d INTEGER,
            e INTEGER,
            PRIMARY KEY (d),
            FOREIGN KEY (a) references R) 



False: Foreign key in one table should uniquely identifies a row of other table. In above table definition, table S has a foreign key that refers to field ‘a’ of R. The field ‘a’ in table S doesn’t uniquely identify a row in table R.Quiz of this Question
sk200112
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64
Wrap a page's content with Bootstrap

To wrap a page's content, use the .container class, 
<div class = "container">
...
</div>
The following is the .container class in bootstrap.css file: 
.container{
    padding-right: 20px;
    padding-left: 20px;
    margin-right: auto;
    margin-left: auto;
}
How to load and display an image in ImageView on Android App?

This example demonstrates how to load and display an image in ImageView on Android App.
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:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MyAndroidAppActivity">
   <ImageView
      android:id="@+id/imageView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
   <Button
      android:id="@+id/btnChangeImage"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Change Image" />
</LinearLayout>
Step 3 − Add the following code to src/MyAndroidAppActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
import android.view.View.OnClickListener;
public class MyAndroidAppActivity extends AppCompatActivity {
   Button button;
   ImageView image;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      addListenerOnButton();
   }
   public void addListenerOnButton() {
      image=(ImageView) findViewById(R.id.imageView1);
      button=(Button) findViewById(R.id.btnChangeImage);
      button.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View arg0) {
            image.setImageResource(R.drawable.ic_launcher_background);
         }
      });
   }
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.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=".MyAndroidAppActivity">
         <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
Creating scrollable Listbox within a grid using Tkinter

A Listbox widget displays a list of items such as numbers list, items list, list of employees in a company, etc. There might be a case when a long list of items in a Listbox needs a way to be viewed inside the window. For this purpose, we can attach scrollbars to the Listbox widget by initializing the Scrollbar() object. If we configure and attach the Listbox with the scrollbar, it will make the Listbox scrollable.
In this example, we will create a Listbox with a list of numbers ranging from 1 to 100. The Listbox widget has an associated Scrollbar with it.
#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("700x350")

#Create an object of Scrollbar widget
s = Scrollbar()

#Create a horizontal scrollbar
scrollbar = ttk.Scrollbar(win, orient= 'vertical')
scrollbar.pack(side= RIGHT, fill= BOTH)

#Add a Listbox Widget
listbox = Listbox(win, width= 350, font= ('Helvetica 15 bold'))
listbox.pack(side= LEFT, fill= BOTH)

#Add values to the Listbox
for values in range(1,101):
   listbox.insert(END, values)

listbox.config(yscrollcommand= scrollbar.set)

#Configure the scrollbar
scrollbar.config(command= listbox.yview)

win.mainloop()
Running the above code will display a window containing a scrollable Listbox.
Sequence of execution of, instance method, static block and constructor in java?

A static block is a block of code with a static keyword. In general, these are used to initialize the static members of a class. JVM executes static blocks before the main method at the time loading a class.
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
public class MyClass {
   MyClass(){
      System.out.println("Hello this is a constructor");
   }
   public static void main(String args[]){
      new MyClass();
   }
}
Hello this is a constructor
These are the normal methods of a class (non static), you need to invoke them using an object of the class −
public class MyClass {
   public void demo(){
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new MyClass().demo();
   }
}
Hello this is an instance method
When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.
public class ExampleClass {
   static{
      System.out.println("Hello this is a static block");
   }
   ExampleClass(){
      System.out.println("Hello this a constructor");
   }
   public static void demo() {
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new ExampleClass().demo();
   }
}
Hello this is a static block
Hello this a constructor
Hello this is an instance method
VBScript UBound Function

The UBound Function returns the Largest subscript of the specified array. Hence, this value corresponds to the size of the array.
UBound(ArrayName[,dimension])

ArrayName, a Required parameter. This parameter corresponds to the name of the array.
ArrayName, a Required parameter. This parameter corresponds to the name of the array.
dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on.
dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim arr(5)
         arr(0) = "1"            'Number as String
         arr(1) = "VBScript"     'String
         arr(2) = 100            'Number
         arr(3) = 2.45           'Decimal Number
         arr(4) = #10/07/2013#   'Date
         arr(5) = #12.45 PM#     'Time

         document.write("The Largest Subscript value of  the given array is : " & UBound(arr))

         ' For MultiDimension Arrays :
         Dim arr2(3,2)
         document.write(
            "The Largest Subscript of the first dimension of arr2 is : " & UBound(arr2,1) & "<br />")
         document.write(
            "The Largest Subscript of the Second dimension of arr2 is : " & UBound(arr2,2) & "<br />")

      </script>
   </body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, then it produces the following result −
The Largest Subscript value of the given array is : 5
The Largest Subscript of the first dimension of arr2 is : 3
The Largest Subscript of the Second dimension of arr2 is : 2


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Differences between wait() and join() methods in Java

In multithreading when we deal with threads there comes the requirement of pause and start a thread for this Threading provides two methods wait and join which are used for the same.
The following are the important differences between wait() and join().
JavaTester.java
 Live Demo
public class JavaTester extends Thread {
   static Object lock = new Object();
   static int n;
   int i;
   String name;
   JavaTester(String name, int i) {
      this.name = name;
      this.i = i;
   }
   @Override
   public void run() {
      try {
         synchronized (lock) {
            while (i != n) {
               lock.wait();
            }
            System.out.println(name + " started");
            n++;
            lock.notifyAll();
         }
         synchronized (lock) {
            while (i != n - 4) {
               lock.wait();
            }
            System.out.println(name + " finished");
            n++;
            lock.notifyAll();
         }
      }
      catch (InterruptedException e) {
      }
   }
   public static void main(String[] args) throws Exception {
      new JavaTester("a", 0).start();
      new JavaTester("b", 1).start();
      new JavaTester("c", 2).start();
      new JavaTester("d", 3).start();
   }
}
a started
b started
c started
d started
a finished
b finished
c finished
d finished
How to read a Matrix from user in Java? - GeeksforGeeks

05 Mar, 2019
Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard.
// Java program to read a matrix from user  import java.util.Scanner;  public class MatrixFromUser {      // Function to read matrix    public static void readMatrixByUser()    {        int m, n, i, j;        Scanner in = null;        try {            in = new Scanner(System.in);            System.out.println("Enter the number "                               + "of rows of the matrix");            m = in.nextInt();            System.out.println("Enter the number "                               + "of columns of the matrix");            n = in.nextInt();              // Declare the matrix            int first[][] = new int[m][n];              // Read the matrix values            System.out.println("Enter the elements of the matrix");            for (i = 0; i < m; i++)                for (j = 0; j < n; j++)                    first[i][j] = in.nextInt();              // Display the elements of the matrix            System.out.println("Elements of the matrix are");            for (i = 0; i < m; i++) {                for (j = 0; j < n; j++)                    System.out.print(first[i][j] + "  ");                System.out.println();            }        }        catch (Exception e) {        }        finally {            in.close();        }    }      // Driver code    public static void main(String[] args)    {        readMatrixByUser();    }}
Enter the number of rows of the matrix 2
Enter the number of columns of the matrix 2
Enter the elements of the matrix
1
2
3
4
Elements of the matrix are
1 2 
3 4 

Java-Arrays
Picked
Java
Matrix
Matrix
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Print a given matrix in spiral form
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Conditional statements in JavaScript

There are three types of conditional statements in JavaScript −
If statement − The if statement is used to execute code inside the if block only if the specific condition is met.
If else statement − The If....Else statement is used to check only two conditions and execute different codes for each of them.
If else if else statement − The if...else if...else statement is used for checking more than two conditions.
Following is the code to implement conditional statements in 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: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Conditional statements in JavaScript</h1>
<input type="text" class="numInput" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let numInputEle = document.querySelector(".numInput");
   BtnEle.addEventListener("click", () => {
      if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2 and 3 both";
      } else if (numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The number is divisbly by 3";
      } else if (numInputEle.value % 2 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2";
      } else {
         resEle.innerHTML = "The numbers isn't divisible by 2 or 3";
      }
   });
</script>
</body>
</html>
On entering a number and clicking on ‘CHECK’ button −
Java regex program to verify whether a String contains at least one alphanumeric character.

Following regular expression matches a string that contains at least one alphanumeric characters −
"^.*[a-zA-Z0-9]+.*$";
Where,
^.* Matches the string starting with zero or more (any) characters.
^.* Matches the string starting with zero or more (any) characters.
[a-zA-Z0-9]+ Matches at least one alpha-numeric character.
[a-zA-Z0-9]+ Matches at least one alpha-numeric character.
.*$ Matches the string ending with zero or more (ant) characters.
.*$ Matches the string ending with zero or more (ant) characters.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a string");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression
      String regex = "^.*[a-zA-Z0-9]+.*$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      if(matcher.matches()) {
         System.out.println("Given string is valid");
      } else {
         System.out.println("Given string is not valid");
      }
   }
}
Enter a string
###test123$$$
Given string is valid
Enter a string
####$$$$
Given string is not valid
 Live Demo
import java.util.Scanner;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a string");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression
      String regex = "^.*[a-zA-Z0-9]+.*$";
      boolean result = input.matches(regex);
      if(result) {
         System.out.println("Valid match");
      }else {
         System.out.println("In valid match");
      }
   }
}
Enter a string
###test123$$$
Valid match
Enter a string
####$$$$
In valid match
Design and Analysis Bubble Sort

Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if necessary. When no exchanges are required, the file is sorted.
This is the simplest technique among all sorting algorithms.
Algorithm: Sequential-Bubble-Sort (A) 
fori← 1 to length [A] do 
for j ← length [A] down-to i +1 do 
   if A[A] < A[j - 1] then 
      Exchange A[j] ↔ A[j-1] 

voidbubbleSort(int numbers[], intarray_size) { 
   inti, j, temp; 
   for (i = (array_size - 1); i >= 0; i--) 
   for (j = 1; j <= i; j++) 
      if (numbers[j - 1] > numbers[j]) { 
         temp = numbers[j-1]; 
         numbers[j - 1] = numbers[j]; 
         numbers[j] = temp; 
      } 
} 

Here, the number of comparisons are
1 + 2 + 3 +...+ (n - 1) = n(n - 1)/2 = O(n2)
Clearly, the graph shows the n2 nature of the bubble sort.
In this algorithm, the number of comparison is irrespective of the data set, i.e. whether the provided input elements are in sorted order or in reverse order or at random.
From the algorithm stated above, it is clear that bubble sort does not require extra memory.
Unsorted list:
5 > 2 swap
5 > 1 swap
5 > 4 swap
5 > 3 swap
5 < 7 no swap
7 > 6 swap
2 > 1 swap
2 < 4 no swap
4 > 3 swap
4 < 5 no swap
5 < 6 no swap
There is no change in 3rd, 4th, 5th and 6th iteration.
Finally,
the sorted list is

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
How to get rows/index names in Pandas dataframe

02 Nov, 2021
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations.
Let’s discuss how to get row names in Pandas dataframe.
First, let’s create a simple dataframe with nba.csv
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # calling head() method  # storing in new variable data_top = data.head(10)     # display data_top 
Now let’s try to get the row name from above dataset.
Method #1: Simply iterate over indices
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   # calling head() method  # storing in new variable data_top = data.head()     # iterating the columnsfor row in data_top.index:    print(row, end = " ")
Output:
0 1 2 3 4 5 6 7 8 9 
 Method #2: Using rows with dataframe object
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   # calling head() method  # storing in new variable data_top = data.head()     # list(data_top) orlist(data_top.index)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 Method #3: index.values method returns an array of index.
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   # calling head() method  # storing in new variable data_top = data.head()     list(data_top.index.values)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 Method #4: Using tolist() method with values with given the list of index.
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   # calling head() method  # storing in new variable data_top = data.head()     list(data_top.index.values.tolist())
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 Method #5: Count number of rows in dataframe
Since we have loaded only 10 top rows of dataframe using head() method, let’s verify total number of rows first.
Python3
# iterate the indices and print each onefor row in data.index:    print(row, end= " ")
Output:
Now, let’s print the total count of index.
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   row_count = 0  # iterating over indicesfor col in data.index:    row_count += 1  # print the row countprint(row_count)
Output:
458
prachisoda1234
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
numpy.median() in Python

28 Nov, 2018
numpy.median(arr, axis = None) : Compute the median of the given data (array elements) along the specified axis.
How to calculate median?
Given data points.
Arrange them in ascending order
Median = middle term if total no. of terms are odd.
Median = Average of the terms in the middle (if total no. of terms are even)
Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the median. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing median.
Results : Median of the array (a scalar value if axis is none) or array with median values along specified axis.
Code #1:
# Python Program illustrating # numpy.median() method     import numpy as np    # 1D array arr = [20, 2, 7, 1, 34]  print("arr : ", arr) print("median of arr : ", np.median(arr))   
Output :
arr :  [20, 2, 7, 1, 34]
median of arr :  7.0

 Code #2:
# Python Program illustrating # numpy.median() method  import numpy as np    # 2D array arr = [[14, 17, 12, 33, 44],         [15, 6, 27, 8, 19],        [23, 2, 54, 1, 4, ]]     # median of the flattened array print("\nmedian of arr, axis = None : ", np.median(arr))     # median along the axis = 0 print("\nmedian of arr, axis = 0 : ", np.median(arr, axis = 0))    # median along the axis = 1 print("\nmedian of arr, axis = 1 : ", np.median(arr, axis = 1))  out_arr = np.arange(3)print("\nout_arr : ", out_arr) print("median of arr, axis = 1 : ",       np.median(arr, axis = 1, out = out_arr))
Output :
median of arr, axis = None :  15.0

median of arr, axis = 0 :  [15.  6. 27.  8. 19.]

median of arr, axis = 1 :  [17. 15.  4.]

out_arr :  [0 1 2]
median of arr, axis = 1 :  [17 15  4]

Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
HTML | DOM outerHTML property

11 Jun, 2020
The outerHTML property of the DOM interface gives the HTML fragment of that element. It not only gives the content, but the whole HTML structure of the element. It can also be used to replace the HTML structure of the element.
Syntax:
To return the outerHTML.var value = element.outerHTML;
var value = element.outerHTML;
To set the outerHTML.element.outerHTML = "HTML_Structure";
element.outerHTML = "HTML_Structure";
Return value: When getting outerHTML, it returns HTML String data.
Example 1: This example shows how to get the outerHTML of an element with id=“gfg”.
HTML
<!DOCTYPE html><html>  <head>    <title>GeeksforGeeks</title></head>  <body>    <div id="gfg">        <h1>GeeksforGeeks</h1>          <p>Welcome geeks!</p>    </div>          <script>        var g = document.getElementById("gfg");        document.write(g.outerHTML);    </script></body>  </html>
Output:
The outerHTML of element can be seen in the output:
Example 2: This example shows how to set or change the outerHTML.
HTML
<!DOCTYPE html><html>  <head>    <title>GeeksforGeeks</title></head>  <body>    <h1>GeeksforGeeks</h1>    <div id="d">        Click on Button to change        the outerHTML.    </div>    <br>    <button onclick="changeouter()">click</button>    <script>        function changeouter() {            var gfg = document.getElementById("d");            gfg.outerHTML =             "<h3>Hey Geeks! outerHTML is changed</h3>";        }    </script></body>  </html>
Output:
Before clicking the button:
After clicking the button:
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
What is a PyMongo Cursor?

14 Jun, 2022
MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) that accommodates more data types.
When you use the function db.collection.find() to search documents in collections then as a result it returns a pointer. That pointer is known as a cursor. Consider if we have 2 documents in our collection, then the cursor object will point to the first document and then iterate through all documents which are present in our collection. 
As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB query result sets. This cursor instance is returned by the find() method. Consider the below example for better understanding.
Example: Sample database is as follows: 
  
javascript
from pymongo import MongoClient     # Connecting to mongodb   client = MongoClient('mongodb://localhost:27017/') with client:         db = client.GFG    lectures = db.lecture.find()     print(lectures.next())    print(lectures.next())    print(lectures.next())            print("\nRemaining Lectures\n")    print(list(lectures))
In this, find() method returns the cursor object.
lectures = db.lecture.find()
With the next() method we get the next document in the collection.
lectures.next()
With the list() method, we can transform the cursor to a Python list.
khushb99
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Python MySQL – Join

13 Jun, 2022
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server.
This is a MySQL Connector that allows Python to access MySQL Driver and implement SQL queries in its programming facility. Here we will try implementing Join clause on our Database and will study the output generated.
Join allows you to combine two or more tables in SQL, based on related column between them. Based on this application of join there are three types of join: 
INNER JOIN gives the records that are produced by matching columns. JOIN and INNER JOIN both work the same. Syntax:
SELECT column1, column2...
FROM tablename
JOIN tablename ON condition;
SELECT column1, column2...
FROM tablename
INNER JOIN tablename ON condition;
LEFT JOIN gives those records from table 1 removing exclusive contents of 2 Syntax:
SELECT column1, column2...
FROM tablename
LEFT JOIN tablename ON condition;
RIGHT JOIN gives all records from table 2 after removing exclusive records of 1. Syntax:
SELECT column1, column2...
FROM tablename
RIGHT JOIN tablename ON condition;
The following programs will help you understand this better. DATABASE IN USE:   PROGRAM 1: Use of inner join 
Python3
import mysql.connector  # Connecting to the databasemydb = mysql.connector.connect(  host ='localhost',  database ='College',  user ='root',)  cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.NAME from Student S JOIN \Student on S.Roll_no = Student.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set:    print(x)
OUTPUT:  PROGRAM 2: use of LEFT JOIN 
Python3
import mysql.connector  # Connecting to the databasemydb = mysql.connector.connect(  host ='localhost',  database ='College',  user ='root',)  cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.Name from STUDENT S\ LEFT JOIN Student s ON S.Roll_no = s.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set:    print(x)
OUTPUT:  PROGRAM 3 : use of RIGHT JOIN 
Python3
import mysql.connector  # Connecting to the databasemydb = mysql.connector.connect(  host ='localhost',  database ='College',  user ='root',)  cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.Name from STUDENT S RIGHT \JOIN Student s ON S.Roll_no = s.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set:    print(x)
OUTPUT: 
mitalibhola94
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
Ruby | String count() Method

13 Dec, 2019
count is a String class method in Ruby. In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated.
Syntax:str.count(parameter_list)
Parameters: Here, str is the given string.
Returns: The numbers of the characters.
Example 1:
# Ruby program to demonstrate # the count method        # Taking a string and # using the methodstr = "String Counting"puts str.count "ing"
Output:
7

Example 2:
# Ruby program to demonstrate # the count method        # Taking a string and # using the methodstr = "String Counting"puts str.count "^ing"  str2 = "Ruby Method\\r\\n"  puts str.count "\\"
Output:
8
0

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.