code-rag-bench/online-tutorials huggingface dataset:
Java Program to Extract a Image From a PDF - GeeksforGeeks

17 Nov, 2020
Program to extract an image from a PDF using Java. The external jar file is required to import in the program. Below is the implementation for the same.
Algorithm:
Extracting image using the APACHE PDF Box module.
Load the existing PDF document using file io.
Creating an object of PDFRenderer class.
Rendering an image from the PDF document using the BufferedImage class.
Writing the extracted image to the new file.
Close the document.
Note: External files are required to download for performing the operation. For more documentation of the module used to refer to this. 
Implementation:
Java
// Extracting  Images  from a PDF using javaimport java.io.*;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.rendering.PDFRenderer;  class GFG {    public static void main(String[] args) throws Exception    {        // Existing PDF Document        // to be Loaded using file io        File newFile            = new File("C:/Documents/GeeksforGeeks.pdf");        PDDocument pdfDocument = PDDocument.load(newFile);          // PDFRenderer class to be Instantiated        // i.e. creating it's object        PDFRenderer pdfRenderer            = new PDFRenderer(pdfDocument);          // Rendering an image        // from the PDF document        // using BufferedImage class        BufferedImage img = pdfRenderer.renderImage(0);        // Writing the extracted        // image to a new file        ImageIO.write(            img, "JPEG",            new File("C:/Documents/GeeksforGeeks.png"));        System.out.println(            "Image has been extracted successfully");          // Closing the PDF document        pdfDocument.close();    }}
PDF before execution:
Existing PDF Document which containing the image which is to be extracted 
Image after extraction:
Extracted Image from the PDF document
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Stack remove(int) method in Java with Example - GeeksforGeeks

24 Dec, 2018
The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index.
Syntax:
Stack.remove(int index)
Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Stack.
Return Value: This method returns the element that has just been removed from the Stack.
Below program illustrate the Java.util.Stack.remove(int index) method:
Example 1:
// Java code to illustrate remove() when position of// element is passed as parameter  import java.util.*;  public class StackDemo {    public static void main(String args[])    {          // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements in the Stack        stack.add("Geeks");        stack.add("for");        stack.add("Geeks");        stack.add("10");        stack.add("20");          // Output the Stack        System.out.println("Stack: " + stack);          // Remove the element using remove()        String rem_ele = stack.remove(4);          // Print the removed element        System.out.println("Removed element: "                           + rem_ele);          // Print the final Stack        System.out.println("Final Stack: "                           + stack);    }}
Stack: [Geeks, for, Geeks, 10, 20]
Removed element: 20
Final Stack: [Geeks, for, Geeks, 10]

Example 2:
// Java code to illustrate remove() when position of// element is passed as parameter  import java.util.*;  public class StackDemo {    public static void main(String args[])    {          // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Use add() method to add elements in the Stack        stack.add(10);        stack.add(20);        stack.add(30);        stack.add(40);        stack.add(50);          // Output the Stack        System.out.println("Stack: " + stack);          // Remove the element using remove()        int rem_ele = stack.remove(0);          // Print the removed element        System.out.println("Removed element: "                           + rem_ele);          // Print the final Stack        System.out.println("Final Stack: "                           + stack);    }}
Stack: [10, 20, 30, 40, 50]
Removed element: 10
Final Stack: [20, 30, 40, 50]

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Java Program Format Time in MMMM Format - GeeksforGeeks

02 Nov, 2020
In Java, The MMM format for months is a short form of the month using 3 characters. SimpleDateFormat class is used for implementing this format in java and you can import this package by using the following code. 
import java.text.SimpleDateFormat

Example:
MMMM Format:
The MMMM format for months is the full name of the Month. For example -January, February, March, April, May, etc are the MMMM Format for the Month. 
Here, you will see the complete package that how you can use SimpleDateFormat class which extends DateFormat class. SimpleDateFormat class is also helpful to convert date to text format and also it’s parsing from text to date format and in normalization.
Class SimpleDateFormat
     java.lang.Object
        java.text.Format
            java.text.DateFormat
                 java.text.SimpleDateFormat

