code-rag-bench/online-tutorials huggingface dataset:
Print pyramid of GeeksforGeeks in PL/SQL - GeeksforGeeks

30 Jul, 2021
PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements. All the statements of a block are passed to the oracle engine all at once which increases processing speed and decreases the traffic.PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other.
Typically, each block performs a logical action in the program. A block has the following structure:
DECLARE
    declaration statements;

BEGIN
    executable statements

EXCEPTIONS
    exception handling statements

END;
Now write a program in pl/sql which print a pyramid of string “GeeksforGeeks” shown below
Examples – 
GeeksforGeeks
GeeksforGeek
GeeksforGee
GeeksforGe
GeeksforG
Geeksfor
Geeksfo
Geeksf
Geeks
Geek
Gee
Ge
G
Code –
C++
--Declaration BlockDECLARE -- declaration of string as Geeksforgeeksstr VARCHAR2(100) := 'GeeksforGeeks'; -- len of string and num for no of rowslen VARCHAR2(100);num NUMBER(15); -- execution part beginBEGIN --calculating length of stringnum:=LENGTH(str);  -- starting of while from-- from num to till num>1WHILE num>=1    LOOP        len:=SUBSTR(str,1,num);        num:=num-1;        DBMS_OUTPUT.PUT_LINE(len);         --ending of loop here       END LOOP; -- end of beginning blockEND; -- End program
Output: 
GeeksforGeeks
GeeksforGeek
GeeksforGee
GeeksforGe
GeeksforG
Geeksfor
Geeksfo
Geeksf
Geeks
Geek
Gee
Ge
G
Disadvantages of SQL – 
SQL doesn’t provide the programmers with a technique of condition checking, looping, and branching.
SQL statements are passed to the Oracle engine one at a time which increases traffic and decreases speed.
SQL has no facility of error checking during manipulation of data.
Akanksha_Rai
surindertarika1234
surinderdawra388
SQL-PL/SQL
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Characteristics of Internet of Things
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Advantages and Disadvantages of OOP
Introduction to Internet of Things (IoT) | Set 1
Election algorithm and distributed processing
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Activation Functions
Lex Program to count number of words
Magical String in C++

Suppose there is a string. That string is called a magical string S, that consists of only '1' and '2' and obeys the following rules −
The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.
The first few components of string S is the following − S = "1221121221221121122......"
If we group the consecutive '1's and '2's in S, it will be − 1 22 11 2 1 22 1 22 11 2 11 22 ...... and the occurrences of '1's or '2's in each group are − 1 2 2 1 1 2 1 2 2 1 2 2 ......
Now suppose we have an integer N as input, find the number of '1's in the first N number in the magical string S. So if the input is like 6, then the output will be 3, as first 6 elements in the magical string is “12211”. This contains three 1s, so return 3.
To solve this, we will follow these steps −
if n <= 0, then return 0, if n <= 3, then return 1
ret := 1, make an array arr of size n
arr[0] := 1, arr[1] := 2, arr[2] := 2
head := 2, tail := 3 and num := 1
while tail < nfor i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loopnum = num XOR 3increase head by 1
for i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loop
arr[tail] := num
if num is 1 and tail < n, then increase ret by 1
increase tail by 1
if tail >= n, then break the loop
num = num XOR 3
increase head by 1
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int magicalString(int n) {
      if(n <= 0) return 0;
      if(n <= 3) return 1;
      int ret = 1;
      vector <int> arr(n);
      arr[0] = 1;
      arr[1] = 2;
      arr[2] = 2;
      int head = 2;
      int tail = 3;
      int num = 1;
      while(tail < n){
         for(int i = 0; i < arr[head]; i++){
            arr[tail] = num;
            if(num == 1 && tail < n) ret++;
            tail++;
            if(tail >= n) break;
         }
         num ^= 3;
         head++;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.magicalString(6));
}
6
3
Java catch Keyword

❮ Java Keywords

If an error occur, use try...catch to catch the error and execute some code to handle it:
try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
}


Try it Yourself »

The catch keyword catches exceptions generated by try statements.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Read more about exceptions in our Java Try..Catch 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.
PyQt5 – How to change border style of MainWindow ? - GeeksforGeeks

