code-rag-bench/online-tutorials huggingface dataset:
Python – Convert Snake case to Pascal case

28 Apr, 2020
Sometimes, while working with Python Strings, we have problem in which we need to perform a case conversion of String. This a very common problem. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.
Input : geeks_for_geeksOutput : GeeksforGeeks
Input : left_indexOutput : leftIndex
Method #1 : Using title() + replace()This task can be solved using combination of above functions. In this, we first convert the underscore to empty string and then title case each word.
# Python3 code to demonstrate working of # Convert Snake case to Pascal case# Using title() + replace()  # initializing stringtest_str = 'geeksforgeeks_is_best'  # printing original stringprint("The original string is : " + test_str)  # Convert Snake case to Pascal case# Using title() + replace()res = test_str.replace("_", " ").title().replace(" ", "")  # printing result print("The String after changing case : " + str(res)) 
The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

 
Method #2 : Using capwords()The task of performing title case is performed using capwords() in this method.
# Python3 code to demonstrate working of # Convert Snake case to Pascal case# Using capwords()import string  # initializing stringtest_str = 'geeksforgeeks_is_best'  # printing original stringprint("The original string is : " + test_str)  # Convert Snake case to Pascal case# Using capwords()res = string.capwords(test_str.replace("_", " ")).replace(" ", "")  # printing result print("The String after changing case : " + str(res)) 
The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
JavaScript | Optional chaining

10 May, 2021
The optional chaining ‘?.’ is an error-proof way to access nested object properties, even if an intermediate property doesn’t exist. It was recently introduced by ECMA International, Technical Committee 39 – ECMAScript which was authored by Claude Pache, Gabriel Isenberg, Daniel Rosenwasser, Dustin Savery. It works similar to Chaining ‘.’ except that it does not report the error, instead it returns a value which is undefined. It also works with function call when we try to make a call to a method which may not exist.
When we want to check a value of the property which is deep inside a tree-like structure, we often have to perform check whether intermediate nodes exist.
let Value = user.dog && user.dog.name;
The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves and/or assigning intermediate results in temporary variables:
let Value = user.dog?.name;
Syntax: 
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
Note: If this code gives any error try to run it on online JavaScript editor.
Example: Optional Chaining with Object
Javascript
const user = {  dog: {    name: "Alex"  }}; console.log(user.cat?.name); //undefinedconsole.log(user.dog?.name); //Alexconsole.log(user.cat.name);
Output:
Example: Optional Chaining with Function Call
Javascript
let user1 = () => console.log("Alex");let user2 = {  dog(){    console.log("I am Alex");  }}let user3 = {}; user1?.();       // Alexuser2.dog?.();   // I am Alexuser3.dog();     // ERROR - Uncaught TypeError:                 // user3.dog is not a function.user3.dog?.();   // Will not generate any error.
Output:
abhishekkharmale
Vijay Sirra
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
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 insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Perl my Function

This function declares the variables in LIST to be lexically scoped within the enclosing block. If more than one variable is specified, all variables must be enclosed in parentheses.
Following is the simple syntax for this function −
my LIST

This function does not return any value.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

my $string = "We are the world";
print "$string\n";
myfunction();
print "$string\n";

sub myfunction {
   my $string = "We are the function";
   print "$string\n";
   mysub();
}
sub mysub {
   print "$string\n";
}
When above code is executed, it produces the following result −
We are the world
We are the function
We are the world
We are the world
References in C++ - GeeksQuiz

10 Mar, 2018
int f(int &x, int c) {
   c  = c - 1;
   if (c == 0) return 1;
   x = x + 1;
   return f(x, c) * x;
} 
#include<iostream>
using namespace std;

int main()
{
  const int x = 10;
  const int& ref = x;

  cout << ref;
  return 0;
}
x = 20
ref = 30
x = 20
ref = 20
x = 10
ref = 30
x = 30
ref = 30
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022
Overloading stream insertion (<<) and extraction (>>) operators in C++

