code-rag-bench/online-tutorials huggingface dataset:
C++ Program to Print Number Entered by User

The objects “cin” and “cout” are used in C++ for input and output respectively. cin is an instance of the istream class and is attached to the standard input device such as the keyboard. cout is an instance of the ostream class and is connected to the standard output device such as the display screen.
A program that prints the number entered by the user is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int num;
   cout<<"Enter the number:\n";
   cin>>num;
   cout<<"The number entered by user is "<<num;
   return 0;
}
Enter the number: 5
The number entered by user is 5
In the above program, the user enters the number using the cin object.
cout<<"Enter the number:\n";
cin>>num;
Then the number is displayed using the cout object.
cout<<"The number entered by user is "<<num;
A way for the user to enter multiple numbers is to use an array. This is demonstrated using the below program −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a[5],i;
   cout<<"Enter the numbers in array\n";
   for(i=0; i<5; i++)
   cin>>a[i];
   cout<<"The numbers entered by user in array are ";
   for(i=0; i<5; i++)
   cout<<a[i]<<" ";
   return 0;
}
Enter the numbers in array
5 1 6 8 2
The numbers entered by user in array are 5 1 6 8 2
In the above program, a for loop is used to access all the array elements from the user. For each iteration of the for loop, the array element with the corresponding index is accessed using the cin object.
for(i=0; i<5; i++)
cin>>a[i];
After that, all the array elements are displayed using the same concept of the for loop.
for(i=0; i<5; i++)
cout<<a[i]<<" ";
How to make a primary key start from 1000?

To make a primary key start from 1000, you need to alter your table and set to auto_increment with value 1000. The syntax is as follows −
alter table yourTableName auto_increment=1000;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table PrimaryKey1000Demo
   -> (
   -> ProductId int auto_increment,
   -> PRIMARY KEY(ProductId)
   -> );
Query OK, 0 rows affected (0.56 sec)
Now here is the query that will update the primary key to start from 1000 −
mysql> alter table PrimaryKey1000Demo auto_increment=1000;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now we have updated the start value to begin from 1000. Let us now insert some records to check the starting value of primary key. The query to insert record is as follows −
mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.11 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.19 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.23 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.08 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from PrimaryKey1000Demo;
The following is the output displaying ProductID, our primary key to begin from 1000 −
+-----------+
| ProductId |
+-----------+
|      1000 |
|      1001 |
|      1002 |
|      1003 |
+-----------+
4 rows in set (0.00 sec)
Get number of fields in MySQL table?

To display number of fields in MySQL, use the COUNT(*). Following is the syntax −
select COUNT(*) AS anyAliasName
from INFORMATION_SCHEMA.COLUMNS
where table_name = yourTableName AND
TABLE_SCHEMA = yourDatabaseName;
Let us first create a table −
mysql> create table DemoTable794 (
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(100),
   ClientAge int,
   ClientCountryName varchar(100)
);
Query OK, 0 rows affected (1.61 sec)
Following is the query to get the number of fields in MySQL −
mysql> select COUNT(*) AS TOTAL_NUMBER_OF_COLUMNS
   from INFORMATION_SCHEMA.COLUMNS
   where table_name = 'DemoTable794' AND
   TABLE_SCHEMA = 'web';
This will produce the following output -
+-------------------------+
| TOTAL_NUMBER_OF_COLUMNS |
+-------------------------+
| 4                       |
+-------------------------+
1 row in set (0.00 sec)
PyQt5 - QStatusBar Widget

QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information.
There are three types of status indicators −
Temporary − Briefly occupies most of the status bar. For example, used to explain tool tip texts or menu entries.
Normal − Occupies part of the status bar and may be hidden by temporary messages. For example, used to display the page and line number in a word processor.
Permanent − It is never hidden. Used for important mode indications. For example, some applications put a Caps Lock indicator in the status bar.
Status bar of QMainWindow is retrieved by statusBar() function. setStatusBar() function activates it.
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)

addWidget()
Adds the given widget object in the status bar
addPermanentWidget()
Adds the given widget object in the status bar permanently
showMessage()
Displays a temporary message in the status bar for a specified time interval
clearMessage()
Removes any temporary message being shown
removeWidget()
Removes specified widget from the status bar
In the following example, a top level QMainWindow has a menu bar and a QTextEdit object as its central widget.
Window’s status bar is activated as explained above.
Menu’s triggered signal is passed to processtrigger() slot function. If ‘show’ action is triggered, it displays a temporary message in the status bar as −
if (q.text() == "show"):
   self.statusBar.showMessage(q.text()+" is clicked",2000)
