code-rag-bench/online-tutorials huggingface dataset:
Importance of clone() method in Java?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.
We will get a CloneNotSupportedException if we try to call the clone() method on an object of a class that doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.
protected Object clone() throws CloneNotSupportedException
We can implement the clone() method in two ways
This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. In the case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references get copied and not the referred objects.
public class ShallowCopyTest {
   public static void main(String args[]) {
      A a1 = new A();
      A a2 = (A) a1.clone();
      a1.sb.append("Tutorialspoint!");
      System.out.println(a1);
      System.out.println(a2);
   }
}
class A implements Cloneable {
   public StringBuffer sb = new StringBuffer("Welcome to ");
      public String toString() {
         return sb.toString();
      }
   public Object clone() {
      try {
         return super.clone();
      } catch(CloneNotSupportedException e) {
      }
      return null;
   }
}
Welcome to Tutorialspoint!
Welcome to Tutorialspoint!
We need to override the clone() method for the classes having non-primitive type members to achieve Deep Copy as it requires the member objects to be cloned as well, which is not done by the default cloning mechanism.
public class DeepCopyTest {
   public static void main(String args[]) {
      A a1 = new A();
      A a2 = (A) a1.clone();
      a1.sb.append(" TutorialsPoint!");
      System.out.println(a1);
      System.out.println(a2);
   }
}
class A implements Cloneable {
   public StringBuffer sb = new StringBuffer("Welcome to ");
   public String toString() {
      return sb.toString();
   }
   public Object clone() {
      try {
         A a = (A) super.clone();
         a.sb = new StringBuffer(sb.toString());
         return a;
      }
      catch(CloneNotSupportedException e) {
      }
      return null;
   }
}
Welcome to TutorialsPoint!
Welcome to
How can we remove a selected row from a JTable in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class.
public void removeRow(int row)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveSelectedRowTest extends JFrame {
   private JTable table;
   private DefaultTableModel model;
   private Object[][] data;
   private String[] columnNames;
   private JButton button;
   public RemoveSelectedRowTest() {
      setTitle("RemoveSelectedRow Test");
      data = new Object[][] {{"101", "Ramesh"}, {"102", "Adithya"}, {"103", "Jai"}, {"104", "Sai"}};
      columnNames = new String[] {"ID", "Name"};
      model = new DefaultTableModel(data, columnNames);
      table = new JTable(model);
      table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
      button = new JButton("Remove");
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent ae) {
            // check for selected row first
            if(table.getSelectedRow() != -1) {
               // remove selected row from the model
               model.removeRow(table.getSelectedRow());
               JOptionPane.showMessageDialog(null, "Selected row deleted successfully");
            }
         }
      });
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(button, BorderLayout.SOUTH);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(400, 300);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new RemoveSelectedRowTest();
   }
}
Install Anaconda on MacOS Big Sur | by Alice Zhao | Towards Data Science

I got a new MacBook Pro today and one of the first things I installed was Anaconda, which currently comes with Python 3.8. Unforutantely, I ran into issues when I tried to use conda commands in the Terminal. This post walks through how to resolve those issues and start using Anaconda on Big Sur.
Anaconda Installation StepsThe Problem (zsh: command not found: conda)The Solution
Anaconda Installation Steps
The Problem (zsh: command not found: conda)
The Solution
You can skip this section if you’ve already installed Anaconda on your laptop.
Go to the Anaconda installation page. Scroll down to the Anaconda Installers section and click on the Graphical Installer under MacOS.
Once you finish downloading the installer onto your laptop, double click on the icon and keep on clicking Continue until you reach the end. If you’ve successfully installed Anaconda, you should see the Anaconda Navigator icon in your Applications.
After the install, I went to the Terminal, typed conda list and got my first error on my new laptop. 😭
zsh: command not found: conda
You would think that with a successful installation, conda commands should work in the Terminal. However, zsh is the new default shell on MacOS and you need to run two extra lines of code to make things work.
Here’s what my Terminal looked like when I got the error:
alice@Alices-MacBook-Pro ~ % conda listzsh: command not found: conda
Here’s what I typed in the Terminal to resolve the error (line 1 of 2):
source /opt/anaconda3/bin/activate
NOTE: I did the Graphical Installation of Anaconda and it put the anaconda3 folder within the /opt folder. If your anaconda3 folder happens to be somewhere else after your install, like the home directory for example, you would type source ~/anaconda3/bin/activate instead, with ~ meaning home directory.
Here’s the second line I typed in the Terminal (line 2 of 2):
conda init zsh
Close the Terminal window. When you open it back up again, you should see the little (base) prefix to tell you that you’re in the default base environment in Anaconda and you are all set! 🎉
(base) alice@Alices-MacBook-Pro ~ %
NOTE: I found many articles online saying to update the PATH variable, but Anaconda actually recommends against doing so and running the two commands above instead, which they state in their documentation.
Python NLTK | tokenize.WordPunctTokenizer()