C++ is able to input and output the built-in data types using the stream extraction operator >> and
the stream insertion operator <<. The stream insertion and stream extraction operators also can be
overloaded to perform input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class because it would be
called without creating an object.
Following example explains how extraction operator >> and insertion operator <<.
#include <iostream>
using namespace std;
class Distance {
   private:
   int feet; // 0 to infinite
   int inches; // 0 to 12
   public:
   // required constructors
   Distance() {
      feet = 0;
      inches = 0;
   }
   Distance(int f, int i) {
      feet = f;
      inches = i;
   }
   friend ostream &operator<<( ostream &output, const Distance &D ) {
      output << "F : " << D.feet << " I : " << D.inches;
      return output;
   }
   friend istream &operator>>( istream &input, Distance &D ) {
      input >> D.feet >> D.inches;
      return input;
   }
};
int main() {
   Distance D1(11, 10), D2(5, 11), D3;
   cout << "Enter the value of object : " << endl;
   cin >> D3;
   cout << "First Distance : " << D1 << endl;
   cout << "Second Distance :" << D2 << endl;
   cout << "Third Distance :" << D3 << endl;
   return 0;
}
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
How to add a grid on a figure in Matplotlib ?

02 Jul, 2021
Matplotlib library is widely used for plotting graphs. In many graphs, we require to have grid to improve readability. Grids are created by using grid() function in pyplot sub library.
grid() : Configure the grid lines.
Syntax:
matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs)
Parameters:
b: bool or None, optional parameter for Whether to show the grid lines.
which : {‘major’, ‘minor’, ‘both’}, optional. It specifies the grid lines to apply the changes on.
axis : {‘both’, ‘x’, ‘y’}, optional. The axis to apply the changes on.
**kwargs : Optional. Specify Line properties such as color, line style, line width, etc.
Steps:
Plot a graph
Specify grid using pyplot.grid() method.
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy # Define x and yx = numpy.arange(0, 1, 0.1)y = numpy.power(x, 2) # Plot graphplt.scatter(x, y) # Define grid with axis='y'plt.grid(axis='y')plt.show() # Define a figurefig = plt.figure()ax = fig.gca() # Set labels on x and y axis of figureax.set_xticks(numpy.arange(0, 1, 0.1))ax.set_yticks(numpy.arange(0, 1, 0.1)) # Plot the graphax.scatter(x, y) # Specify default grid on figureax.grid()ax.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np # Define x and yx = np.arange(-5, 5, 0.01)y = np.sin(2*np.pi*x) # Plot line graphplt.plot(x, y) # Specify grid with line attributesplt.grid(color='r', linestyle='--') # Display the plotplt.show()
Output:
sagartomar9927
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.exitCode Property

01 Apr, 2021
 There are two ways that are generally used  to terminate a Node.js program which are using process.exit() or process.exitCode variable. In this post, we have discussed about process.exitCode variable. It is an integer that represents the code passed to the process.exit() function or when the process exits on its own. It allows the Node.js program to exit naturally and avoids the Node program to do additional work around event loop scheduling, and it is much safer than passing exitcode to process.exit().
Syntax
  process.exitCode = value
 Here value means exitcode value.
Example 1: One way is to pass exitcode value to process.exit() function. Exit code 1 is used when unhandled fatal exceptions occur that was not handled whereas Exit code 0 is used to terminate when no more async operations are happening.
Javascript
const express = require('express')const app = express()  var a=10;var b=20;  if(a==10){  console.log(a)  process.exitCode(1);}  console.log(b);      app.listen(3000, () => console.log('Server ready'))
Output:
Example 2: Another way is to set  process.exitCode value which will allows the Node.js program to exit on its own without leaving further calls for the future.
Javascript
const express = require('express')const app = express()  var a=10;var b=20;  if(a==10){  console.log(a)  process.exitCode=0;}  console.log(b);  app.listen(3000, () => console.log('Server ready'))
Output:
Node.js-process-module
NodeJS-Process
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Python Program to Print all Integers that are not Divisible by Either 2 or 3 and Lie between 1 and 50

When it is required to print all the elements which can’t be divided by 2 or 3 and lie between 1 and 50, the constraints are mentioned in the form of a ‘while’ loop and ‘if’ condition.
Below is a demonstration of the same −
 Live Demo
print("Integers not divisible by 2 and 3, that lie between 1 and 50 are : ")
n = 1
while n <= 51:
   if n % 2 != 0 and n % 3 != 0:
      print(n)
   n = n+1
Integers not divisible by 2 and 3, that lie between 1 and 50 are :
1
5
7
11
13
17
19
23
25
29
31
35
37
41
43
47
49
The value of n is assigned to 1.
The value of n is assigned to 1.
A while loop runs until this ‘n’ is not greater than 51,
A while loop runs until this ‘n’ is not greater than 51,
It checks to see if the number is divisible by 2 or 3 or not.
It checks to see if the number is divisible by 2 or 3 or not.
If it is not divisible, the number is displayed on the console.
If it is not divisible, the number is displayed on the console.
After every display, it is incremented.
After every display, it is incremented.
Equate two list index elements in Python

