code-rag-bench/online-tutorials huggingface dataset:
How to create ACF plot in R?

The autocorrelation plot or ACF plot is a display of serial correlation in data that changes over time. The ACF plot can be easily created by using acf function.
For example, if we have a vector called V then we can create its autocorrelation plot by using the command given below −
acf(V)
Check out the below examples to understand how it can be done.
To create ACF plot in R, use the code given below −
x<-sample(1:9,10,replace=TRUE)
x
If you execute the above given code, it generates the following output −
[1] 2 5 6 7 1 7 9 3 9 7

To create ACF plot in R, add the following code to the above snippet −
x<-sample(1:9,10,replace=TRUE)
acf(x)
If you execute all the above given codes as a single program, it generates the following output −
To create ACF plot in R, use the code given below −
y<-rpois(10,5)
y
If you execute the above given code, it generates the following output −
[1] 7 5 2 4 7 3 2 6 8 5

To create ACF plot in R, add the following code to the above snippet −
y<-rpois(10,5)
acf(y)
If you execute all the above given codes as a single program, it generates the following output −
How to use onKeyPress event in ReactJS? - GeeksforGeeks

25 Jan, 2021

The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers.
To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build an application that displays the key pressed in the input box.
Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
 

 
 










import React, { useState } from 'react'; 
  
const App = () => { 
  const [state, setState] = useState(''); 
    
  const handler = (event) => { 
      // changing the state to the name of the key 
    // which is pressed 
    setState(event.key); 
  }; 
    
  return ( 
    <div> 
      <h1>Hi Geeks!</h1> 
        
<p>Key pressed is: {state}</p> 
  
        
      {/* Passing the key pressed to the handler function */} 
      <input type="text" onKeyPress={(e) => handler(e)} /> 
        
    </div> 
  ); 
}; 
  
export default App; 






Note: You can define your own styling in the App.css file.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 

Picked


ReactJS


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to redirect to another page in ReactJS ?
How to pass data from one component to other component in ReactJS ?
React-Router Hooks
Re-rendering Components in ReactJS
How to set background images in ReactJS ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Print stack trace in Java

In order to print the stack trace in Java, we use the java.lang.Throwable.printStackTrace() method. The printStackTrace() method prints the throwable and its backtrace in the standard error stream.
Declaration - The java.lang.Throwable.printStackTrace() method is declared as follows −
public void printStackTrace()
Let us see a program to print the stack trace in Java.
 Live Demo
public class Example {
   public static void main(String args[]) throws Throwable {
      try {
         int n = 3;
         System.out.println(n/0);
      } catch (ArithmeticException e) {
         System.out.println("Printing stack trace...");
         e.printStackTrace(); // prints the stack trace
      }
   }
}
Printing stack trace...
java.lang.ArithmeticException: / by zero
at Example.main(Example.java:8)
How can we modify a MySQL view with CREATE OR REPLACE VIEW statement?

As we know that we can modify a view by using ALTER VIEW statement but other than that we can also use CREATE OR REPLACE VIEW to modify an existing view. The concept is simple as MySQL simply modifies the view if it already exists otherwise a new view would be created. Following is the syntax of it −
CREATE OR REPLACE VIEW view_name AS Select_statements FROM table;
mysql> Create OR Replace VIEW Info AS Select Id, Name, Address, Subject from student_info WHERE Subject = 'Computers';
Query OK, 0 rows affected (0.46 sec)
The above query will create or replace a view ‘Info’. It will be created if not existed already otherwise it would get replaced by a new definition given in the above query.
How to correctly sort a string with a number inside in Python?

This type of sort in which you want to sort on the basis of numbers within string is called natural sort or human sort. For example, if you have the text:
['Hello1','Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']
 Then you want the sorted list to be:
['Hello1', 'Hello2','Hello12', 'Hello17', 'Hello25', 'Hello29']
 and not:
['Hello1','Hello12', 'Hello17', 'Hello2', 'Hello25', 'Hello29']
 To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number. 
 import re
 def atoi(text):
    return int(text) if text.isdigit() elsetext