30 Sep, 2019
With the help of nltk.tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from string of words or sentences in the form of Alphabetic and Non-Alphabetic character by using tokenize.WordPunctTokenizer()() method.
Syntax : tokenize.WordPunctTokenizer()()Return : Return the tokens from a string of alphabetic or non-alphabetic character.
Example #1 :In this example we can see that by using tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from stream of alphabetic or non-alphabetic character.
# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer     # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer()     # Create a string inputgfg = "GeeksforGeeks...$$&* \nis\t for geeks"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘GeeksforGeeks’, ‘...$$&*’, ‘is’, ‘for’, ‘geeks’]
Example #2 :
# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer     # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer()     # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs’, ‘.’, ’36’, ‘.’]
shubham_singh
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
GATE | GATE-CS-2017 (Set 1) | Question 16

22 Jul, 2021
Consider the following CPU processes with arrival times (in milliseconds) and length of CPU bursts (in milliseconds) as given below:
If the pre-emptive shortest remaining time first scheduling algorithm is used to schedule the processes, then the average waiting time across all processes is _______ milliseconds.
Note: This questions appeared as Numerical Answer Type.(A) 1(B) 2(C) 3(D) 4Answer: (C)Explanation: 
Turn Around Time
P1  = 12-0 = 12
P2 = 6-3 = 3
P3 = 17-5 = 12
P4 = 8 - 6 = 2

Waiting Time
P1  = 12-7 = 5
P2 = 3-3 = 0
P3 = 12-5 = 7
P4 = 2 - 2 = 0

Average Waiting time = (7+0+5+0)/4 = 3.0
Therefore, option C is correct
Alternate Solution
Given, with arrival time and burst time:
Using (preemptive) shortest remaining time first algorithm, gantt chart is:
Therefore,Average waiting time = ( 5 + 0 + 7 + 0 ) / 4 = 12 / 4 = 3
This explanation has been contributed by Mithlesh Upadhyay.
Watch GeeksforGeeks Video Explanation :
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
Normal Probability Plot in R using ggplot2

14 Jan, 2022
A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line.
In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only.
Install the following necessary libraries by pasting them in r console
install.packages(“ggplot2”)
install.packages(“qqplotr”)
Create a random data set with a different mean and standard deviation that you want to plot.
Plotting data using stat_qq_point() method.
Plotting data points with line using stat_qq_line() function.
Given below is a proper implementation using the above approach 
Example 1: Plotting data using stat_qq_point() method.
R
# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data without line and labelsggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2)
Output:
Fig. 1 Plotting Data points.
Example 2: Plotting data points with line using stat_qq_line() function.
R
# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data with proper labels# And adding line with proper propertiesggplot(mapping = aes(sample = random_values))+ stat_qq_point(size = 2,color = "red")+ stat_qq_line(color="green")+ xlab("x-axis") + ylab("y-axis")
Output:
Fig. 2 Adding normal line
adnanirshad158
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add or Remove class in jQuery ?