During data manipulation with Python , we may need to bring two lists together and equate the elements in each of them pair wise. Which means the element at index 0 from list 1 will be equated with element from index 0 of list2 and so on.
The tuple function will be leveraged to take elements form each list in sequence and matching them up. We first store the result in a temp string which has the pattern in which the output of matching up of the values form lists will be displayed.
 Live Demo
listA = ['day1', 'day2', 'day3']
listB = ['Mon', 'Tue', 'Fri']

# Given lists
print("Given list A is : " ,listA)
print("Given list B is : " ,listB)


# Pairing list elements
temp = len(listA) * '% s = %% s, '
res = temp % tuple(listA) % tuple(listB)

# printing result
print("Paired lists : " , res)
Running the above code gives us the following result −
Given list A is : ['day1', 'day2', 'day3']
Given list B is : ['Mon', 'Tue', 'Fri']
Paired lists : day1 = Mon, day2 = Tue, day3 = Fri,
The zip function can pair up the elements form lists in sequence and the join function will apply the required pattern we need to apply to the pairs.
 Live Demo
listA = ['day1', 'day2', 'day3']
listB = ['Mon', 'Tue', 'Fri']

# Given lists
print("Given list A is : " ,listA)
print("Given list B is : " ,listB)


# Pairing list elements
res= ', '.join('% s = % s' % i for i in zip(listA, listB))

# printing result
print("Paired lists : " , res)
Running the above code gives us the following result −
Given list A is : ['day1', 'day2', 'day3']
Given list B is : ['Mon', 'Tue', 'Fri']
Paired lists : day1 = Mon, day2 = Tue, day3 = Fri
What is strtok() function in C language?

strtok() function is a part of the <string.h> header file #include <string.h>
The syntax of strtok() function is as follows −
char* strtok(char* string, const char* limiter);
Input string string and a delimiter character limiter. strtok() will divide the string into tokens based on the delimited character.
We can expect a list of strings from strtok(). But, the function returns a single string because after calling strtok(input, limiter), it will returns the first token.
But we have to keep calling the function again and again on a NULL input string, until we get NULL!
Generally, we used to keep calling strtok(NULL, delim) until it returns NULL.
Following is the C program for strtok() function −
 Live Demo
#include <stdio.h>
#include <string.h>
int main() {
   char input_string[] = "Hello Tutorials Point!";
   char token_list[20][20];
   char* token = strtok(input_string, " ");
   int num_tokens = 0; // Index to token list. We will append to the list
   while (token != NULL) {
      strcpy(token_list[num_tokens], token); // Copy to token list
      num_tokens++;
      token = strtok(NULL, " "); // Get the next token. Notice that input=NULL now!
   }
   // Print the list of tokens
   printf("Token List:\n");
   for (int i=0; i < num_tokens; i++) {
      printf("%s\n", token_list[i]);
   }
   return 0;
}
When the above program is executed, it produces the following result −
Token List:
Hello
Tutorials
Point!
Input string is “Hello Tutorials Point”, and we are trying to tokenize it by spaces.
We get first token by using strtok(input, " "). Here the double quotes are delimiter and are a single character string!
Afterwards, we keep getting tokens by using strtok(NULL, " ") and loop until we get NULL from strtok().
Write a Program to Find the Maximum Depth or Height of a Tree in C++

In this problem, we are given a binary tree. Our task is to write a program to find the maximum depth or height of the given tree.
Let’s take an example to understand the problem,
The height of the tree is 3.
To find the maximum height of a tree, we will check the heights of its left and right subtree and add one to the maximum of both. This is a recursive process that will continue this the last node is of the tree is found and one is added progressively to find the height of the sub-trees.
Finding the height of tree i.e. height(3) = max(height(5),height(7)) + 1.
For this, we will calculate the height of nodes with values 5 and 7.
height(5) = max(height(1),height(9)) + 1 and
height(7) = 1, it has no subtree that can be formed.
Similarly, height(1) = height(9) = 1
height(5) = max(1,1) +1 = 2
height(3) = max(height(5),height(7)) + 1 = max(2,1) + 1 = 3.
So the height becomes 3.
Program to illustrate the solution,
 Live Demo