26 Mar, 2020
When we create a window in PyQt5, by default, there is no special type of border to it. But we change the style, thickness as well as color of the main window by using setStyleSheet() method.
Below is how normal border vs styled border looks like 
Syntax : self.setStyleSheet(“border : 3px dashed blue;”)
Argument: It takes string as argument."border : size_of_border type_of_border color_of_border;"
Action performed : It sets the border style.
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # setting up the style of border        self.setStyleSheet("border : 3px dashed blue;")          # creating a label widget        self.label_1 = QLabel("new border ", self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions
Class getSuperclass() method in Java with Examples - GeeksforGeeks

27 Jan, 2022
The getSuperclass() method of java.lang.Class class is used to get the super class of this entity. This entity can be a class, an array, an interface, etc. The method returns the super class of this entity.Syntax:  
public Class<T> getSuperclass()
Parameter: This method does not accept any parameter.Return Value: This method returns the super class of this entity.Below programs demonstrate the getSuperclass() method.Example 1: 
Java
// Java program to demonstrate getSuperclass() method public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the super class of myClass        // using getSuperclass() method        System.out.println("Superclass of myClass: "                           + myClass.getSuperclass());    }}
Class represented by myClass: class Test
Superclass of myClass: class java.lang.Object
 
Example 2: 
Java
// Java program to demonstrate getSuperclass() method public class Test {     class Arr {    }     public static void main(String[] args)        throws ClassNotFoundException    {        // returns the Class object for Arr        Class arrClass = Arr.class;         // Get the super class of arrClass        // using getSuperclass() method        System.out.println("Superclass of arrClass: "                           + arrClass.getSuperclass());    }}
Superclass of arrClass: class java.lang.Object
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSuperclass– 
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
Converting Row into list RDD in PySpark

18 Jul, 2021
In this article, we are going to convert Row into a list RDD in Pyspark.
Creating RDD from Row for demonstration:
Python3
# import Row and SparkSessionfrom pyspark.sql import SparkSession, Row  # create sparksessionspark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()  # create student data with Row functiondata = [Row(name="sravan kumar",            subjects=["Java", "python", "C++"],            state="AP"),          Row(name="Ojaswi",            lang=["Spark", "Java", "C++"],            state="Telangana"),          Row(name="rohith",            subjects=["DS", "PHP", ".net"],            state="AP"),          Row(name="bobby",            lang=["Python", "C", "sql"],            state="Delhi"),          Row(name="rohith",            lang=["CSharp", "VB"],            state="Telangana")]rdd = spark.sparkContext.parallelize(data)  # display actual rddrdd.collect()
Output:
[Row(name='sravan kumar', subjects=['Java', 'python', 'C++'], state='AP'),
Row(name='Ojaswi', lang=['Spark', 'Java', 'C++'], state='Telangana'),
Row(name='rohith', subjects=['DS', 'PHP', '.net'], state='AP'),
Row(name='bobby', lang=['Python', 'C', 'sql'], state='Delhi'),
Row(name='rohith', lang=['CSharp', 'VB'], state='Telangana')]
Using map() function we can convert into list RDD
Syntax: rdd_data.map(list)
where, rdd_data is the data is of type rdd.
Finally, by using the collect method we can display the data in the list RDD.
Python3
# convert rdd to list by using map() methodb = rdd.map(list)  # display the data in b with collect methodfor i in b.collect():    print(i)
Output:
['sravan kumar', ['Java', 'python', 'C++'], 'AP']
['Ojaswi', ['Spark', 'Java', 'C++'], 'Telangana']
['rohith', ['DS', 'PHP', '.net'], 'AP']
['bobby', ['Python', 'C', 'sql'], 'Delhi']
['rohith', ['CSharp', 'VB'], 'Telangana']
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery UI Button icon Option

22 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Button icon option is used to add an icon inside button element.
Syntax:
$( ".selector" ).button({
  icon: "ui-icon-gear"
});
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 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></head>  <body>    <h1 style="color: green;">GeeksforGeeks</h1>      <h3>jQuery UI Button icon option</h3>      <button>GFG Button</button>      <script>        $("button").button({            icon: "ui-icon-circle-arrow-e"        });    </script></body>  </html>
Output:
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.
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to add options to a select element using jQuery?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Roadmap to Learn JavaScript For Beginners
Upload files in Python