def natural_keys(text):
    return [ atoi(c) for c in re.split('(\d+)',text) ]
 my_list =['Hello1', 'Hello12', 'Hello29', 'Hello2', 'Hello17', 'Hello25']
 my_list.sort(key=natural_keys)
print my_list
 This will give you the output:
['Hello1','Hello2', 'Hello12', 'Hello17', 'Hello25', 'Hello29']
Can we change the Cursor with Java Swing?

Yes, we can change the default cursor representation in Java. Let us first create a button component −
JButton button = new JButton("Button with two borders");
Whenever user will keep the mouse cursor on the above button component, the cursor would change to hand cursor −
Cursor cursor = button.getCursor();
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
The following is an example to change the cursor −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);
      LineBorder lineBorder = new LineBorder(Color.red);
      TitledBorder titleBorder = new TitledBorder("Demo Title");
      Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton button = new JButton("Button with two borders");
      button.setBorder(border);
      Cursor cursor = button.getCursor();
      button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      Container contentPane = frame.getContentPane();
      contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(button,BorderLayout.EAST);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}
The output is as follows. When you will keep the cursor on the button with two borders, then hand cursor will be visible as shown below −
Batch Script - COMP

This batch command compares 2 files based on the file size.
COMP [sourceA] [sourceB]

Wherein sourceA and sourceB are the files which need to be compared.
@echo off 
COMP C:\tp\lists.txt C:\tp\listsA.txt
The above command will compare the files lists.txt and listsA.txt and find out if the two file sizes are different.
 Print
 Add Notes
 Bookmark this page
C++ Program for converting hours into minutes and seconds

Given with the input as hours and the task is to convert the number of hours into minutes and seconds and display the corresponding result
Formula used for converting the hours into minutes and seconds is −
1 hour = 60 minutes
   Minutes = hours * 60
1 hour = 3600 seconds
   Seconds = hours * 3600
Input-: hours = 3
Output-: 3 hours in minutes are 180
   3 hours in seconds are 10800
Input-: hours = 5
Output-: 5 hours in minutes are 300
   5 hours in seconds are 18000
Approach used in the below program is as follows −
Input the number of hours in an integer variable let’s say n
Apply the formula of conversion given above to convert hours into minutes and seconds
Display the result
START
Step 1-> declare function to convert hours into minutes and seconds
   void convert(int hours)
   declare long long int minutes, seconds
   set minutes = hours * 60
   set seconds = hours * 3600
   print minute and seconds
step 2-> In main()
   declare variable as int hours = 3
   Call convert(hours)
STOP
#include <bits/stdc++.h>
using namespace std;
//convert hours into minutes and seconds
void convert(int hours) {
    long long int minutes, seconds;
    minutes = hours * 60;
    seconds = hours * 3600;
    cout<<hours<<" hours in minutes are "<<minutes<<endl<<hours<<" hours in seconds are "<<seconds;
}
int main() {
    int hours = 3;
    convert(hours);
    return 0;
}
3 hours in minutes are 180
3 hours in seconds are 10800
forward_list::unique() in C++ STL - GeeksforGeeks

09 Oct, 2019
forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison.
Syntax:
forwardlist_name.unique(BinaryPredicate name)
Parameters: The function accepts a single parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax:
bool name(data_type a, data_type a)
Return value: The function does not return anything.
// C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std;  // Function for binary_predicate/*bool compare(int a, int b){    return (abs(a) == abs(b));}// This function can also be used and passed inside// unique(), to get the same result*/  int main(){      forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 };      cout << "List of elements before unique operation is: ";      // starts from the first element of the list to the last    for (auto it = list.begin(); it != list.end(); ++it)        cout << *it << " ";      // unique operation on forward list    list.unique();    cout << "\nList of elements after unique operation is: ";      // starts from the first element of the list to the last    for (auto it = list.begin(); it != list.end(); ++it)        cout << *it << " ";      return 0;}
List of elements before unique operation is: 1 1 1 1 2 2 2 2 3 3 3 2 4 4 
List of elements after unique operation is: 1 2 3 2 4