#include <iostream>
using namespace std;
class node {
   public:
   int data;
   node* left;
   node* right;
};
int height(node* node) {
   if (node == NULL)
     return 0;
   else {
      int lDepth = height(node->left);
      int rDepth = height(node->right);
      if (lDepth > rDepth)
         return(lDepth + 1);
      else return(rDepth + 1);
   }
}
node* insertNode(int data) {
   node* Node = new node();
   Node->data = data;
   Node->left = NULL;
   Node->right = NULL;
   return(Node);
}
int main() {
   node *root = insertNode(4);
   root->left = insertNode(5);
   root->right = insertNode(0);
   root->left->left = insertNode(1);
   root->left->right = insertNode(9);
   cout<<"The height of the given binary tree is "<<height(root);
   return 0;
}
The height of the given binary tree is 3
How to check whether a checkbox is checked with JavaScript?

To check whether a checkbox is checked with JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<h1>Displaying textBox when a checkbox is checked</h1>
Checkbox: <input type="checkbox" class="check" onclick="checkFunction()" />
<h2 class="textBox" style="display:none">Checkbox is checked!!!</h2>
<script>
   document.querySelector(".check").addEventListener("click", checkFunction);
   function checkFunction() {
      var checkBox = document.querySelector(".check");
      var textBox = document.querySelector(".textBox");
      if (checkBox.checked == true) {
         textBox.style.display = "block";
      } else {
         textBox.style.display = "none";
      }
   }
</script>
</body>
</html>
This will produce the following output −
On clicking the checkbox −
Box plot visualization with Pandas and Seaborn - GeeksforGeeks

08 Sep, 2021
Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detect the outlier in data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes a sample data using 25th, 50th and 75th percentiles. These percentiles are also known as the lower quartile, median and upper quartile.
A box plot consist of 5 things.
Minimum
First Quartile or 25%
Median (Second Quartile) or 50%
Third Quartile or 75%
Maximum
To download the dataset used, click here.
Draw the box plot with Pandas:
One way to plot boxplot using pandas dataframe is to use boxplot() function that is part of pandas library.
# import the required library import numpy as np import pandas as pd import matplotlib.pyplot as plt % matplotlib inline    # load the datasetdf = pd.read_csv("tips.csv")  # display 5 rows of datasetdf.head()   
Boxplot of days with respect total_bill.
df.boxplot(by ='day', column =['total_bill'], grid = False)
 Boxplot of size with respect tip.
df.boxplot(by ='size', column =['tip'], grid = False)
 Draw the boxplot using seaborn library:
Syntax :seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
Parameters:x = feature of datasety = feature of datasethue = feature of datasetdata = dataframe or full datasetcolor = color name
Let’s see how to create the box plot through seaborn library.
Information about “tips” dataset.
# load the datasettips = sns.load_dataset('tips')  tips.head()
Boxplot of days with respect total_bill.
# Draw a vertical boxplot grouped # by a categorical variable:sns.set_style("whitegrid")  sns.boxplot(x = 'day', y = 'total_bill', data = tips)
Bottom black horizontal line of blue box plot is minimum value
First black horizontal line of rectangle shape of blue box plot is First quartile or 25%
Second black horizontal line of rectangle shape of blue box plot is Second quartile or 50% or median.
Third black horizontal line of rectangle shape of blue box plot is third quartile or 75%
Top black horizontal line of rectangle shape of blue box plot is maximum value.
Small diamond shape of blue box plot is outlier data or erroneous data.
sweetyty
Python pandas-plotting
Python-matplotlib
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
What does reload() function do in Python?

The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax "import moduleName". It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again. For example,
>>> import mymodule
>>> # Edited mymodule and want to reload it in this script
>>> reload(mymodule)
Note that the moduleName is the actual name of the module, not a string containing its name. In Python 3, reload was moved from builtins to imp. So to use reload in Python 3, you'd have to write imp.reload(moduleName) and not just reload(moduleName).
Tryit Editor v3.7 - Show Java

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);

    System.out.println("Enter name, age and salary:");

    // String input
    String name = myObj.nextLine();

    // Numerical input
    int age = myObj.nextInt();
    double salary = myObj.nextDouble();

    // Output input by user
    System.out.println("Name: " + name); 
    System.out.println("Age: " + age); 
    System.out.println("Salary: " + salary);
How to read PDF file using PHP ? - GeeksforGeeks