07 Oct, 2021
In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to that particular interaction being client-side and the server-side. A form needs to be created to accept the user input in the form of a file.An HTML form has different attributes that you can set it to, for instance, which URL is the uploaded data is to be submitted is done through the action attribute. An enctype attribute called multi-part/form-data is required in a HTML form to upload a file. Secondly we will be required to use the input tag of HTML and set it equal to “file”. This adds a upload button in addition to an input button in the form. The below code example demonstrates it well: 
html
<html><body>   <form enctype = "multipart/form-data" action = "python_script.py" method = "post">    <p>Upload File: <input type = "file" name = "filename" /></p>     <p><input type = "submit" value = "Upload" /></p> </form></body></html>
The output for the above HTML code would look like below:  
In the above code, the attribute action has a python script that gets executed when a file is uploaded by the user. On the server end as the python script accepts the uploaded data the field storage object retrieves the submitted name of the file from the form’s “filename”. Now all the server needs to do it is read the file that has been uploaded and write it to the “fileitem”(say, ). At the end of this entire process the uploaded file now will be written to the server.So, the python script looks somewhat like the below code:  
Python3
import os fileitem = form['filename'] # check if the file has been uploadedif fileitem.filename:    # strip the leading path from the file name    fn = os.path.basename(fileitem.filename)        # open read and write the file into the server    open(fn, 'wb').write(fileitem.file.read())
Note: The above python script doesn’t work on every server as every server has its own dependencies to allow running a script in their server for security reasons. For instance if using an Azure server one would need to import msvcrt which is Microsoft visual C++ runtime module to work. 
anikaseth98
Python-CGI
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Subset DataFrame by Column Name

16 Mar, 2021
Using Pandas library, we can perform multiple operations on a DataFrame. We can even create and access the subset of a DataFrame in multiple formats. The task here is to create a subset DataFrame by column name. We can choose different methods to perform this task. Here are possible methods mentioned below –
Before performing any action, we need to write few lines of code to import necessary libraries and create a DataFrame.
Creating the DataFrame
Python3
#import pandasimport pandas as pd  # create dataframedata = {'Name': ['John', 'Emily', 'Lara', 'Lucas', 'Katy', 'Jordan'],         'Gender': [30, 27, 21, 21, 16, 20],         'Branch': ['Arts', 'Arts', 'Commerce', 'Science',                    'Science', 'Science'],        'pre_1': [9, 9, 10, 7, 6, 9],        'pre_2': [8, 7, 10, 6, 8, 8]}  df = pd.DataFrame(data)df
Output:
Method 1: Using Python iloc() function 
This function allows us to create a subset by choosing specific values from columns based on indexes. 
Syntax:
df_name.iloc[beg_index:end_index+1,beg_index:end_index+1]
Example: Create a subset with Name, Gender and Branch column
Python3
# create a subset of all rows# and Name, Gender and Branch columndf.iloc[:, 0:3]
Output :
Method 2: Using Indexing Operator
We can use the indexing operator i.e. square brackets to create a subset dataframe 
Example: Create a subset with Name, pre_1, and pre_2 column
Python3
# creating subset dataframe using # indexing operatordf[['Name', 'pre_1', 'pre_2']]
Output – 
Method 3: Using filter() method with like keyword
We can use this method particularly when we have to create a subset dataframe with columns having similarly patterned names.
Example: Create a subset with pre_1 and pre_2 column
Python3
# create a subset of columns pre_1 and pre_2# using filter() methoddf.filter(like='pre')
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
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 ?
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
Create a directory in Python
Type Hints in Python