babaurbeautiful
CPP-forward-list
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
How to do date validation in Python?

The date validation you want to achieve in python will largely depend on the format of the date you have. The strptime function from the datetime library can be used to parse strings to dates/times.
import datetime
date_string = '2017-12-31'
date_format = '%Y-%m-%d'
try:
  date_obj = datetime.datetime.strptime(date_string, date_format)
  print(date_obj)
except ValueError:
  print("Incorrect data format, should be YYYY-MM-DD")
This will give the output −
2017-12-31 00:00:00
You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string.
Merge Sort for Doubly Linked List using C++.

Given a doubly linked list. Sort it using merge sort algorithm
List: 10->20->8-17->5->13->4
Sorted list: 4->5->8->10->13->17->20
1. If head is NULL or list contains only one element then return list
2. Create two lists by dividing original list into 2 parts
3. Sort first and second part of list
4. Merge both sorted list
#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct node {
   int data;
   struct node *next;
   struct node *prev;
};
node *createList(int *arr, int n){
   node *head, *p, *q;
   p = head = new node;
   head->data = arr[0];
   head->prev = NULL;
   head->next = NULL;
   for (int i = 1; i < n; ++i) {
      q = new node;
      q->data = arr[i];
      q->prev = p;
      q->next = NULL;
      p->next = q;
      p = q;
   }
   return head;
}
void displayList(node *head){
   while (head != NULL) {
      cout << head->data << " ";
      head = head->next;
   }
   cout << endl;
}
node *mergeSortedLists(node *head1, node *head2){
   node *result = NULL;
   if (head1 == NULL) {
      return head2;
   }
   if (head2 == NULL) {
      return head1;
   }
   if (head1->data < head2->data) {
      head1->next = mergeSortedLists(head1->next, head2);
      head1->next->prev = head1;
      head1->prev = NULL;
      return head1;
   } else {
      head2->next = mergeSortedLists(head1, head2->next);
      head2->next->prev = head2;
      head2->prev = NULL;
      return head2;
   }
}
void splitList(node *src, node **fRef, node **bRef){
   node *fast;
   node *slow;
   slow = src;
   fast = src->next;
   while (fast != NULL) {
      fast = fast->next;
      if (fast != NULL) {
         slow = slow->next;
         fast = fast->next;
      }
   }
   *fRef = src;
   *bRef = slow->next;
   slow->next = NULL;
}
void mergeSort(node **head){
   node *p = *head;
   node *a = NULL;
   node *b = NULL;
   if (p == NULL || p->next == NULL) {
      return;
   }
   splitList(p, &a, &b);
   mergeSort(&a);
   mergeSort(&b);
   *head = mergeSortedLists(a, b);
}
int main(){
   int arr[] = {10, 20, 8, 17, 5, 13, 4};
   node *head;
   head = createList(arr, SIZE(arr));
   cout << "Unsorted list: " << endl;
   displayList(head);
   mergeSort(&head);
   cout << "Final sorted list: " << endl;
   displayList(head);
   return 0;
}
When you compile and execute the above program. It generates the following output −
Unsorted list:
10 20 8 17 5 13 4
Final sorted list:
4 5 8 10 13 17 20
Adding a Page break/new page in SAP Script

To add a new page, you can use Control command NEW-PAGE in Transaction SE71.
NEW-PAGE [page_options] [ spool_options]
This statement creates a new page in the current list and writes the subsequent list output into a spool list.
In T-Code: SE38 Print Program, you can use Function Module CONTROL_FORM to call NEW-PAGE command as below −
CALL FUNCTION 'CONTROL_FORM'

EXPORTING

COMMAND = 'NEW-PAGE'

EXCEPTIONS

UNOPENED = 1

UNSTARTED = 2

OTHERS = 3.
Minimum String in C++