14 Jul, 2021
In this article, we will learn how you can show PDF file content on a browser using PHP.
We have to include an external PHP file named “class.pdf2text.php“. Include it in the required web page using PHP. Create an HTML form, in which we can choose a PDF file from your computer and also check whether its file extension is PDF or not.
Project Structure: Create a folder for your project and add class.pdf2text.php and create a new index.php file.
FILE structure
Example:
index.php
<?php   require('class.pdf2text.php');extract($_POST);if(isset($readpdf)){          if($_FILES['file']['type']=="application/pdf") {        $a = new PDF2Text();        $a->setFilename($_FILES['file']['tmp_name']);         $a->decodePDF();        echo $a->output();     }           else {        echo "<p style='color:red;text-align:center'>            Wrong file format</p>";    }}       ?>  <html>  <head>    <title>Read pdf php</title></head>  <body>    <form method="post" enctype="multipart/form-data">        Choose Your File        <input type="file" name="file" />        <br>        <input type="submit" value="Read PDF" name="readpdf" />    </form></body>  </html>
Output: The following output is in video format for the above.
read PDF file
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to generate PDF file using PHP ?
How to create admin login page using PHP?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Get the first element of array in JavaScript

You can use simple for loop along with some if else condition to get the array’s first element in
JavaScript.
The logic is that, first of all check the array length is greater than 1 or not if the length is not
equal to 1 that means there is no element in the array. So, go to the else condition and set the
value undefined and print any message at the console. If there is an element in an array, set the
first index value to any variable and terminate the loop with the help of break and print the
message at the console.
var studentDetails=
[
   {
      "firstName":"John"
   },
   {
      "firstName":"David"
   },
   {
      "firstName":"Bob"
   },
   {
      "firstName":"Mike"
   },
   {
      "firstName":"Carol"
   }
]
var firstObjectValue = "";
if(studentDetails.length > 1){
   for(var index=0;index< studentDetails.length;index++){
      firstObjectValue=studentDetails[index].firstName;
      break;
   }
} else {
   firstObjectValue=undefined;
}
if(firstObjectValue!=undefined)
   console.log(firstObjectValue);
else
console.log("There is no element in the array");
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo184.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo184.js
John
PHP | imagewebp() Function - GeeksforGeeks

19 Feb, 2020
The imagewebp() function is an inbuilt function in PHP which is used to display image to browser or file. The main use of this function is to view an image in the browser, convert any other image type to WebP and alter the quality of the image.Syntax: 
bool imagewebp( resource $image, int $to, int $quality)

Parameters: This function accepts three parameters as mentioned above and described below:  
$image: It specifies the image resource to work on.
$to (Optional): It specifies the path to save the file to.
$quality (Optional): It specifies the quality of the image.
Return Value: This function returns TRUE on success or FALSE on error.Below examples illustrate the imagewebp() function in PHP:Example 1: In this example we will be viewing an image in browser.  
php
<?php    // Load an image from local webp file// Images can be converted into webp // using imagewebp() function or other// online convertors$im = imagecreatefromwebp('./geeksforgeeks.webp');  // View the loaded image in browser// using imagewebp() functionheader('Content-type: image/webp');  imagewebp($im);imagedestroy($im);?>
Output:  
Example 2: In this example we will convert PNG into WEBP.  
php
<?php    // Load an image from local webp file// Images can be converted into webp // using imagewebp() function or other// online convertors$im = imagecreatefromwebp('./geeksforgeeks.webp');  // Convert the image into webp// using imagewebp() functionimagewebp($im, 'converted.webp');imagedestroy($im);?>
Output: 
This will save the WEBP version of image in the same folder where your PHP script is.

Program 3: In this example we will alter the image quality.  
php
<?php  // Load an image from local webp file// Images can be converted into webp // using imagewebp() function or other// online convertors$im = imagecreatefromwebp('./geeksforgeeks.webp');  // Convert the image into webp using imagewebp()// function and view in the browserheader('Content-type: image/webp');imagewebp($im, null, 0);imagedestroy($im);?>
Output:  
Reference:  https://www.php.net/manual/en/function.imagewebp.php
PHP-function
PHP-image-functions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Integer Equals() method in Java

The Equals() method compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.
Let us first set Integer object.
Integer val1 = new Integer(30);
Integer val2 = new Integer(60);
Integer val3 = new Integer(55);
Integer val4 = new Integer(30);
Now let us check their equality using the Equals() method.
val1.equals(val2);
In the same way, check it for different Integers.
Let us see the complete example.
 Live Demo