Example 1: Display Month in MMM and MMMM Format 
Java
// Java program to display Month // in MMM and MMMM Formatimport java.text.SimpleDateFormat;import java.util.Date;  public class GFG {    public static void main(String[] argv) throws Exception {          // Setting the date object    Date dat = new Date();    SimpleDateFormat dateFormat;          // Setting MMM Format    dateFormat = new SimpleDateFormat("MMM");    System.out.println(dateFormat.format(dat));          // Setting MMMM Format    dateFormat = new SimpleDateFormat("MMMM");    System.out.println(dateFormat.format(dat));}}
Output : 
Nov
November

Example 2: Display Date and Time in MMMM Format 
Java
// Java Program to Display Date// and Time in MMMM Formatimport java.text.SimpleDateFormat;import java.util.Date;  public class GFG {    public static void main(String[] argv) throws Exception {          // Setting the date object    Date dat = new Date();    SimpleDateFormat dateFormat;      // Setting the date and time in MMMM format    dateFormat = new SimpleDateFormat("EEEE  dd MMMM yyyy kk:mm:ss");    System.out.println(dateFormat.format(dat));}}
Output: 
Monday  02 November 2020 11:46:05

Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
How to use Divider Component in ReactJS? - GeeksforGeeks

05 Mar, 2021
A divider is a thin line that groups content in lists and layouts. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Divider Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Divider from "@material-ui/core/Divider";import ListItem from "@material-ui/core/ListItem";import ListItemText from "@material-ui/core/ListItemText";import List from "@material-ui/core/List";  export default function App() {  return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to use Divider Component in ReactJS?</h4>      <List component="nav">        <ListItem button>          <ListItemText primary="1 Divider Below this list item" />        </ListItem>        <Divider />        <ListItem button divider>          <ListItemText primary="2 Divider Below this list item" />        </ListItem>        <Divider /> <br />        <Divider />      </List>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/dividers/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
SUBSTRING() Function in SQL Server - GeeksforGeeks

28 Sep, 2020
The SUBSTRING() function extracts a substring starting from a position in an input string with a given length. In the case of substring, you need an input string and need to mention the starting point and the total length of the string.
Input  : String, start, length
output : substring.

Syntax :
SUBSTRING(input_string, start, length);

Parameter :SUBSTRING function accepts three-parameter like String, start, length. Let’s have a look.
input_string –It can be a character, binary, text, ntext, or image expression.
start – It is an integer defining the location where the returned substring starts. The first position in the string is 1.
length – It is a positive integer that specifies the number of characters to be returned from the substring.
Returns :It returns a substring with a specified length starting from a location in an input string.
Example-1 :Using SUBSTRING() function with literal strings.
SELECT SUBSTRING('SQL In Geeksforgeeks', 7, 18 ) 
AS ExtractString;

Output :
Example-2 :Using SUBSTRING() function with table columns.
Table -Player_Details
SELECT SUBSTRING(PlayerName, 1, 5) AS ExtractString
FROM Player_Details;

Output :
DBMS-SQL
SQL-Server
substring
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
Timer objects in Python

Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions. In python Timer is a subclass of Thread class. Using start() method timer is started.
threading.Timer(interval, function, args = None, kwargs = None), this is the syntax of creating timer of Timer object.
Here in this example at first we shall get
After 3 second it will display
import threading
   def mytimer():
      print("Python Program\n")
      my_timer = threading.Timer(3.0, mytimer)
      my_timer.start()
print("Bye\n")
Bye
Python Program
timer.cancel() is the syntax for cancelling the timer.
import threading
   def mytimer():
      print("Python Program\n")
      my_timer = threading.Timer(3.0, mytimer)
      my_timer.start()
   print("Cancelling timer\n")
      my_timer.cancel()
print("Bye\n")
Cancelling Timer
Bye
Difference between fork() and exec() in C

Here we will see the effect of fork() and exec() system call in C. The fork is used to create a new process by duplicating the calling process. The new process is the child process. See the following property.
The child process has its own unique process id.
The parent process id of the child process is same as the process id of the calling process.
The child process does not inherit the parent’s memory lock and semaphores.
The fork() returns the PID of the child process. If the value is non-zero, then it is parent process’s id, and if this is 0, then this is child process’s id.
The exec() system call is used to replace the current process image with the new process image. It loads the program into the current space, and runs it from the entry point.
So the main difference between fork() and exec() is that fork starts new process which is a copy of the main process. the exec() replaces the current process image with new one, Both parent and child processes are executed simultaneously.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main() {
   pid_t process_id;
   int return_val = 1;
   int state;
   process_id = fork();
   if (process_id == -1) { //when process id is negative, there is an error, unable to fork
      printf("can't fork, error occured\n");
         exit(EXIT_FAILURE);
   } else if (process_id == 0) { //the child process is created
      printf("The child process is (%u)\n",getpid());
         char * argv_list[] = {"ls","-lart","/home",NULL};
      execv("ls",argv_list); // the execv() only return if error occured.
      exit(0);
   } else { //for the parent process
      printf("The parent process is (%u)\n",getppid());
      if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state
         if (WIFEXITED(state) && !WEXITSTATUS(state))
            printf("program is executed successfully\n");
         else if (WIFEXITED(state) && WEXITSTATUS(state)) {
            if (WEXITSTATUS(state) == 127) {
               printf("Execution failed\n");
            } else
               printf("program terminated with non-zero status\n");
         } else
            printf("program didn't terminate normally\n");
      }
      else {
         printf("waitpid() function failed\n");
      }
      exit(0);
   }
   return 0;
}
The parent process is (8627)
The child process is (8756)
program is executed successfully
Java Math acos() Method