26 Aug, 2019
Python is a dynamically typed language, which means you never have to explicitly indicate what kind of types variable has. But in some cases, dynamic typing can lead to some bugs that are very difficult to debug and in those cases, Type Hints or Static Typing can be convenient. Type Hints has been introduced as a new feature in Python 3.5.
Let’s look at this factorial function to understand this clearly:
# factorial functiondef factorial(i):  if i<0:    return None  if i == 0:    return 1  return i * factorial(i-1)  # passing an integer to the functionprint(factorial(4))  # passing a string to the functionprint(factorial("4"))  # passing a floating point number to the functionprint(factorial(5.01))
If we try to pass an integer to the function it works correctly. Now, if we try to pass a string to the factorial function, we will get an error, as we can’t do a mathematical comparison with string.Also, if we try to pass a floating point number, let’s say 5.01 we will also get an error here, as we are decrementing the number by 1 according to our logic in each iteration and it becomes -0.99 in the last iteration which returns “None”, which leads to an error as we are trying to multiply “None” with other floating point numbers.
The Type-Hints code looks as follows:We have to specify the type of argument & also the type of the factorial function.
# factorial functiondef factorial(i: int) -> int:  if i<0:    return None  if i == 0:    return 1  return i * factorial(i-1)  # passing a fraction to the functionprint(factorial(5.01))
The Type-Hint is completely ignored by the Python interpreter. So, if we run this code again, we still get the same error.
So, we have to use a static type checker that analyzes our code and tries to detect if we are violating our Type-Hints or not.The best known type checker is “mypy“. We can install it by simply using pip .
pip install mypy
To run the code now, we have to simply call the Python interpreter and we have to specify “-m” to indicate that we want to load a module and then specify the script which we want to check. For example:
mypy program.py
Now, if we run this it will not actually execute our “program.py” script but it will analyze it and will give us an error as like “Argument 1 to factorial has incompatible type float; expected int ” and which is a very clear message and that makes us much easier to debug our code as previously without mypy type checker the error message was not that much specific. And if we run the code again with an integer, it will work as fine.
Python-Data Type
Python-datatype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set value of unsigned char array in C during runtime

31 Oct, 2019
This article explains how to set or change the value of unsigned char array during runtime in C.
Given:Suppose we have an unsigned char array of size n
unsigned char arr[n] = {};

// currently arr = {'', '', '', ...}

To do:We want to set or change the values of this array during runtime.
For example, we want to make the array
arr = {'1', '2', '3', ...}

Solution:This can be achieved with the help of memcpy() method. memcpy() is used to copy a block of memory from a location to another. It is declared in string.h
Syntax:
// Copies "numBytes" bytes from address "from" to address "to"
void * memcpy(void *to, const void *from, size_t numBytes);

Below is the implementation of the above program:
// C program to set the value// of unsigned char array during runtime  #include <stdio.h>#include <string.h>  int main(){      // Initial unsigned char array    unsigned char arr[3] = { 0 };      // Print the initial array    printf("Initial unsigned char array:\n");    for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {        printf("%c ", arr[i]);    }    printf("\n");      // Using memcpy() to change the values    // during runtime    memcpy(arr,           (unsigned char[]){ '1', '2', '3' },           sizeof arr);      // Print the updated array    printf("Updated unsigned char array:\n");    for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {        printf("%c ", arr[i]);    }      printf("\n");    return 0;}
Arrays
C Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
UDP Server-Client implementation in C
C Program to read contents of Whole File
Fabric.js | Rect moveCursor Property

25 May, 2020
In this article, we are going to see how to set the moveCursor property of a rectangle canvas using FabricJS. When we move the canvas object then the cursor will be changed. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width.
To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rectangle provided by FabricJS and set the move cursor value of canvas rectangle using moveCursor property and render the Rectangle on the Canvas as given in the below example.
Syntax:
fabric.Rect({
    width: number,
    height: number,
    moveCursor: string
});
Parameters: This function accepts three parameters as mentioned above and described below:
width: It specifies the width of rectangle.
height: It specifies the height of rectangle.
moveCursor: It specifies that the cursor value when moving the canvas object.
Example: This example uses FabricJS to set the moveCursor value that will works when the object moving.
<!DOCTYPE html> <html>   <head>     <title>         Fabric.js | Rect moveCursor Property    </title>           <!-- Adding the FabricJS library -->    <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script> </head>   <body>      <div style="text-align: center;width: 600px;">          <h1 style="color: green;">              GeeksforGeeks          </h1>          <b>              Fabric.js | Rect moveCursor Property          </b>      </div>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000">     </canvas>           <script>               // Initiate a Canvas instance         var canvas = new fabric.Canvas("canvas");           // Initiate a Rect instance         var rectangle = new fabric.Rect({             width: 200,            height: 100,            fill: '',             stroke: 'green',            strokeWidth: 3,            moveCursor: 'pointer'        });           // Render the Rect in canvas         canvas.add(rectangle);         canvas.centerObject(rectangle);    </script> </body>   </html>
Output:
Fabric.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to convert Octal Number to Decimal and vice-versa