10 Aug, 2021
The addClass() or removeClass() methods are used to add the CSS classes when there is a need to add to our webpage when there is some event listener or to create some kind of effect.
In this article, let us see how can we add a CSS class or remove a CSS class in jQuery.
Syntax:
Adding a class:$('selector').addClass(class_name);
$('selector').addClass(class_name);
Removing a class:$('selector').removeClass(class_name);
$('selector').removeClass(class_name);
Example: The following example adds a class that makes the background colour black when clicked on ADD CLASS button and also removes that added class when clicked on the REMOVE CLASS button.
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">      <!-- Including jQuery  -->    <script src=        "https://code.jquery.com/jquery-3.6.0.min.js"         integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="        crossorigin="anonymous">    </script>      <style>        h1 {            color: #006600;        }                  button {            color: white;            background-color: #006600;            width: auto;            height: 30px;        }                  body {            text-align: center;        }                  div {            margin: 10px;            height: 150px;            width: 150px;            position: relative;            text-align: center;            display: flex;            left: 215px;        }                  .bg-black {            background-color: black;        }    </style></head>  <body>    <h1>Geeks For Geeks</h1>      <button id="btnadd"> ADD CLASS </button>    <button id="btnremove"> REMOVE CLASS </button>        <div id="GFG_IMAGE">          <!-- Image added using img tag             with src attribute -->        <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"            height='150px' width='150px'>        <img>    </div>      <script>        $(document).ready(function() {            $('#btnadd').click(function() {                $('img').addClass('bg-black');            });            $('#btnremove').click(function() {                $('img').removeClass('bg-black');            });        });    </script></body>  </html>
Output:
Add class and remove class
CSS-Properties
jQuery-Methods
jQuery-Questions
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
GATE-CS-2005 - GeeksforGeeks

11 Oct, 2021
int ( * f) (int * )
f * (int * ) int
It is a lattice but not a distributive lattice.

Table for Join Operation of above Hesse diagram

V |a b c d e
________________
a |a a a a a
b |a b a a b
c |a a c a c
d |a a a d d
e |a b c d e

Table for Meet Operation of above Hesse diagram

^ |a b c d e
_______________
a |a b c d e
b |b b e e e
c |c e c e e
d |d e e d e
e |e e e e e

Therefore for any two element p, q in the lattice (A,<=)

p <= p V q ; p^q <= p

This satisfies for all element (a,b,c,d,e).

which has 'a' as unique least upper bound and 'e' as unique 
greatest lower bound.

The given lattice doesn't obey distributive law, so it is 
not distributive lattice,

Note that for b,c,d we have distributive law

b^(cVd) = (b^c) V (b^d). From the diagram / tables given above 
we can verify as follows,

(i) L.H.S. = b ^ (c V d) = b ^ a = b

(ii) R.H.S. = (b^c) V (b^d) = e v e = e

b != e which contradict the distributive law. 
Hence it is not distributive lattice.

so, option (B) is correct. 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Split given String into substrings of size K by filling elements
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Software Testing Metrics, its Types and Example
Software Testing - Boundary Value Analysis
TCS NQT Coding Sheet
Python Program to Print Numbers in an Interval

11 May, 2020
Given a range of numbers, find all the numbers between them.
Input : l = 2, u = 5Output : 2 3 4 5
Input : l = 10, u = 20Output : 10 11 12 13 14 15 16 17 18 19 20
The idea is to use range function in Python.
# Python program to print all the numbers within an intervall = 10u = 20  for num in range(l, u + 1):    print(num)
10
11
12
13
14
15
16
17
18
19
20

We can also print alternate numbers or numbers with given steps.
# Python program to print all EVEN numbers within an intervall = 10u = 20if l%2==0:    for num in range(l, u + 1, 2):        print(num)else:    for num in range(l+1, u + 1, 2):        print(num)
10
12
14
16
18
20

ajeetkjnp68
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Object Oriented Programming in C++
What is Three dots(...) or Ellipsis in Python3