❮ Math Methods

Return the arc cosine of different numbers:
System.out.println(Math.acos(0.64));
System.out.println(Math.acos(-0.4));
System.out.println(Math.acos(0));
System.out.println(Math.acos(1));
System.out.println(Math.acos(-1));
System.out.println(Math.acos(2)); 

Try it Yourself »

The acos() method returns the arc cosine 
value of a number.
Tip: acos(-1) returns the value of PI.
public static double abs(double number)

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.
Angular Material - Toasts

The Angular Material provides various special methods to show unobtrusive alerts to the users. It also provides a term toast for them. The $mdToast service is used to show toasts.
The following example shows the use of toasts.
am_toasts.htm
<html lang = "en">
   <head>
      <link rel = "stylesheet"
         href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
      <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
      
      <script language = "javascript">
         angular
            .module('firstApplication', ['ngMaterial'])
            .controller('toastController', toastController);

         function toastController ($scope, $mdToast, $document) { 
            $scope.showToast1 = function() {
               $mdToast.show (
                  $mdToast.simple()
                  .textContent('Hello World!')                       
                  .hideDelay(3000)
               );
            };

            $scope.showToast2 = function() {
               var toast = $mdToast.simple()
                  .textContent('Hello World!')
                  .action('OK')
                  .highlightAction(false);                     
               
               $mdToast.show(toast).then(function(response) {
                  if ( response == 'ok' ) {
                     alert('You clicked \'OK\'.');
                  }
               });			   
            }
         }	  
      </script>      
   </head>
   
   <body ng-app = "firstApplication"> 
      <div id = "toastContainer" ng-controller = "toastController as ctrl"
         layout = "row" ng-cloak>
         <md-button ng-click = "showToast1()">Show Simple Alert</md-button>
         <md-button ng-click = "showToast2()">Show Alert with callback</md-button>
      </div>
   </body>
</html>
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Text Validations in Cypress

Cypress can validate the text on an element with the help of jQuery text() method.
This method shall help us to fetch the text content on the selected element. We
can also put assertions on the text content of the element.
cy.get('.product').should('have.text', 'Tutorialspoint');
We can do validations on the text like verify what it contains or matches with the
help of the Javascript methods match(), include() and so on. Thus Cypress
commands can work on non-Cypress methods with the help of jQuery objects and
invoke methods on them.
Code Implementation with the text() method.
// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/index.htm");
// enter test in the edit box
// assertion to validate the number of child elements
cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);
// locate element with get and find method
cy.get('#gs_50d > tbody > tr > td'). find('input')
//enter test in the edit box
.type('Cypress');
//iterate the list items with each command
cy.get('.mui-tabs__bar.mui-tabs__bar_1.mui-tabs__bar--justified)
.find('li').each(($el, index, $list) => {
// extract text with text() method
const txt = $el.find('a').text();
if ( txt.includes('Deve')){
$el.click();
}
})
});
});
On running the above block of code, Cypress Test runner gives the below output −
MongoDB and Python

MongoDB is a widely used document database which is also a form of NoSQL DB. Python can interact with MongoDB through some python modules and create and manipulate data inside Mongo DB. In this article we will learn to do that. But MongoDB should already be available in your system before python can connect to it and run. To setup MongoDB in your system please visit our  MongoDB tutorial
here..
To interact with MongoDB we need the module names pymongo. Install it in your python environment using the below command.
pip install pymogo
We now use this python module to check for any existing DB. The below python program connects to the MongoDB service and gives a output of the list of DB names available.
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