In a computer system, the octal number is expressed in the octal numeral system while the decimal number is in the decimal numeral system. The octal number is in base 8 while the decimal number is in base 10.
Examples of decimal numbers and their corresponding octal numbers are as follows.
A program that converts the octal numbers into decimal and the decimal numbers into octal is as follows −
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
void DecimalToOctal(int decimalNum) {
   int octalNum = 0, placeValue = 1;
   int dNo = decimalNum;
   while (decimalNum != 0) {
      octalNum += (decimalNum % 8) * placeValue;
      decimalNum /= 8;
      placeValue *= 10;
   }
cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl;
}
void OctalToDecimal(int octalNum) {
   int decimalNum = 0, power = 0;
   int oNo = octalNum;
   while(octalNum != 0) {
      decimalNum += (octalNum%10) * pow(8,power);
      ++power;
      octalNum/=10;
   }
   cout<<"Decimal form of octal number "<<oNo<<" is "<<decimalNum<<endl;
}
int main() {
   DecimalToOctal(20);
   OctalToDecimal(32);
   return 0;
}
Octal form of decimal number 20 is 24
Decimal form of octal number 32 is 26
In the above program, the function DecimalToOctal convert the decimal numbers into octal and the function OctalToDecimal converts octal numbers into decimal.
In the function DecimalToOctal, initially the variable octalNum is initialized to zero. The variable placeValue denotes the location of the digit in the number. The value of octalNum is found using a while loop.
For each iteration of the while loop, the decimalNum is divided by 8 and the remainder is multiplied by placeValue. This is added to the previous value of octalNum. Also decimalNum is divided by 8 and the quotient is stored back. placeValue is multiplied by 10.
A code snippet that demonstrates this is as follows.
while (decimalNum != 0) {
   octalNum += (decimalNum % 8) * placeValue;
   decimalNum /= 8;
   placeValue *= 10;
}
After the Octal value i.e octalNum is ovbtained, it is displayed. This is given below −
cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl;
In the function OctalToDecimal, in each iteration of the while loop octalNum is divided by 8 and the remainder is multiplied by 8 raised to power. This is added to the previous value of decimalNum. Power is incremented by 1 and octalNum is divided by 10. This is demonstrated as follows.
while(octalNum != 0) {
   decimalNum += (octalNum%10) * pow(8,power);
   ++power;
   octalNum/=10;
}
After the value of decimalNum is found, it is displayed. This is seen as follows.
cout<<"Decimal form of octal number "<<oNo<<" is "<<decimalNum<<endl;
The main() function only contains the function calls to DecimalToOctal() and OctalToDecimal() with the required values. This is demonstrated by the following code snippet.
DecimalToOctal(20);
OctalToDecimal(32);
Bootstrap Form select

A select is used when you want to allow the user to pick from multiple options, but by default, it only allows one.
Use <select> for list options with which the user is familiar, such as states or numbers.
Use multiple = "multiple" to allow the users to select more than one option.
You can try to run the following code to implement Bootstrap form select
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content="width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form role = "form">
         <div class = "form-group">
            <label for = "name">Country</label>
            <select class = "form-control">
               <option>India</option>
               <option>Australia</option>
               <option>US</option>
            </select>
         </div>
      </form>
   </body>
</html>
Java Math nextAfter() method with Example - GeeksforGeeks