05 Sep, 2020
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e, provides easy access to single instances.
Various Use Cases of Ellipsis (...):
Default Secondary Prompt in Python interpreter.
Accessing and slicing multidimensional Arrays/NumPy indexing.
In type hinting.
Used as Pass Statement inside Functions.
Ellipsis notation[...] is used as a default secondary prompt in Python interpreter which is seen during multi-line constructs
Example:
Accessing: Giving access to a specified range of elements, just omitting out the serial indices.
Slicing: Important use of Ellipsis is in slicing higher-dimensional data structures.
Example:
Suppose, we have a 4-dimensional matrix of order 2x2x2x2. To select all first row elements(in case of row-major structure) in the 4th dimension, we can simply use the ellipsis notation
Python3
# importing numpyimport numpy as np  array = np.random.rand(2, 2, 2, 2)print(array[..., 0])print(array[Ellipsis, 0])
Output:
[[[0.46253663 0.03092289]
  [0.72723607 0.75953107]]

 [[0.33160093 0.79259324]
  [0.76757812 0.21241883]]]
[[[0.46253663 0.03092289]
  [0.72723607 0.75953107]]

 [[0.33160093 0.79259324]
  [0.76757812 0.21241883]]]

In the above example, [:, :, :, 0], [..., 0] and [Ellipsis, 0] are all equivalent.
We can not have multiple ellipsis in a single slicing like a[...,index,...]
Ellipsis is used in specifying type hints using the typing module (e.g. Callable[..., str]). It can serve in either way:
Method 1: When the argument(s) of the function allows the type: Any
Actually callable takes the arguments: 
Callable "[" parameters_expression, type_expression "]"

(e.g. Callable[..., str]) 
Example:
Python3
from typing import Callable  def inject(get_next_item: Callable[..., str]) -> None:            ...# Argument type is assumed as type: Anydef foo(x: ...) -> None:              ...
Using ‘...’ as parameters_expression signifies a function that returns a string without specifying the call signature.
Method 2: When the return value of the function is of type: Any  
Actually callable returns this way:
Callable "[" parameters_expression, type_expression "]" -> return_type: #body

Example:
Python3
class flow:        # (using "value: Any" to allow arbitrary types)    def __understand__(self, name: str, value: ...) -> None: ...
  
Ellipsis is used instead of pass statement inside functions. ‘pass’ replaced by ‘...’ or ‘Ellipsis’. 
Example:
Python3
# style1def foo():    pass# style2def foo():    ...# both the styles are same
Ellipsis can also be used as a default argument value. Especially when you want to distinguish between not passing in value and passing in None.
Example: 
Python3
def foo(x = ...):    return x  print(foo)
Output:
<function foo at 0x7fabdeea6e18>

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select all links inside the paragraph using jQuery ?

06 Sep, 2021
In this article, we will see how to write code to select all links inside the paragraph using jQuery. To select all links inside paragraph element, we use parent descendant selector. This selector is used to selects every element that are descendant to a specific (parent) element.
Syntax:
$("parent descendant")
Approach: Here, we have created links and content inside paragraph element. After that, we use $(“p a”) selector to select all links inside paragraph element and changes its style using css() method.
 
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>        jQuery code to select all         links inside the paragraph    </title>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>      <style>        body {            text-align: center;            font-size: 30px;        }                  button {            background-color: green;            color: white;            border: none;            font-size: 24px;            border-radius: 5px;            padding: 15px 32px;            text-align: center;            text-decoration: none;            display: inline-block;        }                  a {            text-decoration: none;        }    </style>      <script>        $(document).ready(function() {            $("button").click(function() {                $("p a").css({                    color: "white",                    background: "green"                });            });        });    </script></head>  <body>    <h1 style="color:green">        GeeksforGeeks    </h1>      <h3>        jQuery code to select all         links inside the paragraph    </h3>      <p>        <a href="#">GeeksforGeeks</a> is a         computer science <br>portal where         you can learn <a href="#">HTML</a>,        <a href="#">CSS</a>, <br><a href="#">        JavaScript</a>, etc.    </p>      <button>        Click Here    </button></body>  </html>
Output:
CSS-Properties
jQuery-Questions
jQuery-Selectors
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
How to convert an array into JavaScript string?