print(myclient.list_database_names())
Running the above code gives us the following result −
['Mymdb', 'admin', 'config', 'local']
A collection is similar to a table in traditional rdbms. We can next check for collections present in a specific database using the below python program.
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
print(mndb.list_collection_names())
Running the above code gives us the following result −
['newmongocoll']
The document in MongoDB is also comparable to a row in traditional RDBMS. In this program we see how to insert a document to MongoDB using a python program. First we connect to the DB and collections and then use a dictionary to put values of the document into the collection.
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
mycol = mndb['newmongocoll']

mydict = { "ID": "2", "Name": "Ramana" }

x = mycol.insert_one(mydict)
print(x)
Running the above code gives us the following result −
<pymongo.results.InsertOneResult object at 0x000002CA92A920C0>
We can also query for documents present in MongoDB using find method available in pymongo.
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
mycol = mndb['newmongocoll']

for x in mycol.find():
print(x)
Running the above code gives us the following result −
{'_id': ObjectId('5ef8b6f92d192421b78d32cb'), 'ID': '2', 'Name': 'Ramana'}
How to handle authentication popup with Selenium WebDriver using Java?

We can handle authentication popup with Selenium. To do this, we have to pass the user credentials within the URL. We shall have to add the username and password to the URL.
https://username:password@URL
https://admin:admin@the−nternet.herokuapp.com/basic_auth
Here, the admin is the username and password.
URL − www.the-internet.herokuapp.com/basic_auth
Let us work and accept the below authentication popup.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AuthnPopup{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u = "admin";
      // adding username, password with URL
      String str = "https://" + u + ":" + u + "@" +
      "the-internet.herokuapp.com/basic_auth";
      driver.get(str);
      // identify and get text after authentication of popup
      String t = driver.findElement(By.cssSelector("p")).getText();
      System.out.println("Text is: " + t);
      driver.quit();
   }
}
React.js Component Lifecycle - Unmounting

ComponentWillUnmount is the only method that executes in unmount phase.
Component enters into this phase when there is no matching in element tree for this component.
Just before the component gets removed from actual DOM, this method gets called.
Along with removal of this component from DOM tree, all children of this component also gets removed automatically.
Once component is removed from the DOM, it gets available for the garbage collection in React.
Cleanup activities can be done in this method. E.g. clear localstorage variables used in app, clear session, clean up charts, cleanup timers, cancel pending api requests etc.
componentWillUnmount(){
   this.resetSession(); //example method to clean data
}
Cleanup activities helps in improving performances, memory leakages and maintain security.
In latest release 16.4 +, three methods are marked as deprecated and renamed as well. These methods will be removed in next major release of React.jscomponentWillReceiveProps changed to UNSAFE_componentWillReceiveProps . This method is implemented securely and statically with name getDerivedStateFromPropscomponentWillMount changed to UNSAFE_componentWillMount. Code from this method should be moved to componentDidMount or constructor as per logic.componentWillUpdate changed to UNSAFE_componentWillUpdate. Secure implementation is getSnapshotBeforeUpdate. If there is any value returned from this method then it will used as an argument in the next method i.e. componentDidUpdate.If user closes browser then the componentWiIlUnmount will not complete.componentWillUnmount does not have any argument. setState shold not be called from this method. This is a one-time call for the component. Purpose of this method is to destroy the side effects created by the component.Once component is unmounted, we can’t use it again. Every time a new component gets created.Also if there is no difference in virtual dom and actual dom, react can stop the update phase as well.
componentWillReceiveProps changed to UNSAFE_componentWillReceiveProps . This method is implemented securely and statically with name getDerivedStateFromProps
componentWillMount changed to UNSAFE_componentWillMount. Code from this method should be moved to componentDidMount or constructor as per logic.
componentWillUpdate changed to UNSAFE_componentWillUpdate. Secure implementation is getSnapshotBeforeUpdate. If there is any value returned from this method then it will used as an argument in the next method i.e. componentDidUpdate.
If user closes browser then the componentWiIlUnmount will not complete.
componentWillUnmount does not have any argument. setState shold not be called from this method. This is a one-time call for the component. Purpose of this method is to destroy the side effects created by the component.
Once component is unmounted, we can’t use it again. Every time a new component gets created.
Also if there is no difference in virtual dom and actual dom, react can stop the update phase as well.
How to adjust Space Between ggplot2 Axis Labels and Plot Area in R ? - GeeksforGeeks