15 Apr, 2018
The java.lang.Math.nextAfter() returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments are equal then the second argument is returned.
Syntax :// datatype can be float or double.public static dataType nextAfter(dataType st, dataType dir)
Parameter :st :starting floating-point value.dir :value indicating which of start’s neighbors or start should be returned.
Return :This method returns the floating-point number adjacent to start in the direction of direction.
Note :
If one of the arguments is NaN, Output is NaN
If both arguments are signed zeros, direction is returned unchanged(as implied by the requirement of returning the second argument if the arguments compare as equal).
If start is Double.MIN_VALUE or Float.MIN_VALUE and direction has a value such that the result should have a smaller magnitude, then a zero with the same sign as start is returned.
If start is infinite and direction has a value such that the result should have a smaller magnitude, Double.MAX_VALUE or Float.MAX_VALUE with the same sign as start is returned.
If start is equal to Double.MAX_VALUE or Float.MAX_VALUE and direction has a value such that the result should have a larger magnitude, an infinity with same sign as start is returned.
Example 1 :To show working of java.lang.Math.nextAfter() method.
// Java program to demonstrate working// of java.lang.Math.nextAfter() methodimport java.lang.Math;  class GfG {      // driver code    public static void main(String args[])    {        double a = 0.0 / 0;        double b = 12.2;          // Input a is NaN, Output NaN        System.out.println(Math.nextAfter(a, b));          double c = 0.0;        double d = 0.0;          // Both Input are signed zeros, Output zero        System.out.println(Math.nextAfter(c, d));          float e = Float.MIN_VALUE;        float f = 12.2f;          System.out.println(Math.nextAfter(e, f));          float g = 1.0f / 0f;        float h = 1.0f;          System.out.println(Math.nextAfter(g, h));          double i = Double.MAX_VALUE;        double j = 12344.2;          System.out.println(Math.nextAfter(i, j));    }}
Output:
NaN
0.0
2.8E-45
3.4028235E38
1.7976931348623155E308

java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Stream In Java
Different ways of Reading a text file in Java
Internal Working of HashMap in Java
Iterators in Java
Java Programming Examples
Comparator Interface in Java with Examples
Strings in Java
Difference between Work area, global structure and internal table in SAP ABAP

Internal tables let you read data from a fixed structure and stores it in-memory (working memory) in ABAP. The data is stored in a sequential manner in memory. They are basically equivalent to arrays but dynamic in nature. Since they are dynamic in nature, memory management is already taken care by ABAP. Usually, data read from database tables are stored in the internal table to exactly replicate the database tables. 
Work Area refers to a single row of a fixed structure. It is basically used for storing temporary data. It is commonly used while iterating over a loop.
For ex. If you need to loop over an internal table, you can store the current record in a work area.
---------------
LOOP AT INTAB INTO WORKAREA.
ENDLOOP.
--------------
Here INTAB refers to an internal table and WORKAREA refers to a work area. 
Global Structure as the name reflects is global in nature. It is a structure which is created for an info provider and then can be reused across all queries for the same info provider.
PL/SQL - IF-THEN-ELSIF Statement

The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
It's ELSIF, not ELSEIF.
It's ELSIF, not ELSEIF.
An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE.
An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE.
Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN  
   S1; -- Executes when the boolean expression 1 is true  
ELSIF( boolean_expression 2) THEN 
   S2;  -- Executes when the boolean expression 2 is true  
ELSIF( boolean_expression 3) THEN 
   S3; -- Executes when the boolean expression 3 is true  
ELSE  
   S4; -- executes when the none of the above condition is true  
END IF; 

DECLARE 
   a number(3) := 100; 
BEGIN 
   IF ( a = 10 ) THEN 
      dbms_output.put_line('Value of a is 10' ); 
   ELSIF ( a = 20 ) THEN 
      dbms_output.put_line('Value of a is 20' ); 
   ELSIF ( a = 30 ) THEN 
      dbms_output.put_line('Value of a is 30' ); 
   ELSE 
       dbms_output.put_line('None of the values is matching'); 
   END IF; 
   dbms_output.put_line('Exact value of a is: '|| a );  
END; 
/ 
When the above code is executed at the SQL prompt, it produces the following result −
None of the values is matching 
Exact value of a is: 100  

PL/SQL procedure successfully completed. 

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML iframe
How to combine lists in R?

When we have multiple lists but they have similar type of data then we might want to combine or merge those lists. This will be helpful to use because we can perform the calculations using one list name instead of applying them on multiple ones. We can combine multiple lists with the help of mapply function.
Consider the below lists −
> List1<-list(letters[1:5],1:5,5:1,25,c("A","B","C","D"))
> List1
[[1]]
  [1] "a" "b" "c" "d" "e"