To convert an array into JavaScript string, use the toString() method. JavaScript array toString() method returns a string representing the source code of the specified array and its elements.
You can try to run the following code to convert an array into a string −
Live Demo
<html>
   <head>
      <title>JavaScript Array toString Method</title>
   </head>
   <body>
      <script>
         var arr = new Array("time", "money", "work");
         var str = arr.toString();
         document.write("Returned string is : " + str );
      </script>
   </body>
</html>
Returned string is : time,money,work
Constrain a number within a given range in Arduino

The constrain() function in Arduino helps to, as the name suggests, constrain a number between an upper bound and a lower bound.
constrain(val, min, max)
where, val is the number to be constrained, min is the lower bound value, and max is the upper bound value
If val is less than min, this function will return min. If val is greater than max, this function will return max. As long as val is between min and max, this function will return val.
The following example illustrates the use of this function −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   int a = 200;
   Serial.println(constrain(a, 5, 210));
   Serial.println(constrain(a, 300, 400));
   Serial.println(constrain(a, 100, 150));
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, in the first case, the integer a was within bounds, so it got returned. In the second case, a was less than the lower bound, hence the lower bound got returned, and in the third case, a was higher than the upper bound, hence the upper bound was returned.
Please note that as per Arduino’s documentation (https://www.arduino.cc/reference/en/language/functions/math/constrain/) it is recommended to avoid using another function within constrain.
This constrain (analogRead(A0), 10,50); may yield incorrect results. Instead, you can try −
int a = analogRead(A0);
int a_constr = constrain(a, 10, 50);
Program to print solid and hollow square patterns in C

In geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles.
Solid and Hollow Square will appear as shown below
For Solid Square −
Accept the Number of Rows from the user to draw the Solid Square
For each Row, Print * for each Column to draw the Solid Square
For Hollow Square −
Accept the Number of Rows from the user to draw the Hollow Square
For the First and Last Row, Print * for each Column
For the Remaining Rows, Print * for the first and Last Column.
/* Program to print hollow and Solid Square pattern */
#include <stdio.h>
int main(){
   int r, c, rows; //Hollow Rhombus
   int r1,c1, rows1; //Solid Rhombus
   clrscr();
   /* Hollow Square */
   printf("Enter the Number of rows for Hollow Square: ");
   scanf("%d", &rows);
   printf("\n");
   for (r=1; r<=rows; r++){
      if (r==1 || r==rows){
         for (c=1; c<=rows; c++){
            printf("*");
         }
      }
      else{
         for (c=1; c<=rows; c++){
            if (c==1 || c==rows){
               printf("*");
            }
            else{
               printf(" ");
            }
         }
      }
      printf("\n");
   }
   printf("\n");
   /* Solid Square */
   printf("Enter the Number of rows for Solid Square: ");
   scanf("%d", &rows1);
   printf("\n");
   for (r1=1; r1<=rows1; r1++){
      for (c1=1; c1<=rows1; c1++){
         printf("*");
      }
      printf("\n");
   }
   getch();
   return 0;
}
Find all the numbers in a string using regular expression in Python

29 Dec, 2020
Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression.
Examples:
Input: abcd11gdf15hnnn678hh4Output: 11 15 678 4
Input: 1abcd133hhe0Output: 1 133 0
Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This pattern will extract all the characters which match from 0 to 9 and the + sign indicates one or more occurrence of the continuous characters.
Below is the implementation of the above approach:
# Python3 program to extract all the numbers from a stringimport re  # Function to extract all the numbers from the given stringdef getNumbers(str):    array = re.findall(r'[0-9]+', str)    return array  # Driver codestr = "adbv345hj43hvb42"array = getNumbers(str)print(*array)
345 43 42

Python Regex-programs
python-regex
Arrays
Python
Python Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Read JSON file using Python
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
How to create footer to stay at the bottom of a Web page?

30 Jul, 2021
To create a footer to stay at the bottom of a web page We can fix the position of it at the bottom of the webpage so that, if you scroll down that webpage you can still view the footer from any position at the page.To make a footer fixed at the bottom of the webpage, you could use position: fixed.
Syntax:
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;   /* Height of the footer */
   background:#6cf;
}