21 Apr, 2021
While plotting the graphs we can make different changes in order to make them much more appealing and clear to the observer. One of the ways is to adjust the spacing between the labels and plot area. In this article, we will study how to adjust space between ggplot2 Axis Labels and plot area in R Programming Language.
To add customizations to our plot we can use the theme() function.
To adjust the vertical spacing we use vjust in the element_text function to vertically adjust the plotting
Example
R
rm(list=ls())  data <- data.frame(name = c("Aditya", "Ritika", "Pulkit",                            "Vishesh", "Kaif"),                                         marks = c(58, 82, 79, 42, 66))                                          library("ggplot2")     ggp <- ggplot(data, aes(name, marks, fill = name)) +              geom_bar(stat = "identity")  ggp + theme(axis.text.x = element_text(vjust = -12))       
Output:
vertically adjusted plot
We can adjust the horizontal spacing in the similar way using hjust in element_text
Example
R
rm(list=ls())  data <- data.frame(Name = c("Aditya", "Ritika", "Pulkit",                            "Vishesh", "Kaif"),                                         Marks = c(58, 82, 79, 42, 66))             library("ggplot2")                                            ggp <- ggplot(data, aes(Name, Marks, fill = Name)) +              geom_bar(stat = "identity")                          ggp + theme(axis.text.x = element_text(hjust = -1))   
Output:
horizontally adjusted plot
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
Tryit Editor v3.7

Tryit: Template 1 - using float
Tryit Editor v3.6 - Show Node.js Command Prompt

var mysql = require('mysql');
​
var con = mysql.createConnection({
  host: "localhost",
  user: "myusername",
  password: "mypassword",
  database: "mydb"
});
​
con.connect(function(err) {
  if (err) throw err;
Make a star shape with HTML5 SVG

Here is the HTML5 version of an SVG example that would draw a star using the <polygon> tag.
<html>
   <head>
      <style>
         #svgelem{
            position: relative;
            left: 50%;
            -webkit-transform: translateX(-40%);
            -ms-transform: translateX(-40%);
            transform: translateX(-40%);
         }
      </style>
      <title>SVG</title>
      <meta charset="utf-8" />
   </head>
   <body>
      <h2 align = "center">HTML5 SVG Star</h2>
      <svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
      <polygon points = "100,10 40,180 190,60 10,60 160,180" fill = "red"/>
      </svg>
   </body>
</html>
The search Function in Python

This function searches for first occurrence of RE pattern within string with optional flags.
Here is the syntax for this function −
re.search(pattern, string, flags=0)
Here is the description of the parameters −
The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression.
 Live Demo
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
   print "searchObj.group() : ", searchObj.group()
   print "searchObj.group(1) : ", searchObj.group(1)
   print "searchObj.group(2) : ", searchObj.group(2)
else:
   print "Nothing found!!"
When the above code is executed, it produces the following result −
searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter
Redirecting System.out.println() output to a file in Java

The filed named out of the System class represents a standard output Stream, an object of the PrintStream class.
The println() method of this accepts any a value ( of any Java valid type), prints it and terminates the line.
By default, console (screen) is the standard output Stream (System.in) in Java and, whenever we pass any String value to System.out.prinln() method, it prints the given String on the console.
The setOut() method of the System class in java accepts an object of the PrintStream class and makes it the new standard output stream.
Therefore, to redirect the System.out.println() output to a file −
Create an object of the File class.
Create an object of the File class.
Instantiate a PrintStream class by passing the above created File object as a parameter.
Instantiate a PrintStream class by passing the above created File object as a parameter.
Invoke the out() method of the System class, pass the PrintStream object to it.
Invoke the out() method of the System class, pass the PrintStream object to it.
Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.
Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
public class SetOutExample {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      File file = new File("D:\\sample.txt");
      //Instantiating the PrintStream class
      PrintStream stream = new PrintStream(file);
      System.out.println("From now on "+file.getAbsolutePath()+" will be your console");
      System.setOut(stream);
      //Printing values to file
      System.out.println("Hello, how are you");
      System.out.println("Welcome to Tutorialspoint");
   }
}
From now on D:\sample.txt will be your console
How to create a subarray from another array in Java