[[2]]
  [1]  1   2   3   4   5
[[3]]
  [1]  5   4   3   2   1
[[4]]
  [1] 25
[[5]]
  [1] "A" "B" "C" "D"
> List2<-list(letters[6:10],6:10,c(25,16,9,4,1),36,c("Andy","Boston","Caroline","Dinesh"))
> List2
[[1]]
  [1] "f" "g" "h" "i" "j"
[[2]]
  [1]  6   7   8   9  10
[[3]]
  [1] 25  16   9   4   1
[[4]]
  [1] 36
[[5]]
  [1] "Andy" "Boston" "Caroline" "Dinesh"
> mapply(c, List1, List2, SIMPLIFY=FALSE)
[[1]]
  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
[[2]]
  [1]  1   2   3   4   5   6   7   8   9  10
[[3]]
  [1]  5   4   3   2   1  25  16   9   4   1
[[4]]
[1] 25 36
[[5]]
[1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh"
Now suppose, we have one more list that is List3 then it can be combined in the same way as shown below −
> List3<-list(letters[11:15],11:15,c(6,7,8,9,10),49,c("Aaron","Betty","Corie","Donald"))
> List3
[[1]]
  [1] "k" "l" "m" "n" "o"
[[2]]
  [1] 11  12  13  14  15
[[3]]
  [1]  6  7    8   9  10
[[4]]
  [1] 49
[[5]]
  [1] "Aaron" "Betty" "Corie" "Donald"
> mapply(c, List1, List2, List3, SIMPLIFY=FALSE)
[[1]]
  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o"
[[2]]
  [1]  1   2  3    4   5   6   7   8   9   10  11  12  13  14  15
[[3]]
  [1]  5   4  3    2   1  25  16   9   4    1   6   7   8   9  10
[[4]]
  [1] 25  36  49
[[5]]
[1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh" "Aaron" "Betty" "Corie" "Donald"
Second Minimum Node In a Binary Tree in C++

Suppose there is a non-empty special binary tree with some non-negative value, here each
node in this tree has exactly two or zero children. If the node has two children, then this node's value is the smaller value among its two children. In other words, we can say that [root.val = minimum of root.left.val, root.right.val]. If we have such binary tree, we have to find the second minimum value in the set made of all the nodes' value in the whole tree. If there is no such element, then return -1 instead.
So, if the input is like
then the output will be 5. The smallest value is 2, the second smallest value is 5.
To solve this, we will follow these steps −
Define a function TraverseNodes(), this will take node, min, nextMin,
if node is null, then −return
return
if val of node > min, then −if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node
if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node
nextMin := val of node
TraverseNodes(left of node, min, nextMin)
TraverseNodes(right of node, min, nextMin)
From the main method do the following −
min := value of root when root is not null, otherwise -1
nextMin := -1
TraverseNodes(root, min, nextMin)
return nextMin
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = NULL;
         right = NULL;
   }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
         }else{
            q.push(temp->left);
         }
         if(!temp->right){
            if(val != NULL)
               temp->right = new TreeNode(val);
            else
               temp->right = new TreeNode(0);
            return;
      }else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
public:
   int findSecondMinimumValue(TreeNode* root) {
      int min = (root && root->val != 0) ? root->val : -1;
      int nextMin = -1;
      TraverseNodes(root, min, nextMin);
      return nextMin;
   }
   void TraverseNodes(TreeNode* node, int min, int& nextMin) {
      if (!node || node->val == 0) {
         return;
      }
      if (node->val > min) {
         if (nextMin == -1 || node->val < nextMin) {
            nextMin = node->val;
         }
      }
      TraverseNodes(node->left, min, nextMin);
      TraverseNodes(node->right, min, nextMin);
   }
};
main(){
   Solution ob;
   vector<int> v = {2,2,5,NULL,NULL,5,7};
   TreeNode *root = make_tree(v);
   cout << (ob.findSecondMinimumValue(root));
}
{2,2,5,NULL,NULL,5,7}
5
java.util.zip.Inflater.read() Method Example