import java.util.Random;
public class Demo {
   public static void main( String args[] ) {
      Integer val1 = new Integer(30);
      Integer val2 = new Integer(60);
      Integer val3 = new Integer(55);
      Integer val4 = new Integer(30);
      System.out.println("Integer 1 = "+val1);
      System.out.println("Integer 2 = "+val2);
      System.out.println("Integer 3 = "+val3);
      System.out.println("Integer 4 = "+val4);
      System.out.println(val1.equals(val2));
      System.out.println(val1.equals(val3));
      System.out.println(val1.equals(val4));
   }
}
Integer 1 = 30
Integer 2 = 60
Integer 3 = 55
Integer 4 = 30
false
false
true
TIKA - Extracting PDF

Given below is the program to extract content and metadata from a PDF.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class PdfParse {

   public static void main(final String[] args) throws IOException,TikaException {

      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("Example.pdf"));
      ParseContext pcontext = new ParseContext();
      
      //parsing the document using PDF parser
      PDFParser pdfparser = new PDFParser(); 
      pdfparser.parse(inputstream, handler, metadata,pcontext);
      
      //getting the content of the document
      System.out.println("Contents of the PDF :" + handler.toString());
      
      //getting metadata of the document
      System.out.println("Metadata of the PDF:");
      String[] metadataNames = metadata.names();
      
      for(String name : metadataNames) {
         System.out.println(name+ " : " + metadata.get(name));
      }
   }
}
Save the above code as PdfParse.java, and compile it from the command prompt by using the following commands −
javac PdfParse.java
java PdfParse

Below give is the snapshot of example.pdf
The PDF we are passing has the following properties −
After compiling the program, you will get the output as shown below.
Output −
Contents of the PDF:

Apache Tika is a framework for content type detection and content extraction 
which was designed by Apache software foundation. It detects and extracts metadata 
and structured text content from different types of documents such as spreadsheets, 
text documents, images or PDFs including audio or video input formats to certain extent.

Metadata of the PDF:

dcterms:modified :     2014-09-28T12:31:16Z
meta:creation-date :     2014-09-28T12:31:16Z
meta:save-date :     2014-09-28T12:31:16Z
dc:creator :     Krishna Kasyap
pdf:PDFVersion :     1.5
Last-Modified :     2014-09-28T12:31:16Z
Author :     Krishna Kasyap
dcterms:created :     2014-09-28T12:31:16Z
date :     2014-09-28T12:31:16Z
modified :     2014-09-28T12:31:16Z
creator :     Krishna Kasyap
xmpTPg:NPages :     1
Creation-Date :     2014-09-28T12:31:16Z
pdf:encrypted :     false
meta:author :     Krishna Kasyap
created :     Sun Sep 28 05:31:16 PDT 2014
dc:format :     application/pdf; version = 1.5
producer :     Microsoft® Word 2013
Content-Type :     application/pdf
xmp:CreatorTool :     Microsoft® Word 2013
Last-Save-Date :     2014-09-28T12:31:16Z

 Print
 Add Notes
 Bookmark this page
Python | Logging Test Output to a File - GeeksforGeeks

12 Jun, 2019
Problem – Writing the results of running unit tests to a file instead of printed to standard output.
A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file.
Code #1 :
import unittestclass MyTest(unittest.TestCase):    ...if __name__ == '__main__':    unittest.main()
This makes the test file executable, and prints the results of running tests to standard output. To redirect this output, unwind the main() call a bit and write own main() function as shown in the code given below :
Code #2 :
import sys  def main(out = sys.stderr, verbosity = 2):    loader = unittest.TestLoader()      suite = loader.loadTestsFromModule(sys.modules[__name__])    unittest.TextTestRunner(out, verbosity = verbosity).run(suite)      if __name__ == '__main__':    with open('testing.out', 'w') as f:        main(f)
How it works :
The interesting thing about the code is not so much the task of getting test results redirected to a file, but the fact that doing so exposes some notable inner workings of the unittest module.
At a basic level, the unittest module works by first assembling a test suite.
This test suite consists of the different testing methods you defined. Once the suite has been assembled, the tests it contains are executed.
These two parts of unit testing are separate from each other. The unittest.TestLoader instance created in the solution is used to assemble a test suite.
The loadTestsFromModule() is one of several methods it defines to gather tests. In this case, it scans a module for TestCase classes and extracts test methods from them.
The loadTestsFromTestCase() method (not shown) can be used to pull test methods from an individual class that inherits from TestCase.
The TextTestRunner class is an example of a test runner class. The main purpose of this class is to execute the tests contained in a test suite. This class is the same test runner that sits behind the unittest.main() function.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to Reverse a String in PL/SQL using C++