The message will be erased after 2000 milliseconds (2 sec). If ‘add’ action is triggered, a button widget is added.
if q.text() == "add":
   self.statusBar.addWidget(self.b)
Remove action will remove the button from the status bar.
if q.text() == "remove":
   self.statusBar.removeWidget(self.b)
   self.statusBar.show()
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class statusdemo(QMainWindow):
   def __init__(self, parent = None):
      super(statusdemo, self).__init__(parent)
		
      bar = self.menuBar()
      file = bar.addMenu("File")
      file.addAction("show")
      file.addAction("add")
      file.addAction("remove")
      file.triggered[QAction].connect(self.processtrigger)
      self.setCentralWidget(QTextEdit())
		
      self.statusBar = QStatusBar()
      self.b = QPushButton("click here")
      self.setWindowTitle("QStatusBar Example")
      self.setStatusBar(self.statusBar)
		
   def processtrigger(self,q):
	
      if (q.text() == "show"):
         self.statusBar.showMessage(q.text()+" is clicked",2000)
			
      if q.text() == "add":
         self.statusBar.addWidget(self.b)
			
      if q.text() == "remove":
         self.statusBar.removeWidget(self.b)
         self.statusBar.show()
			
def main():
   app = QApplication(sys.argv)
   ex = statusdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output. Status bar shows caption of selected menu button −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Java double Keyword

❮ Java Keywords

double myNum = 19.99d;
System.out.println(myNum);


Try it Yourself »

The double keyword is a data type that can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
Read more about data types in our Java Data Types Tutorial.

❮ Java Keywords

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.
How to iterate through a tuple in Python?

There are different ways to iterate through a tuple object. The for statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to foreach statement in Java. Its syntax is −
for var in tuple:
stmt1
stmt2
Following script will print all items in the list
T = (10,20,30,40,50)
for var in T:
print (T.index(var),var)
The output generated is −
0 10
1 20
2 30
3 40
4 50
Another approach is to iterate over range upto length of tuple, and use it as index of item in tuple
for var in range(len(T)):
  print (var,T[var])
You can also obtain enumerate object from the tuple and iterate through it.
Following code too gives same output.
for var in enumerate(T):
  print (var)
JavaScript Function Invocation

The function invocation is used to execute the code inside the curly braces in the function definition by adding () after function name after it has been defined to invoke that particular function.
Following is the code for implementing JavaScript function invocation −
 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Function Invocation</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above buttons to invoke the function
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   function helloWorld() {
      alert("HELLO WORLD");
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      helloWorld();
   });
</script>
</body>
</html>
On clicking the “CLICK HERE” button −
How to add a new column to a matrix in R?