Suppose we have two strings s and t of same length, and both are in lowercase letters. Consider we have rearranged s at first into any order, then count the minimum number of changes needed to turn s into t.
So, if the input is like s = "eccynue", t = "science", then the output will be 2 as if we rearrange "eccynue" to "yccence", then replace y with s and second c with i, it will be "science".
To solve this, we will follow these steps −
ret := 0
ret := 0
Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t
Define two arrays cnt1 to hold frequency of s and cnt2 to hold frequency of t
for initialize i := 0, when i < 26, update (increase i by 1), do −ret := ret + max(cnt1[i] - cnt2[i], 0)
for initialize i := 0, when i < 26, update (increase i by 1), do −
ret := ret + max(cnt1[i] - cnt2[i], 0)
ret := ret + max(cnt1[i] - cnt2[i], 0)
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(string s, string t) {
      int ret = 0;
      vector <int> cnt1(26);
      vector <int> cnt2(26);
      for(int i = 0; i < s.size(); i++){
         cnt1[s[i] - 'a']++;
      }
      for(int i = 0; i < t.size(); i++){
         cnt2[t[i] - 'a']++;
      }
      for(int i = 0; i < 26; i++){
         ret += max(cnt1[i] - cnt2[i], 0);
      }
      return ret;
   }
};
int main(){
   Solution ob;
   cout << (ob.solve("eccynue", "science"));
}
"eccynue", "science"
2
How to have a function return a figure in Python (using Matplotlib)?

To have a function return a figure in Python (using Matplotlib), we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method.
Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method.
Plot the x and y data points using plot() method; return fig instance.
Plot the x and y data points using plot() method; return fig instance.
Call plot(x, y) method and store the figure instance in a variable, f.
Call plot(x, y) method and store the figure instance in a variable, f.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def plot(x, y):
   fig = plt.figure()
   plt.plot(x, y)
   return fig

x = np.linspace(-10, 10, 100)
y = np.sin(x)

f = plot(x, y)

plt.show()
How to set the spacing between words in a text in JavaScript?

Use the wordSpacing property in JavaScript to set the spacing between words.
You can try to run the following code to learn how to implement wordSpacing property −
<!DOCTYPE html>
   <html>
      <body>
         <p id = "pid">This is an example paragraph.</p>
         <button type = "button" id="btn" onclick = "display()">Set Space</button>
         <script>
            function display() {
               document.getElementById("pid").style.wordSpacing = "25px";
            }
         </script>
      </body>
</html>
Prototype - cumulativeScrollOffset() Method

This method calculates and returns the cumulative scroll offset of an element in nested scrolling containers. This adds the cumulative scrollLeft and scrollTop of an element and all its parents.
This is used for calculating the scroll offset of an element that is in more than one scroll container (e.g., a draggable in a scrolling container which is itself part of a scrolling document).
This method returns an array keeping offsetLeft and offsetTop of the element.
element.cumulativeScrollOffset();

An array of two numbers [offset let, offset top].
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function getOffset() {
            firstElement = $('firstDiv');
            var arr = firstElement.cumulativeScrollOffset();
            alert ( "Offset Left: " +arr[0]+ " Offset Top : " +arr[0]);
         }
      </script>
   </head>
   
   <body>
      <p>Click getOffset button to see the result.</p>
      <div id = "firstDiv">
         <p>This is first paragraph</p> 
      </div>
      <br />
      
      <input type = "button" value = "getOffset" onclick = "getOffset();"/>
   </body>
</html>
Click getOffset button to see the result.
This is first paragraph

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
What is NULL check and insertion rule in a DB2 table?