The java.util.zip.InflaterInputStream.read() method reads a byte of uncompressed data. This method will block until enough input is available for decompression.
Following is the declaration for java.util.zip.InflaterInputStream.read() method.
public int read() throws IOException

the byte read, or -1 if end of compressed input is reached.
IOException  − if an I/O error occurs.
IOException  − if an I/O error occurs.
The following example shows the usage of java.util.zip.InflaterInputStream.read() method.
package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.mark(0);  
      }
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.reset();  
      }
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}
Let us compile and run the above program, this will produce the following result −
Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

 Print
 Add Notes
 Bookmark this page
Add Text Inside the Plot in Matplotlib - GeeksforGeeks

03 Jan, 2021
In this article, We are going to see how to add text inside the plot in Matplotlib. The matplotlib.pyplot.text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes. It also supports mathematical expressions.
Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Parameters:
where x, y – coordinates
s – text to be added inside the plot(string)
fontdict – optional parameter. It overrides the default text properties
**kwargs – text properties
Example 1: Adding mathematical equations inside the plot.
Python3
import matplotlib.pyplot as pltimport numpy as np  x = np.arange(-10, 10, 0.01)y = x**2  #adding text inside the plotplt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22)  plt.plot(x, y, c='g')  plt.xlabel("X-axis", fontsize = 15)plt.ylabel("Y-axis",fontsize = 15)  plt.show()
Output:
Example 2: Adding rectangular box around the text by using the keyword ‘bbox’. bbox is a dictionary of Rectangle properties.
Python3
import matplotlib.pyplot as pltimport numpy as np  x = np.arange(-10, 10, 0.01)y = x**2  plt.xlabel("X-axis", fontsize = 15)plt.ylabel("Y-axis",fontsize = 15)  #Adding text inside a rectangular box by using the keyword 'bbox'plt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22,          bbox = dict(facecolor = 'red', alpha = 0.5))  plt.plot(x, y, c = 'g')  plt.show()
Output:
Example 3: Adding the text “Sine wave” inside the plot.
Python3
import matplotlib.pyplot as pltimport numpy as np  x = np.arange(0, 10, 0.1)y = np.sin(x)  plt.plot(x,y)  plt.text(3.5, 0.9, 'Sine wave', fontsize = 23)  plt.xlabel('X-axis', fontsize = 15)plt.ylabel('Y-axis', fontsize = 15)  #plt.grid(True, which='both')plt.show()
Output: 
Example 4: Using annotation along with text inside plot
Python3
import matplotlib.pyplot as pltimport numpy as np  x = ['Rani', 'Meena', 'Raju', 'Jhansi', 'Ram']y = [5, 7, 9, 2, 6]  plt.bar(x,y)  plt.text(3, 7, 'Student Marks',          fontsize = 18, color = 'g')  plt.xlabel('Students', fontsize = 15)plt.ylabel('Marks', fontsize = 15)  plt.annotate('Highest scored', xy = (2.4, 8),              fontsize = 16, xytext = (3, 9),              arrowprops = dict(facecolor = 'red'),             color = 'g')  plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
Python | Find Mean of a List of Numpy Array - GeeksforGeeks

14 Mar, 2019
Given a list of Numpy array, the task is to find mean of every numpy array. Let’s see a few methods we can do the task.
Method #1: Using np.mean()
# Python code to find mean of every numpy array in list  # Importing moduleimport numpy as np  # List InitializationInput = [np.array([1, 2, 3]),         np.array([4, 5, 6]),         np.array([7, 8, 9])]  # Output list initializationOutput = []  # using np.mean()for i in range(len(Input)):   Output.append(np.mean(Input[i]))  # Printing outputprint(Output)
[2.0, 5.0, 8.0]

 Method #2: Using np.average()
# Python code to find mean of # every numpy array in list  # Importing moduleimport numpy as np  # List InitializationInput = [np.array([11, 12, 13]),         np.array([14, 15, 16]),         np.array([17, 18, 19])]  # Output list initializationOutput = []  # using np.mean()for i in range(len(Input)):   Output.append(np.average(Input[i]))  # Printing outputprint(Output)
[12.0, 15.0, 18.0]

Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python