A data collection process is one of the initial and very important tasks in a data analysis project and sometimes we miss something. Therefore, we need to collect that data later and add it to the originally collected data. This mistake can be done for matrix data as well, hence we might need to add a new column to original matrix and this can be done by using cbind function.
Live Demo
> M1<-matrix(1:25,nrow=5)
> M1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
> V1<-26:30
> M1<-cbind(M1,V1)
> M1
V1
[1,] 1 6 11 16 21 26
[2,] 2 7 12 17 22 27
[3,] 3 8 13 18 23 28
[4,] 4 9 14 19 24 29
[5,] 5 10 15 20 25 30
Live Demo
> M2<-matrix(rpois(81,5),ncol=9)
> M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 7 3 3 4 2 3 6 3 6
[2,] 7 5 6 6 4 4 4 5 3
[3,] 5 6 3 9 4 3 4 6 4
[4,] 4 4 3 6 1 3 6 9 4
[5,] 2 4 4 5 9 2 3 4 4
[6,] 6 5 5 3 3 4 3 9 5
[7,] 11 5 5 6 4 5 3 4 4
[8,] 4 3 1 1 9 3 5 4 3
[9,] 14 7 5 1 6 4 4 6 5
> V2<-rpois(9,10)
> M2<-cbind(M2,V2)
> M2
V2
[1,] 7 3 3 4 2 3 6 3 6 14
[2,] 7 5 6 6 4 4 4 5 3 9
[3,] 5 6 3 9 4 3 4 6 4 7
[4,] 4 4 3 6 1 3 6 9 4 10
[5,] 2 4 4 5 9 2 3 4 4 6
[6,] 6 5 5 3 3 4 3 9 5 11
[7,] 11 5 5 6 4 5 3 4 4 10
[8,] 4 3 1 1 9 3 5 4 3 12
[9,] 14 7 5 1 6 4 4 6 5 13
Live Demo
> M3<-matrix(rnorm(25,2,0.36),nrow=5)
> M3
[,1] [,2] [,3] [,4] [,5]
[1,] 1.696484 1.269688 1.607353 1.913940 2.463333
[2,] 2.485409 2.107897 1.989745 2.072183 1.120741
[3,] 2.202257 1.715435 2.027664 1.230764 2.435480
[4,] 1.845053 2.132015 1.845209 1.480105 1.870550
[5,] 2.286963 1.776010 1.691820 1.634944 2.091766
> V3<-rnorm(5,5,1)
> M3<-cbind(M3,V3)
> M3
V3
[1,] 1.696484 1.269688 1.607353 1.913940 2.463333 4.961799
[2,] 2.485409 2.107897 1.989745 2.072183 1.120741 5.243562
[3,] 2.202257 1.715435 2.027664 1.230764 2.435480 4.393539
[4,] 1.845053 2.132015 1.845209 1.480105 1.870550 6.008758
[5,] 2.286963 1.776010 1.691820 1.634944 2.091766 5.988232
Live Demo
> M4<-matrix(round(runif(64,2,5),0),ncol=8)
> M4
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 3 5 5 3 4 3 4 3
[2,] 3 3 4 3 3 3 4 3
[3,] 3 4 3 4 4 4 4 2
[4,] 3 2 3 2 5 2 5 4
[5,] 4 4 2 5 3 3 2 3
[6,] 3 4 3 3 4 2 4 5
[7,] 4 3 3 3 4 4 3 2
[8,] 4 3 4 3 4 4 2 5
> V4<-round(runif(8,1,5),0)
> M4<-cbind(M4,V4)
> M4
V4
[1,] 3 5 5 3 4 3 4 3 5
[2,] 3 3 4 3 3 3 4 3 5
[3,] 3 4 3 4 4 4 4 2 4
[4,] 3 2 3 2 5 2 5 4 2
[5,] 4 4 2 5 3 3 2 3 5
[6,] 3 4 3 3 4 2 4 5 4
[7,] 4 3 3 3 4 4 3 2 2
[8,] 4 3 4 3 4 4 2 5 3
Live Demo
> M5<-matrix(round(rexp(36,1.22),2),ncol=6)
> M5
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.55 0.02 1.27 0.31 0.10 0.08
[2,] 1.13 0.26 0.46 0.06 0.90 0.43
[3,] 0.14 1.26 0.89 0.12 0.16 0.63
[4,] 0.33 0.79 1.03 2.72 0.17 0.49
[5,] 0.17 4.59 0.04 0.26 0.18 1.52
[6,] 0.46 1.05 0.10 0.96 0.64 0.31
> V5<-round(rexp(6,2.1),2)
> M5<-cbind(M5,V5)
> M5
V5
[1,] 1.55 0.02 1.27 0.31 0.10 0.08 0.07
[2,] 1.13 0.26 0.46 0.06 0.90 0.43 0.00
[3,] 0.14 1.26 0.89 0.12 0.16 0.63 0.40
[4,] 0.33 0.79 1.03 2.72 0.17 0.49 0.23
[5,] 0.17 4.59 0.04 0.26 0.18 1.52 0.32
[6,] 0.46 1.05 0.10 0.96 0.64 0.31 0.64
Is there any way to skip finally block even if some exception occurs in exception block using java?

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
To handle exceptions Java provides a try-catch block mechanism.
A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.
try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}
When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in the try block it is passed to the catch block (or blocks) that follows it.
If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
import java.io.File;
import java.io.FileInputStream;
public class Test {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         File file =new File("my_file");
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}
Given file path is not found
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System.exit(0) method, at the end of the catch block which is just before the finally block.
public class FinallyExample {
   public static void main(String args[]) {
      int a[] = {21, 32, 65, 78};
      try {
         System.out.println("Access element three :" + a[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
         System.exit(0);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 5
How to Recognize Optical Characters in Images in Python?

17 Feb, 2022
Prerequisite: Pytesseract, OpenCV
In this article, we are going to recognize the character from the images and get text data out of an image. Let’s take a quick introduction to the required module.
OpenCV: It is a Python module in which we can do image processing, video capture, and some analysis tools like face detection or object detection. It has C++, Python, Java, and MATLAB interfaces and supports Windows, Linux, Android, and Mac OS.
Pytesseract: Python-tesseract is an optical character recognition (OCR) tool for Python. That is, it will recognize and “read” the text embedded in images. Python-tesseract is a wrapper for Google’s Tesseract-OCR Engine. It is also useful as a stand-alone invocation script to tesseract, as it can read all image types supported by the Pillow and Leptonica imaging libraries, including jpeg, png, gif, BMP, tiff, and others. Additionally, if used as a script, Python-tesseract will print the recognized text instead of writing it to a file.
Approach:
Import required module
Setting the path of pytesseract.
Read the image with cv2.imread()
Convert image in RGB format.
Extract text from image using pytesseract.image_to_string(img).
We are going to use this image for a demonstration:
Below is the full implementation: 
Python3
# importing the librariesimport cv2import pytesseract  # seting the path of pytesseract exe# you have to write the location of# on which your tesseract was installedpytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'  # Now we will read the image in our program# you have to put your image path in place of photo.jpgimg = cv2.imread('photo.jpg')  # Our image will read as BGR format,# So we will convert in RGB format because # tesseract can only read in RGB formatimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # For getting the text and number from imageprint(pytesseract.image_to_string(img))  # For displaying the original imagecv2.imshow("result", img)cv2.waitKey(0)
Output:
GeeksforGeeks
sagar0719kumar
Image-Processing
Picked
Python-OpenCV
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to rotate an image using Python?

03 Jun, 2022
In this article, let’s see how to rotate an Image using Python. By Image Rotation, the image is rotated about its center by a specified number of degrees. The rotation of an image is a geometric transformation. It can be done either by Forward Transformation (or) Inverse Transformation.
Here Image Processing Library with Pillow uses Inverse Transformation. If the Number Of Degrees Specified for Image Rotation is Not an Integer Multiple of 90 Degrees, then some Pixel Values Beyond Image Boundaries i.e Pixel values lying outside the Dimension of the image. Such Values will not be displayed in the output image. 
Method:1 Using Image Processing Library Pillow
Python3
# import the Python Image# processing Libraryfrom PIL import Image # Giving The Original image Directory# SpecifiedOriginal_Image = Image.open("./gfgrotate.jpg") # Rotate Image By 180 Degreerotated_image1 = Original_Image.rotate(180) # This is Alternative Syntax To Rotate# The Imagerotated_image2 = Original_Image.transpose(Image.ROTATE_90) # This Will Rotate Image By 60 Degreerotated_image3 = Original_Image.rotate(60) rotated_image1.show()rotated_image2.show()rotated_image3.show()
Output:
This is Image is Rotated By 180 Degree
This Image Is Rotated By 60 Degree
This Image Is Rotated By 90 Degree
The rotate() method of Python Image Processing Library Pillow Takes the number of degrees as a parameter and rotates the image in Counter Clockwise Direction to the number of degrees specified.
Method 2: Using Open-CV to rotate an image by an angle in Python
This is common that everyone knows that Python Open-CV is a module that will handle real-time applications related to computer vision. Open-CV works with image processing library imutils which deals with images. The imutils.rotate() function is used to rotate an image by an angle in Python.
Python3
import cv2  # importing cvimport imutils  # read an image as input using OpenCVimage = cv2.imread(r".\gfgrotate.jpg") Rotated_image = imutils.rotate(image, angle=45)Rotated1_image = imutils.rotate(image, angle=90) # display the image using OpenCV of# angle 45cv2.imshow("Rotated", Rotated_image) # display the image using OpenCV of# angle 90cv2.imshow("Rotated", Rotated1_image) # This is used for To Keep On Displaying# The Image Until Any Key is Pressedcv2.waitKey(0)
Output:
Image Rotated Using Open-CV in 45 Degree
Image Rotated Using Open-CV in 90 Degree
Even this Open-CV Rotates the image in Counter Clockwise direction to the number of degrees specified
simranarora5sos
nikhatkhan11
Image-Processing
Picked
Python-OpenCV
Python-pil
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Python | Decimal max() method

17 Sep, 2019
Decimal#max() : max() is a Decimal class method which compares the two Decimal values and return the max of two.
Syntax:  Decimal.max()

Parameter:  Decimal values

Return:  the max of two.

Code #1 : Example for max() method
# Python Program explaining # max() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.max() methodprint ("\n\nDecimal a with max() method : ", a.max(a))  print ("Decimal a with max() method : ", a.max(b))  print ("Decimal b with max() method : ", b.max(a))
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with max() method :  -1
Decimal a with max() method :  0.142857
Decimal b with max() method :  0.142857


Code #2 : Example for max() method
# Python Program explaining # max() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.max() methodprint ("\n\nDecimal a with max() method : ", a.max(a))  print ("Decimal a with max() method : ", a.max(b))  print ("Decimal b with max() method : ", b.max(a))
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with max() method :  -3.14
Decimal a with max() method :  3.21E+7
Decimal b with max() method :  3.21E+7

Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
The Null Object in Python

Python does not have a null object. But the most closely related similar object is none. In this article, we will see how how None behaves in Python.
Checking the type of Null and None we see that there is no Null Type and the None object is of type NoneType.
print(type(None))
print(type(Null))
Running the above code gives us the following result −
Traceback (most recent call last):
   File "C:\Users\xxx\scratch.py", line 4, in
      print(type(Null))
NameError: name 'Null' is not defined
None is the same as False.
None is the same as False.
None is the same as False.
None is the same as False.
None is the same as False.
None is the same as False.
None is an empty string.
None is an empty string.
None is 0.
None is 0.
Comparing None to anything will always return False except None itself.
Comparing None to anything will always return False except None itself.
An undefined variable is not the same as a Null variable. A variable will be null in Python if you assign None to it.
var_a = None
print('var_a is: ',var_a)
print(var_b)
Running the above code gives us the following result −
Traceback (most recent call last):
   File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 5, in <module>
      print(var_b)
NameError: name 'var_b' is not defined
var_a is: None
If something is declared as None, you can not use any methods to add, remove elements from it.
 Live Demo
listA = [5,9,3,7]
listA.append(18)
print(listA)
listA = None
listA.append(34)
print(listA)
Running the above code gives us the following result −
[5, 9, 3, 7, 18]
Traceback (most recent call last):
   File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 7, in
      listA.append(34)
AttributeError: 'NoneType' object has no attribute 'append'
HTML | draggable Attribute

02 Jun, 2022
This attribute is used to specify whether an element is draggable or not. Links and images are by default draggable. The draggable attribute is often used in the drag and drop operations.
Supported Tags: It supports all HTML elements. 
Syntax: 
<element draggable = "true|false|auto">
Attribute Value: This attribute contains three value which are listed below: 
true: This value represents the element is draggable.
false: This value represents the element is not draggable.
auto: This value represents the uses of the default browser.
Example: 
HTML
<!DOCTYPE HTML><html>    <head>        <title>draggable attribute</title>        <style>        .dropbox {            width: 350px;            height: 70px;            padding: 10px;            border: 1px solid #aaaaaa;        }        h1 {            color:green;        }        </style>        <script>            function droppoint(event) {                var data = event.dataTransfer.getData("Text");                event.target.appendChild(document.getElementById(data));                event.preventDefault();            }            function allowDropOption(event) {                event.preventDefault();            }            function dragpoint(event) {                event.dataTransfer.setData("Text", event.target.id);            }        </script>    </head>    <body>        <center>        <h1>GeeksforGeeks</h1>        <h2>draggable attribute</h2>        <div class = "dropbox" ondrop="droppoint(event)"        ondragover="allowDropOption(event)"></div>        <p id="drag1" draggable="true" ondragstart="dragpoint(event)">        GeeksforGeeks: A computer science portal for geeks</p>           </center>    </body></html>
Output: Before dragging:  
After dragging and drop  
Supported Browsers: The browser supported by draggable attribute are listed below: 
Google Chrome 
Edge 12 and above
Internet Explorer 
Firefox 2 and above
Opera 12.0 and above
Safari 
 
surinderdawra388
ManasChhabra2
kumargaurav97520
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to use NamedTuple and Dataclass in Python? - GeeksforGeeks

26 Jul, 2020
We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don’t worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a class in Python. 
NamedTuple 
DataClass 
First, of all let’s create a class with the naive methods. Let’s create a class transaction, where each payment transaction has a sender, a receiver, date, and the amount. 
Example:
Python
class Transaction:          def __init__(self, amount, sender, receiver, date):      self.amount = amount      self.sender = sender      self.receiver = receiver      self.date = date
This is pretty straight forward but let’s be honest this is a lot of code for us lazy developers. Now, this is where NamedTuple comes in.
Named Tuple is essentially an extension of the Python built-in tuple data type. Python’s tuple is a simple data structure for grouping objects with different types. Its defining feature is being immutable i.e an object whose state cannot be modified after it is created. 
We will start with the collections package. This package provides alternatives to Python’s general built-in types like dict, list, set, and tuple. Creating a NamedTuple object is as straightforward as creating the class.  
Python3
import collections  Transaction = collections.namedtuple('Transaction',                                     ['sender', 'amount',                                      'receiver', 'date'])  # Creating objectrecord = Transaction(sender="Aryaman",                     receiver="Ankur",                     date="2020-06-18",                     amount=1.0)  print(record)print(record.receiver)
Output:
Transaction(sender=’Aryaman’, amount=1.0, receiver=’Ankur’, date=’2020-06-18′)
Ankur
DataClass may be a new feature introduced since Python 3.7. It is used as a decorator. What it does under the hood is implementing __init__, __repr__, etc for us. 
Example:
Python3
from dataclasses import dataclass    @dataclassclass Transaction:    sender: str    receiver: str    date: str    amount: float    # Creating objectrecord = Transaction(sender="Aryaman",                     receiver="Ankur",                     date="2020-06-18",                     amount=1.0)  print(record)print(record.receiver)
Output:
Transaction(sender=’Aryaman’, receiver=’Ankur’, date=’2020-06-18′, amount=1.0)Ankur
NamedTuple behaves like a tuple, while DataClass behaves more like a regular Python class because by default, the attributes are all mutable and they can only be accessed by name, not by index. 
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
iomanip setbase() function in C++ with Examples - GeeksforGeeks

10 Oct, 2019
The setbase() method of iomaip library in C++ is used to set the ios library basefield flag based on the argument specified as the parameter to this method.
Syntax:
setbase (int base)

Parameters: This method accepts base as a parameter which is the integer argument corresponding to which the base is to be set. 10 stands for dec, 16 stands for hex, 8 stands for oct, and any other value stands for 0 (reset).
Return Value: This method does not returns anything. It only acts as stream manipulators.
Example 1:
// C++ code to demonstrate// the working of setbase() function  #include <iomanip>#include <ios>#include <iostream>  using namespace std;  int main(){      // Initializing the integer    int num = 50;      cout << "Before set: \n"         << num << endl;      // Using setbase()    cout << "Setting base to hex"         << " using setbase: \n"         << setbase(16)         << num << endl;      return 0;}
Before set: 
50
Setting base to hex using setbase: 
32

Example 2:
// C++ code to demonstrate// the working of setbase() function  #include <iomanip>#include <ios>#include <iostream>  using namespace std;  int main(){      // Initializing the integer    int num = 50;      cout << "Before set: \n"         << num << endl;      // Using setbase()    cout << "Setting base to oct"         << " using setbase: \n"         << setbase(8)         << num << endl;      return 0;}
Before set: 
50
Setting base to oct using setbase: 
62

Reference: http://www.cplusplus.com/reference/iomanip/setbase/
CPP-Functions
cpp-input-output
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
jQuery UI datepicker onSelect Option - GeeksforGeeks

19 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI datepicker onSelect Option is called when the datepicker option is selected. The onSelect option holds a function that contains selected date as text and the datepicker instance as parameters.
Syntax:
onSelect: Function( String dateText, Object inst ) {  }
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8" />    <link href=    "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"         rel="stylesheet" />    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script>    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>      <script>        $(function () {            $("#gfg").datepicker({                onSelect: function (date, datepicker) {                    if (date != "") {                        alert("Selected Date: " + date);                    }                }            });        });    </script></head>  <body>    <h1>GeeksforGeeks</h1>    <h3>jQuery UI datepicker onSelect Option</h3>      <div>Enter Date: <input type="text" id="gfg" /></div></body>  </html>
Output:
Reference: https://api.jqueryui.com/datepicker/#option-onSelect
HTML-Tags
jQuery-Methods
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Ruby | Array map() function - GeeksforGeeks

06 Dec, 2019
Array#map() : map() is a Array class method which returns a new array containing the values returned by the block.
Syntax: Array.map()
Parameter: Array
Return: a new array containing the values returned by the block.
Example #1 :
# Ruby code for map() method  # declaring arraya = [18, 22, 33, 3, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 3, 3, 50, 6]  # mapputs "map method : #{a.map {|num| num > 10 }}\n\n"  # mapputs "map method : #{b.map {|x| x.odd? }}\n\n"
Output :
map method : [true, true, true, false, false, false]

map method : [true, false, true, true, false, true]


Example #2 :
# Ruby code for map() method  # declaring arraya = [18, 22, 33, 3, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 3, 3, 53, 6]  # mapputs "map method : #{c.map {|num| num > 10 }}\n\n"  # mapputs "map method : #{c.map {|num| num.even? }}\n\n"
Output :
map method : [true, true, false, false, true, false]

map method : [true, true, false, false, false, true]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
Simple Calculator in Bash - GeeksforGeeks

15 Jul, 2021
Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input in Bash.
Example: 
Enter two numbers:
5.6
3.4
Enter Choice: 
1. Addition
2. Subtraction
3. Multiplication
4. Division
3
5.6 * 3.4 = 19.0 
Approach:  
1. Read Two Numbers
2. Input Choice (1-Addition, 2-Subtraction, 3-Multiplication, 4-Division) 
3. if Choice equals 1
    Calculate res = a + b
   else If Choice equals 2
    Calculate res = a - b
   else if Choice equals 3
    Calculate res = a * b
   else if Choice equals 4
    Calculate res = a / b
4. Output Result, res
Commands/Statement Used: 
1. echo echo is one of the mostly used command. It is used to print a line of text in standard output.  
$ echo [-neE] [arg ...] 
2. read The command read in Linux is used to read the input from the keyboard. 3. Switch-Case When there are a lot of if statement in Shell and it becomes confusing. Then it is good to use case statement.4. bc Command Checkout the link for bc Command bc Command Linux Example
Bash
# !/bin/bash # Take user Inputecho "Enter Two numbers : "read aread b # Input type of operationecho "Enter Choice :"echo "1. Addition"echo "2. Subtraction"echo "3. Multiplication"echo "4. Division"read ch # Switch Case to perform# calculator operationscase $ch in  1)res=`echo $a + $b | bc`  ;;  2)res=`echo $a - $b | bc`  ;;  3)res=`echo $a \* $b | bc`  ;;  4)res=`echo "scale=2; $a / $b" | bc`  ;;esacecho "Result : $res"
Output:
 
References: Array Basics Shell Scripting | Set 2 (Using Loops) Array Basics in Shell Scripting | Set 1 Sorting an array in Bash using Bubble sort bc Command Linux Example 
sooda367
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
Files size() method in Java with Examples - GeeksforGeeks

29 Jul, 2019
size() method of java.nio.file.Files help us to get the size of a file (in bytes). This method returns the file size, in bytes by taking the path of the file as a parameter. The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is implementation-specific and therefore unspecified.
Syntax:
public static long size(Path path)
                 throws IOException

Parameters: This method accepts a parameter path which is the path to the file.
Return value: This method returns the file size, in bytes.
Exception: This method will throw following exceptions:
IOException if an I/O error occurs.SecurityException in the case of the default provider, and a security manager is installed, its checkRead method denies read access to the file.
IOException if an I/O error occurs.
SecurityException in the case of the default provider, and a security manager is installed, its checkRead method denies read access to the file.
Below programs illustrate size?(Path) method:Program 1:
// Java program to demonstrate// Files.size() method  import java.io.IOException;import java.nio.file.*;  public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path            = Paths.get("D:\\GIT_EWS_PROJECTS\\logger"                        + "\\src\\logger"                        + "\\GFG.java");          // get File Size          long result;          result = Files.size(path);          System.out.println("File " + path                           + " Size = "                           + result + " bytes");    }}
Program 2:
// Java program to demonstrate// Files.size() method  import java.io.IOException;import java.nio.file.*;  public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path            = Paths.get("D:\\User Aman\\"                        + "Documents\\MobaXterm\\"                        + "\\ArrayList.docx");        // get File Size        long result;        result = Files.size(path);          System.out.println("File " + path                           + " Size = "                           + result + " bytes");    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#size?(java.nio.file.Path)
Java-Files
Java-Functions
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Iterate through LinkedHashMap using an Iterator in Java - GeeksforGeeks

04 Jan, 2021
LinkedHashMap is a pre-defined class in java like HashMap. The only difference between LinkedHashMap and HashMap is LinkedHashMap preserve insertion order while HashMap does not preserve insertion order. The task is to iterate through a LinkedHashMap using an Iterator. We use the Iterator object to iterate through a LinkedHashMap.
Example
Input:    Key - 2  : Value - 6
    Key - 3  : Value - 4
    Key - 6  : Value - 5
    Key - 4  : Value - 10
    Key - 5  : Value - 6

Output:

Key = Value
2   = 6
3   = 4
6   = 5
4   = 10
5   = 6
Algorithm : 
1. Create a LinkedHashMap and add key, value pairs.
2. we convert our LinkedHashMap to entrySet using,
Set s = lhm.entrySet();
3. we define iterator for our set.    
Iterator it=s.iterator();

4. Using while loop we iterate through our linkedHashMap. 
while(it.hasNext())                      
     System.out.println(it.next()); 
Implementation
Java
// Java program to Iterate through LinkedHashMap using an// Iterator  import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        // create a linkedhashmap        LinkedHashMap<Integer, Integer> lhm            = new LinkedHashMap<>();          // add mappings        lhm.put(2, 6);        lhm.put(3, 4);        lhm.put(6, 8);        lhm.put(4, 10);        lhm.put(5, 6);          // create an entryset        Set s = lhm.entrySet();          // create an iterator        Iterator it = s.iterator();          // iterate an print the mappings        System.out.println("key=Value");        while (it.hasNext()) {            System.out.println(it.next());        }    }}
key=Value
2=6
3=4
6=8
4=10
5=6
Time Complexity: O(n).
Java-LinkedHashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
How to Iterate HashMap in Java?
Python EasyGUI - Message Box - GeeksforGeeks

11 Jun, 2021
Message Box : It is used to display a window having a message or information in EasyGUI, it can be used where there is a need to display some message or some important information, it contains message and a “Ok” button which when pressed closes the message, below is how the message box looks like  
EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from other GUI generators in that EasyGUI is NOT event-driven. Instead, all GUI interactions are invoked by simple function calls. Unlike other complicated GUI’s EasyGUI is the simplest GUI till now. EasyGUI depends on the Tkinter module.  
In order to do this we will use msgbox methodSyntax : msgbox(message, title, ok_button_text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string i.e display text of the OK button Return : It returns the text of the OK button  
Example : In this we will create a message box having a message and will set the display text of the OK button, below is the implementation  
Python3
# importing easygui modulefrom easygui import * # message / information to be displayed on the screenmessage = "This is a Message Box in EasyGUI" # title of the windowtitle = "GfG - EasyGUI" # text of the Ok buttonok_btn_txt = "Continue" # creating a message boxoutput = msgbox(message, title, ok_btn_txt) # printing the outputprint("User pressed  : " + output)
Output :  
 
User pressed  : Continue
Another Example In this we will create a window having message and title but without changing the text of the ok button  
Python3
# importing easygui modulefrom easygui import * # message / information to be displayed on the screenmessage = "This is a Message Box in EasyGUI (GeeksforGeeks)" # title of the windowtitle = "GfG - EasyGUI" # creating a message boxoutput = msgbox(message, title) # printing the outputprint("User pressed  : " + output)
Output :  
 
User pressed  : OK
 
adnanirshad158
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Triple Quotes in Python - GeeksforGeeks

10 Aug, 2021
Spanning strings over multiple lines can be done using python’s triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes. 
Syntax: “”” string””” or ”’ string”’
Note: Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments. Anything inside triple quotes is read by the interpreter. When the interpreter encounters the hash symbol, it ignores everything after that. That is what a comment is defined to be.  
Python3
"""This is a really long comment that can makethe code look ugly and uncomfortable to read ona small screen so it needs to be broken intomulti-line strings using double triple-quotes""" print("hello Geeks")
hello Geeks
 
Similarly, single triple quotes can also be used for the same purpose as shown below: 
Python3
'''This is a really long comment that can makethe code look ugly and uncomfortable to read ona small screen so it needs to be broken intomulti-line strings using double triple-quotes''' print("hello Geeks")
hello Geeks
 
Note : We can also uses # in multiples lines, but triple quotes look much better. 
Another use case of triple quotes is to create strings in Python. Adding the required characters within triple quotes can convert those characters into python strings. The below codes shows the use of triple quotes for creating strings:  
Example 1: 
Python3
str1 = """I """str2 = """am a """str3 = """Geek""" # check data type of str1, str2 & str3print(type(str1))print(type(str2))print(type(str3)) print(str1 + str2 + str3)
<class 'str'>
<class 'str'>
<class 'str'>
I am a Geek
 
Example 2: Multi-line strings using triple quotes. End of lines are included by default.  
Python3
my_str = """IamaGeek !""" # check data type of my_strprint(type(my_str)) print(my_str)
<class 'str'>
I
am
a
Geek !
 
Example 3: If we wish to ignore end of lines, we need to use ” .
Python3
my_str = """I \am \a \Geek !""" # check data type of my_strprint(type(my_str)) print(my_str)
<class 'str'>
I am a Geek !
 
abirmukherjee21
python-basics
python-string
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python