Null in DB2 is defined as nothing. It is an unknown value. If we want to restrict NULL value in any column then the column should be defined with the “NOT NULL” parameter in CREATE TABLE.
The “NOT NULL” will force the user to enter a value for the column. However, if we do not
want to give any value for this column we can also place a “WITH DEFAULT” parameter which will allow DB2 to place the default value in case the user has not provided any value for the “NOT NULL” column.
For example, if we have a column INVOICE_ID which should be not null and also, we want DB2 to insert spaces in this column if the user does not give any value for this column,then we will define the column as below−
CREATE TABLE ORDERS
   (ORDER_ID CHAR(15) NOT NULL,
   ORDER_DATE DATE,
   INVOICE_ID CHAR(15), NOT NULL WITH DEFAULT
   ORDER_TOTAL DECIMAL(9,2),
   TRANSACTION_ID CHAR(15),
   PRIMARY KEY(ORDER_ID),
IN DB4ES01;
The column INVOICE_ID is defined with data type CHAR and the default value taken by DB2 for CHAR is spaces. So in the above case, we have defined INVOICE_ID column as
NOT NULL and it will take default value as spaces when an explicit value is not given for this column.
HTML5 Canvas - Using Images

This tutorial would show how to import an external image into a canvas and then how to draw on that image by using following methods −
beginPath()
This method resets the current path.
moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)
This method draws the given image onto the canvas. Here image is a reference to an image or canvas object. x and y form the coordinate on the target canvas where our image should be placed.
Following is a simple example which makes use of above mentioned methods to import an image.
<!DOCTYPE HTML>

<html>
   <head>
      
      <script type = "text/javascript">
         function drawShape() {
            
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
            
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               
               // Draw shapes
               var img = new Image();
               img.src = '/images/backdrop.jpg';
               
               img.onload = function() {
                  ctx.drawImage(img,0,0);
                  ctx.beginPath();
                  
                  ctx.moveTo(30,96);
                  ctx.lineTo(70,66);
                  
                  ctx.lineTo(103,76);
                  ctx.lineTo(170,15);
                  
                  ctx.stroke();
               }
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
   
</html>
It will produce the following result −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Check if a string has white space in JavaScript?

To check whitespace in a string, use the concept of indexOf(‘ ’). Following is the code −
function stringHasTheWhiteSpaceOrNot(value){
   return value.indexOf(' ') >= 0;
}
var whiteSpace=stringHasTheWhiteSpaceOrNot("MyNameis John");
   if(whiteSpace==true){
      console.log("The string has whitespace");
   } else {
      console.log("The string does not have whitespace");
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo108.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo108.js
The string has whitespace
How to perform double click on an element in Selenium?

We can perform double click on elements in Selenium with the help of Actions class. In order to perform the double click action we will use moveToElement() method, then use doubleClick() method. Finally use build().perform() to execute all the steps.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DoubleClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/questions/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // doubleClick() method for double click to an element after moving to
      //element to with the moveToElement()
      Actions a = new Actions(driver);
      a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).
      doubleClick().
      build().perform();
      driver.quit();
   }
}
Count the number of elements in a HashSet in Java

To count the number of elements in a HashSet, use the size() method.
Create HashSet −
String strArr[] = { "P", "Q", "R" };
Set s = new HashSet(Arrays.asList(strArr));
Let us now count the number of elements in the above Set −
s.size()
The following is an example to count the number of elements in a HashSet −
 Live Demo
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      String strArr[] = { "P", "Q", "R" };
      Set s = new HashSet(Arrays.asList(strArr));
      System.out.println("Elements: "+s);
      System.out.println("Number of Elements: "+s.size());
   }
}
Elements: [P, Q, R]
Number of Elements: 3
Let us see another example −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println("Elements: "+hs);
      System.out.println("Number of Elements: "+hs.size());
   }
}
Elements: [A, B, C, D, E, F, K, M, N]
Number of Elements: 9
How can we set the margin to a JButton in Java?

A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonMarginTest extends JFrame {
   private JButton button;
   public JButtonMarginTest() {
      setTitle("JButtonMargin Test");
      setLayout(new BorderLayout());
      button = new JButton("JButton Margin");
      button.setMargin(new Insets(50, 50, 50, 50));
      add(button, BorderLayout.NORTH);
      setSize(400, 400);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonMarginTest();
   }
}
Visualizing multi dimensional arrays | by Nayantara Jeyaraj (Taro) | Towards Data Science