Use Arrays.copyOfRange() method to get a subarray.
import java.util.Arrays;
public class Tester {
   public static void main(String[] args) {
      int[] array = new int[] {1, 2, 3, 4, 5};
      int[] subArray = Arrays.copyOfRange(array, 0, 2);
      System.out.println("Array: ");
      for(int i = 0; i < array.length; i++) {
         System.out.print(array[i] + " ");
      }
      System.out.println("\nSub array: ");
      for(int i = 0; i < subArray.length; i++) {
         System.out.print(subArray[i] + " ");
      }
   }
}
Array:
1 2 3 4 5
Sub array:
1 2
Construct Binary Search Tree from Preorder Traversal in Python

Suppose we have to create a binary search tree that matches the given preorder traversal. So if the pre-order traversal is like [8,5,1,7,10,12], then the output will be [8,5,10,1,7,null,12], so the tree will be −
To solve this, we will follow these steps −
root := 0th node of the preorder traversal list
stack := a stack, and push root into the stack
for each element i from the second element of the preorder listi := a node with value iif value of i < top of the stack top element, thenleft of stack top node := iinsert i into the stackotherwisewhile stack is not empty, and stack top element value < value of ilast := top of stackpop element from stackright of the last node := iinsert i into the stack
i := a node with value i
if value of i < top of the stack top element, thenleft of stack top node := iinsert i into the stack
left of stack top node := i
insert i into the stack
otherwisewhile stack is not empty, and stack top element value < value of ilast := top of stackpop element from stackright of the last node := iinsert i into the stack
while stack is not empty, and stack top element value < value of ilast := top of stackpop element from stack
last := top of stack
pop element from stack
right of the last node := i
insert i into the stack
return root
Let us see the following implementation to get better understanding −
class Solution(object):
   def bstFromPreorder(self, preorder):
      """
      :type preorder: List[int]
      :rtype: TreeNode
      """
      root = TreeNode(preorder[0])
      stack = [root]
      for i in preorder[1:]:
         i = TreeNode(i)
         if i.val<stack[-1].val:
            stack[-1].left = i
            stack.append(i)
         else:
            while stack and stack[-1].val<i.val:
               last = stack.pop(-1)
            last.right = i
            stack.append(i)
      return root