Example:
<html>  <head>    <style>        #footer {            position: fixed;            padding: 10px 10px 0px 10px;            bottom: 0;            width: 100%;            /* Height of the footer*/             height: 40px;            background: grey;        }    </style>      <head>          <body>            <center>                <div id="container">                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <h1>GeeksforGeeks</h1>                    <div id="footer">This is a footer.                      This stays at the bottom of the page.                  </div>                </div>            </center>        </body>        <html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to Upload Image into Database and Display it using PHP ?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Node.js Process unhandledPromiseRejection Event

03 Nov, 2021
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine.
The unhandledRejection event is emitted whenever a promise rejection is not handled. NodeJS warns the console about UnhandledPromiseRejectionWarning and immediately terminates the process. The NodeJS process global has an unhandledRejection event. This event is fire when unhandledRejection occurs and no handler to handle it in the promise chain. 
Syntax:
process.on("unhandledRejection", callbackfunction)
Parameters: This method takes the following two parameters.
unhandledRejection: It is the name of the emit event in the process.
callbackfunction: It is the event handler of the event.
Return Type: The return type of this method is void.
Example 1: Basic example to register an unhandledRejection listener. 
index.js
// The unhandledRejection listenerprocess.on('unhandledRejection', error => {    console.error('unhandledRejection', error);});  // Reject a promisePromise.reject('Invalid password');
Run index.js file using the following command:
node index.js
Output:
unhandledRejection Invalid password
Example 2: To demonstrate that the unhandledRejection listener will only execute when there is no promise rejection handler in your chain. 
index.js
// The unhandledRejection listenerprocess.on('unhandledRejection', error => {    // Won't execute    console.error('unhandledRejection', error);});  // Reject a promisePromise.reject('Invalid password')    .catch(err => console.error(err))
Run index.js file using the following command:
node index.js
Output:
Invalid password
Note: If you handle unhandledRejection with the listener or consumer function then the default warning to the console (the UnhandledPromiseRejectionWarning from the above examples) will not print to the console. 
Reference: https://nodejs.org/api/process.html#process_event_unhandledrejection
simmytarika5
NodeJS-Process
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Delete a column from a Pandas DataFrame

17 Jan, 2022
Deletion is one of the primary operations when it comes to data analysis. Very often we see that a particular attribute in the data frame is not at all useful for us while working on a specific analysis, rather having it may lead to problems and unnecessary change in the prediction. For example, if we want to analyze the students’ BMI of a particular school, then there is no need to have the religion column/attribute for the students, so we prefer to delete the column. Let us now see the syntax of deleting a column from a dataframe.Syntax:  
del df['column_name']
Let us now see few examples:Example 1:  
Python3
# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Name': ['Rutuja', 'Anuja'],         'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df)display("Original DataFrame")display(df) # deleting a columndel df['Age'] display("DataFrame after deletion")display(df)
Output :  
Note the column ‘Age” has been dropped.Example 2:  
Python3
# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Students': ['A', 'B', 'C', 'D'],         'BMI': [22.7, 18.0, 21.4, 24.1],         'Religion': ['Hindu', 'Islam',                      'Christian', 'Sikh']}df = pd.DataFrame(my_df)display("Original DataFrame")display(df) # deleting a columndel df['Religion'] display("DataFrame after deletion")display(df)
Output :  
Note that the unnecessary column, ‘Religion’ has been deleted successfully. 
saurabh1990aror
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
HTML DOM getElementById() Method