If you asked my opinion about Multidimensional arrays, 5 or 6 years ago, I would have said that they were the most simplistic concept to grasp but the most complicated to implement since the above “architectural marvel” is what pops into my mind as soon as I think of a Multidimensional Array.
That was ages ago before I discovered the most easiest way, as easy as understanding 1+1 = 2, to implement them. Well, though some of you may already be well aware and this might sound like a trivial task, there is a percentage that needs clarification in this concept like I did years ago. So buckle up, here we go.
Let’s start off with the very basics. What’s an Array?
The primitive definition of arrays simply stated that
Arrays were a storage medium that could hold a fixed number of values of a single type
While this is partially true, it not the case anymore. Considering the programming language that I’ve chosen at hand, I think we can expand this definition and modify it to new levels.
JavaScript provides the ever so useful feature of allowing arrays that can be dynamically created, meaning that the size of the array can be decided at a later time and doesn’t even have to be fixed. It can be modified, either incremented or decremented, as the number data to be stored to the array changes.
Well, we all might have noted this dynamism of creating linear one dimensional or two dimensional arrays at some point. So let’s step into creating multi dimensional arrays.
A multidimensional array, in my opinion is an array within an array. Let’s discuss the an array using a table to visualize this easily.
Imagine that you have a simple table where you need to store Student Details such as Name, Age, Grade and Subjects offered. Now, since we have to store details of many students, it might be obvious that this is already a two dimensional array where the above details will be mapped in the following manner.
Upto a certain level this table might seem to be sufficient to grab info from. But, it will be considered to be much cleaner and efficient if the last column, that saves the ‘Subjects Offered’ ,was also subdivided as shown below.
This provides us the privilege of manipulating details of these sub- disciplines of the subjects as well. So, how do we implement this?
Let’s call the array that maps the above Student Details as “studentArray”. And we’ll be creating the skeleton for this array.
var noOfStudentRecords=100;var noOfColumns = 4;var studentArray = [];for(var x = 0; x < noOfStudentRecords; x++){    studentArray[x] = [];    for(var y = 0; y < noOfColumns; y++)    {        if(y==3)        {            studentArray[x][y]= new Array[3];        }    }}
In the above code, we specify the third column as a new array : hence, an array within another array creating a multidimensional array.
This is a very basic explanation of creating multidimensional arrays. In more complex situations, we can split these individual subjects into further categories to host additional details, applying the same concept as above, just on a different dimension.
Kubernetes - Service

A service can be defined as a logical set of pods. It can be defined as an abstraction on the top of the pod which provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps pods to scale very easily.
A service is a REST object in Kubernetes whose definition can be posted to Kubernetes apiServer on the Kubernetes master to create a new instance.
apiVersion: v1
kind: Service
metadata:
   name: Tutorial_point_service
spec:
   ports:
   - port: 8080
   targetPort: 31999

The above configuration will create a service with the name Tutorial_point_service.
apiVersion: v1
kind: Service
metadata:
   name: Tutorial_point_service
spec:
   selector:
      application: "My Application" -------------------> (Selector)
   ports:
   - port: 8080
   targetPort: 31999

In this example, we have a selector; so in order to transfer traffic, we need to create an endpoint manually.
apiVersion: v1
kind: Endpoints
metadata:
   name: Tutorial_point_service
subnets:
   address:
      "ip": "192.168.168.40" -------------------> (Selector)
   ports:
      - port: 8080

In the above code, we have created an endpoint which will route the traffic to the endpoint defined as “192.168.168.40:8080”.
apiVersion: v1
kind: Service
metadata:
   name: Tutorial_point_service
spec:
   selector:
      application: “My Application” -------------------> (Selector)
   ClusterIP: 10.3.0.12
   ports:
      -name: http
      protocol: TCP
      port: 80
      targetPort: 31999
   -name:https
      Protocol: TCP
      Port: 443
      targetPort: 31998

ClusterIP − This helps in restricting the service within the cluster. It exposes the service within the defined Kubernetes cluster.
spec:
   type: NodePort
   ports:
   - port: 8080
      nodePort: 31999
      name: NodeportService