Pl/SQL is a block-structured language that combines SQL's functionality with procedural commands. In this article, we will discuss a program in PL/SQL to reverse a given string for example −
Input : taerGsIdoG
Output : GodIsGreat
Explanation : reverse string of “taerGsIdoG” is “GodIsGreat”.

Input : LQS
Output : SQL
Explanation Reverse string of “LQS” is “SQL”.
First, you need to find the length of the given string.
Now you can traverse the line but in a reversed order.
Store each character in another string while traversing.
At last, you can print the reversed string.
DECLARE
   -- declaring variables to be used.
   input_string VARCHAR(50) := 'taerGsIdoG';
   length NUMBER;
   reversed_string VARCHAR(20);

BEGIN
   -- finding the length of the string.
   length := Length(input_string);

   -- traversing the string in reversed order.
   FOR i IN REVERSE 1.. length LOOP
   -- storing each character in reversed_string variable
   reversed_string := reversed_string || Substr(input_string, i, 1);
   END LOOP;

   dbms_output.Put_line(‘Reversed string : ' || reversed_string);
END;
Reversed string: GodIsGreat
In this article, we discuss a PL/SQL programming language that is very simple; it feels like using ordinary English to give the command to the system, which is a block-structured language. We also discussed a program to reverse a string in PL/SQL language. We hope you find this article helpful.
scanf() and fscanf() in C

The function scanf() is used to read formatted input from stdin in C language. It returns the whole number of characters written in it otherwise, returns a negative value.
Here is the syntax of scanf() in C language,
int scanf(const char *characters_set)
Here is an example of scanf() in C language,
 Live Demo
#include <stdio.h>
int main () {
   char s[20];
   printf("Enter a string : ");
   scanf("%s", s);
   printf("\nEntered string : %s\n", s);
   return(0);
}
Enter a string : Peter!
Entered string : Peter!
The function fscanf() is used to read the formatted input from the given stream in C language. It returns zero, if unsuccessful. Otherwise, it returns The input string, if successful.
Here is the syntax of fscanf() in C language,
int fscanf(FILE *stream_name, const char *set_of_characters)
Here is an example of fscanf() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main () {
   char str1[10];
   int year;
   FILE * fp;
   fp = fopen ("file.txt", "w+");
   fputs("This is demo text!", fp);
   rewind(fp);
   fscanf(fp, "%s", str1);
   printf("First word = \n%s\n", str1 );
   fclose(fp);
   return(0);
}
First word =
This
Accessing index and value in a Python list

When we use a Python list, will be required to access its elements at different positions. In this article we will see how to get the index of specific elements in a list.
The below program sources the index value of different elements in given list. We supply the value of the element as a parameter and the index function returns the index position of that element.
 Live Demo
listA = [11, 45,27,8,43]
# Print index of '45'
print("Index of 45: ",listA.index(45))
listB = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
# Print index of 'Wed'
print("Index of Wed: ",listB.index('Wed'))
Running the above code gives us the following result −
('Index of 45: ', 1)
('Index of Wed: ', 3)
In the below program we loo through each element of the list and apply a list function inner for loop to get the index.
 Live Demo
listA = [11, 45,27,8,43]
#Given list
print("Given list: ",listA)
# Print all index and values
print("Index and Values: ")
print ([list((i, listA[i])) for i in range(len(listA))])
Running the above code gives us the following result −
Given list: [11, 45, 27, 8, 43]
Index and Values:
[[0, 11], [1, 45], [2, 27], [3, 8], [4, 43]]
The enumerate function itself gives track of the index position along with the value of the elements in a list. So when we apply enumerate function to a list it gives both index and value as output.
 Live Demo
listA = [11, 45,27,8,43]
#Given list
print("Given list: ",listA)
# Print all index and values
print("Index and Values: ")
for index, value in enumerate(listA):
   print(index, value)
Running the above code gives us the following result −
Given list: [11, 45, 27, 8, 43]
Index and Values:
0 11
1 45
2 27
3 8
4 43
Python program to print all odd numbers in a range

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a range, we need to print all the odd numbers in the given range.
The brute-force approach is discussed below −
Here we apply a range-based for loop which provides all the integers available in the input interval.
After this, a check condition for odd numbers is applied to filter all the even numbers.
This approach takes O(n) + constant time of comparison.
Now let’s see the implementation below −
start, end = 10, 29
# iteration
for num in range(start, end + 1):
   # check
   if num % 2 != 0:
      print(num, end = " ")
11 13 15 17 19 21 23 25 27 29
All the variables and functions are declared in a global frame as shown in the figure below.
In this article, we learned about the approach to print odd numbers in the input range.
Create a list of tuples from given list having number and its cube in each tuple using Python

When it is required to create a list from a given list that have a number and its cube, the list comprehension can be used.
Below is the demonstration of the same −
 Live Demo
my_list = [32, 54, 47, 89]
print("The list is ")
print(my_list)

my_result = [(val, pow(val, 3)) for val in my_list]
print("The result is ")
print(my_result)
The list is
[32, 54, 47, 89]
The result is
[(32, 32768), (54, 157464), (47, 103823), (89, 704969)]
A list is defined, and is displayed on the console.
A list is defined, and is displayed on the console.
The list comprehension is used to iterate through the list, and use the ‘pow’ method to get the cube of the integer.
The list comprehension is used to iterate through the list, and use the ‘pow’ method to get the cube of the integer.
This is assigned to a result.
This is assigned to a result.
This result is displayed as output on the console.
This result is displayed as output on the console.
Tryit Editor v3.6 - Show Python

myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
​
mydict = { "name": "John", "address": "Highway 37" }
​
x = mycol.insert_one(mydict)
What is Pointer operator * in C++?

C++ provides two pointer operators, which are Address of Operator (&) and Indirection Operator (*). A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to "point to" the other variable. A variable can be any data type including an object, structure or again pointer itself.
The indirection Operator (*), and it is the complement of &. It is a unary operator that returns the value of the variable located at the address specified by its operand. For example,
#include <iostream>
using namespace std;
int main () {
   int  var;
   int  *ptr;
   int  val;
   var = 3000;
   
   // take the address of var
   ptr = &var;
   
   // take the value available at ptr      
   val = *ptr;      
   cout << "Value of var :" << var << endl;
   cout << "Value of ptr :" << ptr << endl;
   cout << "Value of val :" << val << endl;
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var : 3000
Value of ptr : 0xbff64494
Value of val : 3000
C++ Program to Implement Map in STL

A Map is an associative container that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Functions are used here:
m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end.
m::find() – Returns an iterator to the element with key value ‘b’ in the map if found, else returns the iterator to end.
m::erase() – Removes the key value from the map.
m::erase() – Removes the key value from the map.
m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
m:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.
m insert() – To insert elements in the map container.
m insert() – To insert elements in the map container.
m size() – Returns the number of elements in the map container.
m size() – Returns the number of elements in the map container.
m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map.
m count() – Returns the number of matches to element with key value ‘a’ or ‘f’ in the map.
#include<iostream>
#include <map>
#include <string>
using namespace std;
int main () {
   map<char, int> m;
   map<char, int>::iterator it;
   m.insert (pair<char, int>('a', 10));
   m.insert (pair<char, int>('b', 20));
   m.insert (pair<char, int>('c', 30));
   m.insert (pair<char, int>('d', 40));
   cout<<"Size of the map: "<< m.size() <<endl;
   cout << "map contains:\n";
   for (it = m.begin(); it != m.end(); ++it)
      cout << (*it).first << " => " << (*it).second << '\n';
   for (char c = 'a'; c <= 'd'; c++) {
      cout << "There are " << m.count(c) << " element(s) with key " << c << ":";
      map<char, int>::iterator it;
      for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)
         cout << ' ' << (*it).second;
         cout << endl;
   }
   if (m.count('a'))
      cout << "The key a is present\n";
   else
      cout << "The key a is not present\n";
   if (m.count('f'))
      cout << "The key f is present\n";
   else
      cout << "The key f is not present\n";
   it = m.find('b');
   m.erase (it);
   cout<<"Size of the map: "<<m.size()<<endl;
   cout << "map contains:\n";
   for (it = m.begin(); it != m.end(); ++it)
   cout << (*it).first << " => " << (*it).second << '\n';
   return 0;
}
Size of the map: 4
map contains:
a => 10
b => 20
c => 30
d => 40
There are 1 element(s) with key a: 10
There are 1 element(s) with key b: 20
There are 1 element(s) with key c: 30
There are 1 element(s) with key d: 40
The key a is present
The key f is not present
Size of the map: 3
map contains:
a => 10
c => 30
d => 40