25 Nov, 2021
The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null. The element is required to have a unique id, in order to get access to that specific element quickly, & also that particular id should only be used once in the entire document.
Syntax:
document.getElementById( element_ID )
Parameter: This function accepts single parameter element_ID which is used to hold the ID of the element.
Return Value: It returns the object of the given ID. If no element exists with the given ID then it returns null.
Example 1: This example describes the getElementById() method where element_id is used to change the color of the text on clicking the button.
HTML
<!DOCTYPE html><html>  <head>    <title>        DOM getElementById() Method    </title>      <script>          // Function to change the color of element        function geeks() {            var demo = document.getElementById("geeks");            demo.style.color = "green";        }    </script></head>  <body style="text-align:center">    <h1 id="geeks">GeeksforGeeks</h1>    <h2>DOM getElementById() Method</h2>      <!-- Click on the button to change color -->    <input type="button"            onclick="geeks()"            value="Click here to change color" /></body>  </html>
Output:
getElementById() Method
Example 2: This example describes the getElementById() method where the element_id is used to change the content on clicking the button.
HTML
<!DOCTYPE html><html>  <head>    <title>        DOM getElementById() Method    </title>      <script>          // Function to change content of element        function geeks() {            var demo = document.getElementById("geeks");            demo.innerHTML = "Welcome to GeeksforGeeks!";        }    </script></head>  <body style="text-align:center">    <h1>GeeksforGeeks</h1>    <h2>DOM getElementById() Method</h2>    <h3 id="geeks">Hello Geeks!</h3>      <!-- Click here to change content -->    <input type="button"            onclick="geeks()"            value="Click here to change content" /></body>  </html>
Output:
getElementById() Method
Supported Browsers: The browser supported by DOM getElementById() method are listed below:
Google Chrome 1.0
Internet Explorer 5.5
Microsoft Edge 12.0
Firefox 1.0
Opera 7.0
Safari 1.0
bhaskargeeksforgeeks
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Initialize a dictionary with only keys from a list

15 Feb, 2019
Given a List, the task is to create a dictionary with only keys by using given list as keys.
Let’s see the different methods we can do this task.
Method #1 : By iterating through list
# Python code to initialize a dictionary# with only keys from a list  # List of keyskeyList = ["Paras", "Jain", "Cyware"]  # initialize dictionaryd = {}  # iterating through the elements of listfor i in keyList:    d[i] = None      print(d)
{'Cyware': None, 'Paras': None, 'Jain': None}

 Method #2 : Using dictionary comprehension
# Python code to initialize a dictionary# with only keys from a list  # List of KeyskeyList = ["Paras", "Jain", "Cyware"]  # Using Dictionary comprehensionmyDict = {key: None for key in keyList}print(myDict)
{'Paras': None, 'Jain': None, 'Cyware': None}

 Method #3 : Using zip() function
# Python code to initialize a dictionary# with only keys from a list  # List of keyslistKeys = ["Paras", "Jain", "Cyware"]  # using zip() function to create a dictionary# with keys and same length None value dct = dict(zip(listKeys, [None]*len(listKeys)))  # print dictprint(dct)
{'Cyware': None, 'Paras': None, 'Jain': None}

 Method #4 : Using fromkeys() method
# Python code to initialize a dictionary# with only keys from a list  # List of keysStudent = ["Paras", "Jain", "Cyware"]  # using fromkeys() methodStudentDict = dict.fromkeys(Student, None)  # printing dictionaryprint(StudentDict)
{'Cyware': None, 'Jain': None, 'Paras': None}

 
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to save files using a File Chooser in JavaFX?