[8,5,1,7,10,12]
[8,5,10,1,7,null,12]
Matplotlib.axes.Axes.autoscale() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.autoscale() function in axes module of matplotlib library is used to autoscale the axis view to the data (toggle).
Syntax: Axes.autoscale(self, enable=True, axis=’both’, tight=None)
Parameters: This method accepts the following parameters.
enable : If this parameter is True (default) turns autoscaling on, False turns it off.
axis: This parameter is used to which axis to be operate on. {‘both’, ‘x’, ‘y’}
tight: This parameter is forwarded to autoscale_view.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.autoscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function  import numpy as npfrom matplotlib.path import Pathfrom matplotlib.patches import PathPatchimport matplotlib.pyplot as plt    vertices = []codes = []  codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]vertices = [(1, 1), (1, 2), (2, 2),             (2, 1), (0, 0)]  codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]vertices += [(4, 4), (5, 5), (5, 4),              (0, 0)]  vertices = np.array(vertices, float)path = Path(vertices, codes)  pathpatch = PathPatch(path, facecolor ='None',                      edgecolor ='green')  fig, ax = plt.subplots()ax.add_patch(pathpatch)ax.autoscale()  fig.suptitle('matplotlib.axes.Axes.autoscale() \function Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib function  import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.collections import EllipseCollection  x = np.arange(10)y = np.arange(15)X, Y = np.meshgrid(x, y)  XY = np.column_stack((X.ravel(), Y.ravel()))  fig, ax = plt.subplots()  ec = EllipseCollection(10, 10, 5, units ='y',                       offsets = XY * 0.5,                       transOffset = ax.transData,                       cmap ="inferno")  ec.set_array((X * Y).ravel())ax.add_collection(ec)ax.autoscale_view()ax.set_xlabel('X')ax.set_ylabel('y')cbar = plt.colorbar(ec)cbar.set_label('X + Y')  fig.suptitle('matplotlib.axes.Axes.autoscale() function \Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Windows application and Web application

15 Jun, 2022
1. Windows application : It is an application that can run on the windows platform. Graphical user interface forms can be created using this. We can create web applications using IDE Microsoft Visual Studio. This can be done using a variety of programming languages such C#, C++, J#, Visual Basic and many more. Windows applications on a computer system – 
2. Web application : Web application is an application that runs on web browser making use of web server. It makes use of is Microsoft IIS configuration i.e., Internet Information Services (in developing web applications). A variety of web applications using .net can be made. These include many ranging from simple HTML pages to highly interactive business applications. 
Examples of Web applications – 
Difference between Windows application and web application : 
sumitgumber28
abhishek0719kadiyan
annieahujaweb2020
Web technologies
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Synchronous and Asynchronous Transmission
Difference Between Method Overloading and Method Overriding in Java
Difference Between Go-Back-N and Selective Repeat Protocol
Time complexities of different data structures
Difference between Compile-time and Run-time Polymorphism in Java
Differences and Applications of List, Tuple, Set and Dictionary in Python
Difference between HTTP GET and POST Methods
Difference between Top down parsing and Bottom up parsing
Difference between Prim's and Kruskal's algorithm for MST
Difference Between Paging and Segmentation
Maximum of four numbers without using conditional or bitwise operator in C++

In this problem, we are given four integer numbers. Our task is to create a
program to find the maximum of four numbers without using conditional or
bitwise operator in C++.
Code Description − Here, we have four integer values. And we need to find the maximum value out of these numbers without using any conditional or bitwise operator.
Let’s take an example to understand the problem,
a = 4, b = 7, c = 1, d = 9
9
To solve the problem, we will take two elements first, then take the greater element with pair. For each pair, we will create a 2 element arr[] and find which element is greater using the boolean value. The boolean value is used as index, found using the the formula [abs(x - y) + (x - y)].
An easy explanation is,
If arr[0] is greater than arr[1], boolean value is False. else it is True.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int findMax(int x, int y){
   int arr[2] = {x,y};
   bool MaxIndex = ( !(arr[0] - arr[1] + abs(arr[0] - arr[1])));
   return arr[MaxIndex];
}
int CalcMaxElement(int a, int b, int c, int d) {
   int max = a;
   max = findMax(max, b);
   max = findMax(max, c);
   max = findMax(max, d);
   return max;
}
int main() {
   int a = 4, b = 9, c = 7, d = 1;
   cout<<"The maximum of four numbers is "<<CalcMaxElement(a,b,c,d);
   return 0;
}
The maximum of four numbers is 9
Time complexity of recursive Fibonacci program

20 Oct, 2017
The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13...Mathematically Fibonacci numbers can be written by the following recursive formula.
For seed values F(0) = 0 and F(1) = 1
F(n) = F(n-1) + F(n-2)

Before proceeding with this article make sure you are familiar with the recursive approach discussed in Program for Fibonacci numbers
Analysis of the recursive Fibonacci program:We know that the recursive equation for Fibonacci is =++.What this means is, the time taken to calculate fib(n) is equal to the sum of time taken to calculate fib(n-1) and fib(n-2). This also includes the constant time to perform the previous addition.
On solving the above recursive equation we get the upper bound of Fibonacci as  but this is not the tight upper bound. The fact that Fibonacci can be mathematically represented as a linear recursive function can be used to find the tight upper bound.Now Fibonacci is defined as
 = +
The characteristic equation for this function will be = + – – = 
Solving this by quadratic formula we can get the roots as = (+)/ and =( – )/
Now we know that solution of a linear recursive function is given as =  + 
where  and  are the roots of the characteristic equation.So for our Fibonacci function  = + the solution will be
 = +Clearly  and  are asymptotically the same as both functions are representing the same thing.Hence it can be said that = or we can write below (using the property of Big O notation that we can drop lower order terms) =  = This is the tight upper bound of fibonacci.\
Fun Fact:1.6180 is also called the golden ratio. You can read more about golden ratio here: Golden Ratio in Maths
This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Fibonacci
Analysis
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Analysis of Algorithms | Set 4 (Analysis of Loops)
Time Complexity of building a heap
Analysis of different sorting techniques
Time complexities of different data structures
NP-Completeness | Set 1 (Introduction)
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between NP hard and NP complete problem
Analysis of Algorithms | Big-O analysis
What does 'Space Complexity' mean?
Queries using AND ,OR ,NOT operators in MySQL

21 Jun, 2022
AND, OR, NOT operators are basically used with WHERE clause in order to retrieve data from table by filtering with some conditions using AND, OR, NOT in MySQL.Here in this article let us see different queries on the student table using AND, OR, NOT operators step-by-step.
Step-1:Creating a database university:
CREATE DATABASE university;
Step-2:Using the database university:
USE university;
Step-3:Creating a table student:
CREATE TABLE student(
student_id INT
student_name VARCHAR(20)
birth_date DATE
branch VARCHAR(20)
state VARCHAR(20));
Step-4:Viewing the description of the table student:
DESCRIBE student;
Step-5:Adding rows into student table:
INSERT INTO student VALUES(194001,'PRANAB','1999-03-17','CSE','PUNJAB');
INSERT INTO student VALUES(194002,'PRAKASH','2000-08-07','ECE','TAMIL NADU');
INSERT INTO student VALUES(194003,'ROCKY','2000-03-10','ECE','PUNJAB');
INSERT INTO student VALUES(194004,'TRIBHUVAN','1999-03-15','CSE','ANDHRA PRADESH');
INSERT INTO student VALUES(194005,'VAMSI','2000-04-19','CSE','TELANGANA');
Step-6:Viewing the rows in the table:
SELECT * FROM student;
syntax for AND operator:SELECT * FROM table_nameWHERE condition1 AND condition2 AND ....CONDITIONn;
Example-1:Query to find student records with a branch with CSE and  state with PUNJAB using AND operator in MySQL:
SELECT *
    FROM student
    WHERE branch='CSE'ANDstate='PUNJAB'
All the students with branch CSE and from Punjab.
syntax for OR operator:SELECT * FROM table_nameWHERE condition1 OR condition2 OR....CONDITIONn;
Example-2:Query to find student records with a branch with CSE or ECE using OR operator in MySQL:
SELECT *
    FROM student
    WHERE branch='CSE' OR branch='ECE';
All the students with branch either CSE or ECE.
syntax for NOT operator:SELECT * FROM table_nameWHERE NOT condition1 NOT condition2 NOT...CONDITIONn;
Example-3:Query to find student records who were out of PUNJAB using the NOT operator in MySQL:
SELECT *
      FROM student
      WHERE NOT state='PUNJAB';
All the students were from states other than Punjab.
aayushi2402
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are the differences between an Annotation and a Decorator in Angular?

11 Feb, 2022
Although Annotations and Decorators both share the same @ symbol in Angular, they both are different language features.
Annotations: These are hard-coded language feature. Annotations are only metadata set on the class that is used to reflect the metadata library. When user annotates a class, the compiler creates an attribute on that class called annotations, stores an annotation array in it, then tries to instantiate an object with the same name as the annotation, passing the metadata into the constructor. Annotations are not predefined in AngularJs so we can name them on our own.
Example:@ComponentAnnotation
@ComponentAnnotation
Features of Annotations:
Annotations are hard-coded.
Annotations are used by AtScript and Traceur compiler.
Annotations reflect metadata library
Note: Nowadays AngularJs switched from AtScript to TypeScript but Annotations are supported these days also.
Example: Here component is annotated as ComponentAnnotation and further used.
import {   ComponentAnnotation as Component,} from '@angular/core';      export class ComponentAnnotation extends DirectiveMetadata {    constructor() {      }}
Decorators: A decorator is a function that adds metadata to a class, its members, or its method arguments. A decorator is just a function that gives you access to the target that needs to be decorated. There are four type of decorators all of them arem mentioned below:
Types of Decorators:
Class decorators like @Component, @NgModule
Property decorators like @Input and @Output
Method decorators like @HostListener
Parameter decorators like @Injectable
Features of Decorators:
Decorators are predefined in AngularJs.
Decorators are used by TypeScript compiler.
Decorators are used to attach metadata to a class,objects and method.
Example:
import { Component } from '@angular/core';  @Component({  selector: 'hi',  template: '<div>GeeksForGeeks</div>',})export class Geeks{  constructor() {    console.log('GeeksForGeeks');  }}
Differences between Annotation and Decorator:
Conclusion:There is a very significant difference between Annotations and Decorators in AngularJS. Both Decorators and Annotations are supported by Angular. This is a legacy thing because Angular2 swapped from AtScript to TypeScript. Decorators are the default in AngularJs but you can use Annotations too.
jainnikhil0442
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.