NodePort − It will expose the service on a static port on the deployed node. A ClusterIP service, to which NodePort service will route, is automatically created. The service can be accessed from outside the cluster using the NodeIP:nodePort.
spec:
   ports:
   - port: 8080
      nodePort: 31999
      name: NodeportService
      clusterIP: 10.20.30.40

Load Balancer − It uses cloud providers’ load balancer. NodePort and ClusterIP services are created automatically to which the external load balancer will route.
A full service yaml file with service type as Node Port. Try to create one yourself.
apiVersion: v1
kind: Service
metadata:
   name: appname
   labels:
      k8s-app: appname
spec:
   type: NodePort
   ports:
   - port: 8080
      nodePort: 31999
      name: omninginx
   selector:
      k8s-app: appname
      component: nginx
      env: env_name


    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
C - Input and Output

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to  read given input and feed it to the program as per requirement.
Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to  output required data.
Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions
This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ).
Try following program to understand printf() function.
#include <stdio.h>

main()
{
  int dec = 5;
  char str[] = "abc";
  char ch = 's';
  float pi = 3.14;

  printf("%d %s %f %c\n", dec, str, pi,  ch);
}

The output of the above would be:
       5 abc 3.140000 c

Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print  a float and %c is being used to print a character.
A complete syntax of printf() function is given in C - Built-in Functions

This is the function which can be used to to read an input from the command line.
Try following program to understand scanf() function.
#include <stdio.h>

main()
{
  int x;
  int args;

  printf("Enter an integer: ");
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
}

Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x.
This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.
Enter an integer: 20
Read in 20

A complete set of input output functions is given in C - Built-in Functions

Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
Annotate Text Outside of ggplot2 Plot in R - GeeksforGeeks

03 Mar, 2021
Ggplot2 is based on the grammar of graphics, the idea that you can build every graph from the same few components: a data set, a set of geoms—visual marks that represent data points, and a coordinate system. There are many scenarios where we need to annotate outside the plot area or specific area as per client requirements. In this case, the ggplot2 library comes very handy with its sub-options to get the required output and with good customization options for data visualizations. 
To add annotations in R using ggplot2, annotate() function is used.
Syntax: annotate() 
Parameters:
geom : specify text
x : x axis location
y : y axis location
label : custom textual content
color : color of textual content
size : size of text
fontface : fontface of text
angle : angle of text
Import library
Create or load dataset
Create a normal plot
Add annotate() function with required parameters
Let us first see how annotations are added inside the plot, so that the difference in position of the annotations can be understood better.
Examples : 
R
library(ggplot2)  Dt = iris  ggplot(Dt,aes(x=Species,y=Sepal.Length)) +  geom_bar(stat = "summary", fun = "mean") +  annotate("text", x = 1, y = 7, label = "Arbitrary text") + coord_cartesian(ylim = c(0, 8), clip = "off")
Output:
Now let us visualize with annotations outside the plot.
Example:
R
library(ggplot2)  Dt = iris  ggplot(Dt,aes(x=Species,y=Sepal.Length)) +  geom_bar(stat = "summary", fun = "mean") +  annotate("text", x = 1, y = -1, label = "text") +  coord_cartesian(ylim = c(0, 8), clip = "off")
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
BeautifulSoup - Append to the contents of tag - GeeksforGeeks