Using JavaFX file chooser, you can open files browse through them and save the files. The class javafx.stage.FileChooser represents a file chooser, you can open a file dialog open single or multiple files using this. You can create a file chooser in your application by instantiating this class.
The showSaveDialog() method displays a save dialog which allows you to save a file and return it. This method returns null if you haven’t chosen any file
To save a file using JavaFX −
Instantiate the FileChooser class.
Instantiate the FileChooser class.
Set the required properties.
Set the required properties.
Invoke the showSaveDialog() method.
Invoke the showSaveDialog() method.
Add the file chooser to a root node.
Add the file chooser to a root node.
Add the root node to the scene object
Add the root node to the scene object
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.FileChooser.ExtensionFilter;
public class FileChooserSavingFile extends Application {
   @Override
   public void start(Stage stage) {
      ImageView imgView = new ImageView("UIControls/Save.png");
      imgView.setFitWidth(20);
      imgView.setFitHeight(20);
      Menu file = new Menu("File");
      MenuItem item = new MenuItem("Save", imgView);
      file.getItems().addAll(item);
      //Creating a File chooser
      FileChooser fileChooser = new FileChooser();
      fileChooser.setTitle("Save");
      fileChooser.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*.*"));
      //Adding action on the menu item
      item.setOnAction(new EventHandler<ActionEvent>() {
         public void handle(ActionEvent event) {
            //Opening a dialog box
            fileChooser.showSaveDialog(stage);
         }
      });
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(file);
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 355, Color.BEIGE);
      stage.setTitle("File Chooser Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
C++ ios Library - Uppercase Function

It is used to sets the uppercase format flag for the str stream. When the uppercase format flag is set, uppercase (capital) letters are used instead of lowercase for representations on output operations involving stream-generated letters, like some hexadecimal representations and numerical base prefixes.
Following is the declaration for std::uppercase function.
ios_base& uppercase (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::uppercase function.
#include <iostream>

int main () {
   std::cout << std::showbase << std::hex;
   std::cout << std::uppercase << 77 << '\n';
   std::cout << std::nouppercase << 77 << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
0X4D
0x4d

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML form elements
Tryit: input element
Add elements to a Dictionary in Javascript

Now we'll create the put method that'll allow us to put key-value pairs on the dictionary. Now using this we'll implement the put method.
Note that JS has objects that act quite like dictionaries. We can just set the container's key property to value. 
put(key, value) {
   this.container[key] = value;
}
You can test this and the previous functions using − 
const myMap = new MyMap()
myMap.put("key1", "value1")
myMap.put("key2", "value2")

myMap.display()

console.log(myMap.hasKey("key1"));
console.log(myMap.hasKey("key3"));
This will give the output −
{key1: "value1", key2: "value2"}
true
false
In ES6, you can put a key-value pair in a map using the set method. For example, 
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);

myMap.set("key3", "value3")

console.log(myMap.has("key1"))
console.log(myMap.has("key3"))
This will give the output −
True
True
How to stop the execution of a function with JavaScript?

To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.
You can try to run the following code to learn how to work with clearTimeout() method in JavaScript.
<html>
   <head>
      <title>JavaScript clearTimeout() method</title>
      <script>
         <!--
            var imgObj = null;
            var animate ;
           
            function init(){
               imgObj = document.getElementById('myImage');
               imgObj.style.position= 'relative';
               imgObj.style.left = '0px';
            }
            function moveRight(){
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
               animate = setTimeout(moveRight,20);    // call moveRight in 20msec
            }
            function stop(){
               clearTimeout(animate);
               imgObj.style.left = '0px';
            }
            window.onload = init;
         //-->
      </script>
   </head>
   <body>
      <form>
         <img id = "myImage" src = "/images/html.gif" />
         <p>Click the buttons below to handle animation</p>
         <input type = "button" value = "Start" onclick = "moveRight();" />
         <input type = "button" value = "Stop" onclick = "stop();" />
      </form>
   </body>
</html>
Python program to communicate between parent and child process using the pipe.

Using fork is the easiest way to create child process.fork () is part of the os standard Python library.
Here, we solve this task by using of pipe(). For passing information from one process to another pipe() is used. For two way communication two pipes can be use, one for each direction because pipe() is unidirectional.
Step 1: file descriptors r, w for reading and writing.
Step 2: Create a process using the fork.
Step 3: if process id is 0 then create a child process.
Step 4: else create parent process.

import os 
def parentchild(cwrites): 
   r, w = os.pipe() 
   pid = os.fork() 
   if pid: 
      os.close(w) 
      r = os.fdopen(r) 
      print ("Parent is reading") 
      str = r.read() 
      print( "Parent reads =", str) 
   else: 
      os.close(r) 
      w = os.fdopen (w, 'w') 
      print ("Child is writing") 
      w.write(cwrites) 
      print("Child writes = ",cwrites) 
      w.close() 
# Driver code         
cwrites = "Python Program"
parentchild(cwrites) 
Child is writing
Child writes = Python Program
Parent is reading
Parent reads = Python Program