25 Feb, 2021
Prerequisites: Beautifulsoup
Beautifulsoup is a Python library used to extract the contents from the webpages. It is used in extracting the contents from HTML and XML structures. To use this library, we need to install it first. Here we are going to append the text to the existing contents of tag. We will do this with the help of the BeautifulSoup library.
Approach
Import module
Open HTML file
Read contents
Append content to the required tag
Save changes to the file
Function used:
Append function of the Beautifulsoup module is used to append content to desired tags.
Syntax:
append(“<string>”
File Used:
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Append </title></head><body>    <h1>Append to the </h1>      <p>We are going to append to the contents using </p>      <a href="https://www.geeksforgeeks.org/">Geeks For </a></body></html>
Python Code: 
Python3
# Python program to append to the contents of tag  # Importing libraryfrom bs4 import BeautifulSoup  # Opening and reading the html filefile = open("gfg.html", "r")contents = file.read()  soup = BeautifulSoup(contents, "lxml")  # Appending to the contents of 'title' tag in html fileprint("Current content in title tag is:-")print(soup.title)soup.title.append("Using BS")print("Content after appending is:-")print(soup.title)  print("\n")  # Appending to the contents of 'h1' tag in html fileprint("Current content in heading h1 tag is:-")print(soup.h1)soup.h1.append("contents of tag")print("Content after appending is:-")print(soup.h1)  print("\n")  # Appending to the contents of 'p' tag in html fileprint("Current content in paragraph p tag is:-")print(soup.p)soup.p.append("BeautifulSoup library")print("Content after appending is:-")print(soup.p)  print("\n")  # Appending to the contents of 'a' tag in html fileprint("Current content in anchor a tag is:-")print(soup.a)soup.a.append("Geeks Website")print("Content after appending is:-")print(soup.a)  # Code to save the changes in 'output.html' filesavechanges = soup.prettify("utf-8")with open("output.html", "wb") as file:    file.write(savechanges)
Output:
output.html file
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Operators | Question 1 - GeeksforGeeks

28 Jun, 2021
What is the output of the following code :
print 9//2
(A) 4.5(B) 4.0(C) 4(D) ErrorAnswer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number.Quiz of this QuestionPlease comment below if you find anything wrong in the above post
amartyaghoshgfg
Operators
Python-Operators
Python-Quizzes
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python-Quizzes | Python Dictionary Quiz | Question 23
Python-Quizzes | Python Tuples Quiz | Question 10
Python | Miscellaneous | Question 4
Python | Output Type | Question 3
Python-Quizzes | Python List Quiz | Question 22
Why do people prefer Selenium with Python?
Python-Quizzes | Python String Quiz | Question 4
Python | Miscellaneous | Question 3
Python | Animated Banner showing 'GeeksForGeeks'
Python | Miscellaneous | Question 6
Create Battery Notifier for Laptop using Python - GeeksforGeeks

09 Mar, 2021
Laptop or P.C battery charging is always a tension. We often forget to charge our laptop and seem to check the battery. This article demonstrates how to create a simple Battery Notifier application using Python. A battery notifier is a simple application that produces a notification message in the form of a pop-up message on the desktop.  With Python, we can do so with the help of psutil library and plyer library.
psutil(python system and process utilities): It is a cross-platform for retrieving information on running processes and system utilization in python
pip install psutil
plyer: Plyer module is used to access the features of the hardware. This module does not comes built-in with Python. We need to install it externally. To install this module type the below command in the terminal.
pip install plyer
Approach:
Step 1) Import the notification class from the plyer module
from plyer import notification
Step 2) After that you just need to call the notify method of this class.
Syntax: notify(title=”, message=”, app_name=”, app_icon=”, timeout=10, ticker=”, toast=False)
Parameters:
title (str) – Title of the notification
message (str) – Message of the notification
app_name (str) – Name of the app launching this notification
app_icon (str) – Icon to be displayed along with the message
timeout (int) – time to display the message for, defaults to 10
ticker (str) – text to display on status bar as the notification arrives
toast (bool) – simple Android message instead of full notification
Step 3) Add the sleep function to show that notification again.
Below is the implementation.
Python3
import psutilfrom plyer import notificationimport time   # from psutil we will import the# sensors_battery class and with# that we have the battery remainingwhile(True):    battery = psutil.sensors_battery()    percent = battery.percent         notification.notify(        title="Battery Percentage",        message=str(percent)+"% Battery remaining",        timeout=10    )         # after every 60 mins it will show the    # battery percentage    time.sleep(60*60)         continue
  
Output:
 
Note: The time in the sleep function has been reduced to record the output window. 
abhigoya
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How to simulate scanf() method using Python?

Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf()format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.
To extract the filename and numbers from a string like
/usr/sbin/sendmail - 0 errors, 4 warnings
you would use a scanf() format like
%s - %d errors, %d warnings
The equivalent regular expression would be
(\S+) - (\d+) errors, (\d+) warnings