code-rag-bench/online-tutorials huggingface dataset:
HTML DOM innerHTML Property

16 Jun, 2022
The DOM innerHTML property is used to set or return the HTML content of an element.
Syntax:
It returns the innerHTML Property.
Object.innerHTML
It is used to set the innerHTML property.
Object.innerHTML = value
Where,
value: It represents the text content of the HTML element.
Return Value: This property returns a string that represents the HTML content of an element.
Example 1: This example shows how to change the content of the paragraph tag using the innerHTML property. 
HTML
<!DOCTYPE html><html> <body style="text-align: center">    <h1 style="color:green">        GeeksforGeeks    </h1>    <h2>        DOM innerHTML Property    </h2>    <p id="p">GeeksforGeeks</p>      <button onclick="geek()">Click me!</button>    <script>    function geek() {        document.getElementById("p").innerHTML =        "A computer science portal for geeks.";    }    </script></body> </html>
Output:
innerHTML Property
Example 2: This example shows how to get the value of the paragraph tag using the innerHTML property.
HTML
<!DOCTYPE html><html> <body style="text-align: center">    <h1 style="color:green">        GeeksforGeeks    </h1>    <h2>        DOM innerHTML Property    </h2>    <p id="P">A computer science portal for geeks.</p>      <button onclick="geek()">Try it</button>    <p id="p"></p>           <script>    function geek() {        var x = document.getElementById("P").innerHTML;        document.getElementById("p").innerHTML = x;        document.getElementById("p").style.color = "green";    }    </script></body> </html>
Output:
innerHTML Property
Supported Browsers: The browser supported by DOM innerHTML property are listed below:
Google Chrome 33.0 and above
Internet Explorer 4 and above
Microsoft Edge 12.0 and above
Firefox 1.0 and above
Opera 8.0 and above
Safari 9.0 and above
simranarora5sos
bhaskargeeksforgeeks
kumargaurav97520
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 ?
How to plot excel data in R?

26 Mar, 2021
Plotting graph in R using an excel file, we need an excel file with two-column in it, the values in the first column will be considered as the points at the x-axis and the values in the second column will be considered as the points at the y-axis. In this article, we will be discussing the approach to plot a graph using an excel file in R language.
To import and read the excel file to the R console, the  read_excel() function from readxl library in R will be used. This function will read an excel-file available in your current working directory. To install the package of the readxl library in R the user must need to follow the following syntax in the R console.
Syntax:
install.packages(“readxl”) 
Data in use:
plot() function is used for plotting of R objects. With the provided parameters this function returns a scatter plot by default.
Syntax:
plot(x,y,main,xlab,ylab,sub,asp)
Parameters:
x:-the x coordinates of points in the plot
y:-the y coordinates of points in the plot
main:-an overall title for the plot
sub:-a subtitle for the plot
xlab:-a title for the x-axis
ylab:-a title for the y-axis
asp:-the y/x aspect ratio
Return:
Scatter plot of the given x and y values.
Approach
Import library
Import excel file
Read its data
Plot graph
Display plot
Example:
R
library(readxl)  Data_gfg <- read_excel("Data_gfg.xlsx")  plot(x = Data_gfg$x,y = Data_gfg$y,     xlab = "x-axis",     ylab = "y-axis",     main = "Plot")
Output:
Picked
R-Excel
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Creating a Pandas dataframe using list of tuples

06 Jan, 2019
We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use.
Code #1: Simply passing tuple to DataFrame constructor.
# import pandas to use pandas DataFrameimport pandas as pd  # data in the form of list of tuplesdata = [('Peter', 18, 7),        ('Riff', 15, 6),        ('John', 17, 8),        ('Michel', 18, 7),        ('Sheli', 17, 5) ]    # create DataFrame using datadf = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])  print(df) 
Output: Code #2: Using from_records()
import pandas as pd  # data in the form of list of tuplesdata = [('Peter', 18, 7),        ('Riff', 15, 6),        ('John', 17, 8),        ('Michel', 18, 7),        ('Sheli', 17, 5) ]    # create DataFrame using datadf = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score'])  print(df) 
Output: 
Code #3: Using from_items()
import pandas as pd  # data in the form of list of tuplesdata = [('Age', [18, 15, 17, 18, 17]),('Team', ['A', 'B', 'A', 'C', 'B']),('Score', [7, 6, 8, 7, 5]),]  # create DataFrame using datadf = pd.DataFrame.from_items(data)  print(df) 
Output: Code #4: For pivoting it possible.
# import pandas to use pandas DataFrameimport pandas as pd  # data in the form of list of tuplesdata = [('Peter', 18, 7),        ('Riff', 15, 6),    ('John', 17, 8),    ('Michel', 18, 7),    ('Sheli', 17, 5) ]    # create DataFrame using datadf = pd.DataFrame(data, columns =['Team', 'Age', 'Score'])  a = df.pivot('Team', 'Score','Age')print(a)
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
cd command in Linux with Examples

18 Aug, 2021
cd command in linux known as change directory command. It is used to change current working directory. 
Syntax:  
$ cd [directory]
To move inside a subdirectory : to move inside a subdirectory in linux we use 
$ cd [directory_name] 
In the above example, we have checked number of directories in our home directory and moved inside the Documents directory by using cd Documents command. 
Different functionalities of cd command : 
cd /: this command is used to change directory to the root directory, The root directory is the first directory in your filesystem hierarchy.  
$ cd /
Above, / represents the root directory.
cd dir_1/dir_2/dir_3: This command is used to move inside a directory from a directory  
$ cd dir_1/dir_2/dir_3
In above example, we have the document directory and inside the document directory we have a directory named geeksforgeeks and inside that directory we have example directory. To navigate example directory we have used command cd Documents/geeksforgeeks/example.
cd ~ : this command is used to change directory to the home directory.  
$ cd ~
              or 
$ cd 
cd : this command also work same as cd ~ command. 
cd .. : this command is used to move to the parent directory of current directory, or the directory one level up from the current directory. “..” represents parent directory.  
$ cd .. 
cd “dir name”: This command is used to navigate to a directory with white spaces.Instead of using double quotes we can use single quotes then also this command will work. 
$ cd "dir name"
In above example, we have navigated the My songs directory by using cd “My songs” command. or 
$ cd dir\ name :
this command work same as cd “dir name” command. 
simmytarika5
linux-command
Linux-directory-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How To Visualize Sparse Matrix in Python using Matplotlib?

27 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
Spy is a function used to visualize the array as an image similar to matplotlib imshow function, but it is used in case of sparse matrix instead of dense matrix. A sparse matrix is a matrix where most of the elements are zero.
Sparse matrix and its representation
Spy function uses two plotting styles to visualize the array, these are:
Image style
Marker style
Both the styles can be used for full arrays but in case of spmatrix instances only the marker style works. If marker or markersize is None then imshow function is used, and all the remaining keyword arguments are passed to this function; else, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot function.
Syntax: matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None, aspect=’equal’, origin=’upper’, \*\*kwargs)
Return value:
The return type depends on the plotting style, i.e. AxesImage or Line2D.
Parameters:
‘equal’: Ensures an aspect ratio of 1. Pixels will be square.
‘auto’: The axes is kept fixed and the aspect is adjusted so that the data fit in the axes. In general, this will result in non-square pixels.
None: Use rcParams[“image.aspect”]
Other parameters: **kwargs
These are the additional parameters that helps to get different plotting styles.
Example 1:
# Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np    x = np.random.randn(50, 50)  x[15, :] = 0.x[:, 40] = 0.  plt.spy(x)
Output:
Example 2:
# Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np  x = np.random.randn(50, 50)x[15, :] = 0.x[:, 40] = 0.  plt.spy(x, precision = 0.1, markersize = 5)
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Defaultdict in Python
Difference between Keyword and Identifier

23 May, 2022
Keywords: Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one! There are a total of 32 keywords in C:
   auto       break    case     char     const     continue
   default    do       double   else     enum      extern
   float      for      goto     if       int       long
   register   return   short    signed   sizeof    static
   struct     switch   typedef  union    unsigned  void
   volatile   while 
Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements. Difference between Keyword and Identifier:
mitalibhola94
C Basics
school-programming
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Differences and Applications of List, Tuple, Set and Dictionary in Python
Difference between DELETE and TRUNCATE
Difference between FDMA, TDMA and CDMA
Difference between MANET and VANET
Differences Between .NET Core and .NET Framework
How to create Python dictionary by enumerate function?

Python enumerate() function takes any iterable as argument and returns enumerate object using which the iterable can be traversed. It contains index and corresponding item in the iterable object like list, tuple or string.
Such enumerate object with index and value is then converted to a dictionary using dictionary comprehension.
>>> l1=['aa','bb','cc','dd']
>>> enum=enumerate(l1)
>>> enum

>>> d=dict((i,j) for i,j in enum)
>>> d
{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}
PHP | Check if a number is prime

10 Jul, 2021
Given a number, we need to check whether it is prime or not in PHP. General approach for prime check is discussed here. In this article we will learn about how to check if a number is prime or not in PHP.
Examples: 
Input : 21
Output : Not Prime

Input : 31
Output : Prime
 
Simple Method: A simple solution is to iterate through all numbers from 2 to n/2 and for every number check if it divides n. If we find any number that divides, we return 0 (false) otherwise we will return 1 (true). 
Below is the implementation of this approach in PHP:  
PHP
<?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){    if ($number == 1)    return 0;    for ($i = 2; $i <= $number/2; $i++){        if ($number % $i == 0)            return 0;    }    return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1)    echo "Prime";else    echo "Not Prime"?>
Output: 
Prime
Time Complexity: O(n)
Efficient Method: We can optimize the above approach by observing that, instead of checking till n, we can check till sqrt(n) because a larger factor of n must be a multiple of smaller factor that has been already checked.So, we will traverse in the range [2,sqrt(number)] to check if the number is divisible by any number or not. If it is divisible the its not a prime number.
Below is the implementation of this approach in PHP:  
PHP
<?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){    if ($number == 1)    return 0;         for ($i = 2; $i <= sqrt($number); $i++){        if ($number % $i == 0)            return 0;    }    return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1)    echo "Prime";else    echo "Not Prime"?>
Output: 
Prime
Time Complexity: O(sqrt(n)) 
simranarora5sos
anikakapoor
PHP-basics
school-programming
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Neo4j - Count Function

Assume we have created a graph in the database with the following details.
The count() function is used to count the number of rows.
Following is the syntax of the count function.
MATCH (n { name: 'A' })-->(x) 
RETURN n, count(*) 

Following is a sample Cypher Query which demonstrates the usage of the count() function.
Match(n{name: "India", result: "Winners"})--(x)  
RETURN n, count(*) 
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
The COUNT clause is also used to count the groups of relationship types.
Following is a sample Cypher Query which counts and returns the number of nodes participating in each relation.
Match(n{name: "India", result: "Winners"})-[r]-(x)  
RETURN type (r), count(*) 
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Path subpath() method in Java with Examples

20 Jun, 2022
The subpath(int beginIndex, int endIndex) method of java.nio.file.Path used to return a relative Path that is a subsequence of the name elements of this path. We will pass begin and end indexes to construct a subpath. The beginIndex and endIndex parameters specify the subsequence of name elements. The name element closest to the root in the directory hierarchy is index 0 and name element that is farthest from the root has index count-1. The returned subpath object has the name elements that begin at beginIndex and extend to the element at index endIndex-1. 
Syntax:
Path subpath(int beginIndex,
             int endIndex)
Parameters: This method accepts a two parameters:
beginIndex which is the index of the first element, inclusive and
endIndex which is the index of the last element, exclusive.
Return value: This method returns a new Path object that is a subsequence of the name elements in this Path. 
Exception: This method throws IllegalArgumentException if beginIndex is negative, or greater than or equal to the number of elements. If endIndex is less than or equal to beginIndex, or larger than the number of elements. 
Below programs illustrate subpath() method: 
Program 1: 
Java
// Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG {    public static void main(String[] args)    {         // create an object of Path        Path path            = Paths.get("D:\\eclipse\\p2"                        + "\\org\\eclipse\\equinox\\p2\\core"                        + "\\cache\\binary");         // call subPath() to create a subPath which        // begin at index 1 and ends at index 5        Path subPath = path.subpath(1, 5);         // print result        System.out.println("Subpath: "                           + subPath);    }}
Program 2: 
Java
// Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG {    public static void main(String[] args)    {         // create an object of Path        Path path            = Paths.get("D:\\Workspace"                        + "\\nEclipseWork"                        + "\\GFG\\bin\\defaultpackage");         System.out.println("Original Path:"                           + path);         // call subPath() to create a subPath which        // begin at index 0 and ends at index 2        Path subPath = path.subpath(0, 2);         // print result        System.out.println("Subpath: "                           + subPath);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#subpath(int, int)
simmytarika5
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python – Remove index ranges from String

02 Sep, 2020
Given a string and ranges list, remove all the characters that occur in ranges. 
Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6), (7, 10)]Output : geeks is best for geeksExplanation : The required ranges removed.
Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6)]Output : georgeeks is best for geeksExplanation : The required ranges removed.
Method #1 : Using loop
In this, we check for each range, remake string, considering the index doesn’t lie in range checking using conditional statements.
Python3
# Python3 code to demonstrate working of # Remove index ranges from String # Using loop  # initializing stringstest_str1 = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string 1 is : " + str(test_str1))  # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)]  res = ""  for idx, chr in enumerate(test_str1):  for strt_idx, end_idx in range_list:            # checking for ranges and appending     if strt_idx <= idx + 1 <= end_idx:       break  else:    res += chr  # printing result print("The reconstructed string : " + str(res)) 
The original string 1 is : geeksforgeeks is best for geeks
The reconstructed string : geeksbest for geeks

Method #2 : Using any() + list comprehension + join()
In this, we perform task of checking for indices for strings using any() and list comprehension is used to reconstruct string accordingly. 
Python3
# Python3 code to demonstrate working of # Remove index ranges from String # Using any() + list comprehension + join()  # initializing stringstest_str1 = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string 1 is : " + str(test_str1))  # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)]  # using any() to check for strings in index rangesres = ''.join(chr for idx, chr in enumerate(test_str1, 1) if not any(strt_idx <= idx <= end_idx          for strt_idx, end_idx in range_list))  # printing result print("The reconstructed string : " + str(res)) 
The original string 1 is : geeksforgeeks is best for geeks
The reconstructed string : geeksbest for geeks

Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Test Execution Results in XML Format

We can generate the details of the test execution in an xml file. This xml file is mainly useful in cases where we have a dashboard that projects the test results. In such cases, the xml can be parsed to get the details of the execution.
We will now execute the tests from test_multiplcation.py and generate the xml by running
pytest test_multiplication.py -v --junitxml="result.xml"
Now we can see result.xml is generated with the following data −
<?xml version = "1.0" encoding = "utf-8"?>
<testsuite errors = "0" failures = "1"
name = "pytest" skips = "0" tests = "4" time = "0.061">
   <testcase classname = "test_multiplication"          
      file = "test_multiplication.py"
      line = "2" name = "test_multiplication_11[1-11]"
      time = "0.00117516517639>
   </testcase>
   
   <testcase classname = "test_multiplication"    
      file = "test_multiplication.py"
      line = "2" name = "test_multiplication_11[2-22]"
      time = "0.00155973434448">
   </testcase>

   <testcase classname = "test_multiplication" 
      file = "test_multiplication.py"
      line = "2" name = "test_multiplication_11[3-35]" time = "0.00144290924072">
      failure message = "assert (11 * 3) == 35">num = 3, output = 35

         @pytest.mark.parametrize("num,
         output",[(1,11),(2,22),(3,35),(4,44)])
            
         def test_multiplication_11(num, output):> 
         assert 11*num == output
         E assert (11 * 3) == 35

         test_multiplication.py:5: AssertionErro
      </failure>
   </testcase>
   <testcase classname = "test_multiplication" 
      file = "test_multiplication.py"
      line = "2" name = "test_multiplication_11[4-44]"
      time = "0.000945091247559">
   </testcase>
</testsuite>

Here, the tag <testsuit> summarises there were 4 tests and the number of failures are
1.
The tag <testcase> gives the details of each executed test.
The tag <testcase> gives the details of each executed test.
<failure> tag gives the details of the failed test code.
<failure> tag gives the details of the failed test code.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
Error:selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH using Selenium

We can get the error selenium.common.exceptions.WebDriverException if the path of the chromedriver.exe executable file is not set properly or incorrect within the webdriver.Chrome(). The below image shows such an exception.
It can be resolved by the following ways −
Verify the path of the chromedriver.exe file set within webdriver.Chrome.
Verify the path of the chromedriver.exe file set within webdriver.Chrome.
Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code.
Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code.
Code Implementation with webdriver manager
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
#configure webdriver manager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
print("URL is: ")
print(driver.current_url)
driver.close()
Image processing/OpenCV image dilation Java Example.

Erosion and dilation are the two basic morphological operations. As the name
implies, morphological operations are the set of operations that process images
according to their shapes.
During dilation operation additional pixels are added to an image boundary, a total number of pixels added during the dilation process depends on the dimensions of the structuring element used.
You can dilate an image using the dilate() method of the Imgproc class, this method three mat objects representing source, destination, and kernel.
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ImageDilation extends Application {
   public void start(Stage stage) throws IOException {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading image data
      String file ="D:\\Images\\lamma2.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating destination matrix
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      //Preparing the kernel matrix object
      Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((2*2) + 1, (2*2)+1));
      //Applying dilate on the Image
      Imgproc.dilate(src, dst, kernel);
      //Converting matrix to JavaFX writable image
      Image img = HighGui.toBufferedImage(dst);
      WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
      //Setting the image view
      ImageView imageView = new ImageView(writableImage);
      imageView.setX(10);
      imageView.setY(10);
      imageView.setFitWidth(575);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 400);
      stage.setTitle("Dilation Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}
On executing, above example generates the following output −
How to format Phone Numbers in PHP ?

25 May, 2021
In this article, we will learn how to format phone numbers using PHP. When we need to store a phone number then we store the formatting phone number. Using PHP, we can easily format phone numbers.
Approach: In this article, we will format the phone number using the preg_match() method. We can use this method to format phone numbers. This function has special characteristics of finding specified patterns from string. 
PHP code: The following is the complete code to format phone numbers using preg_match().
PHP
<?php  // Create a formatting functionfunction formatting($phone){          // Pass phone number in preg_match function    if(preg_match(        '/^\+[0-9]([0-9]{3})([0-9]{3})([0-9]{4})$/',     $phone, $value)) {              // Store value in format variable        $format = $value[1] . '-' .             $value[2] . '-' . $value[3];    }    else {                 // If given number is invalid        echo "Invalid phone number <br>";    }          // Print the given format    echo("$format" . "<br>");}   // Call the functionformatting("+02025550170");  formatting("+01677942758");?>
Output:
202-555-0170
167-794-2758
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
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 ?
Adding new column to existing DataFrame in Pandas

Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list and series etc. In this article we will see how to add a new column to an existing data frame.
So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no.
 Live Demo
import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])
print (df)
Running the above code gives us the following result:
   Month_No
0       6
1       8
2       3
3       1
4       12
We can use the insert() function of pandas which will insert the column at the position specified by its index. Below we add No of Days in a month as a column to the existing pandas DataFrame at index position 1.
 Live Demo
import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])

# Insert the new column at position 1.
df.insert(1,"No_of_days",[30,31,31,31,31],True)
print (df)
Running the above code gives us the following result −
   Month_No No_of_days
0       6       30
1       8       31
2       3       31
3       1       31
4       12      31
The assign() function
 Live Demo
import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])

# Insert a column at the end
df = df.assign(No_of_days = [30,31,31,31,31])

print (df)
Running the above code gives us the following result −
   Month_No No_of_days
0       6       30
1       8       31
2       3       31
3       1       31
4       12      31
cupsd command in Linux with examples

15 May, 2019
cupsd is a type of scheduler for CUPS (Common Unit Printing System). It implements the printing system on the basis of the Internet Printing Protocol(Version 2.1). If no options is being specified on the command-line then the default configuration file /etc/cups/cupsd.conf will be automatically be used.
Installation:To install the CUPS in your Linux machine, simply use the sudo command with the apt. A complete CUPS package installation has many package dependencies, but they can all be specified on the same command line. Enter the following command on the terminal:
sudo apt install cups 
Once authenticated with your username and password, the packages must be downloaded and installed without error. As the conclusion of the installation, the CUPS server will be going to start automatically by default.
Syntax:
cupsd [ -c config-file ] [ -f ] [ -F ] [ -h ] [ -l ] [ -t ]
Options:
cupsd -c config-file: This option uses the named configuration file.
cupsd -f: This option runs cupsd in the foreground. The default is to run in the background as a “daemon”.
cupsd -F: This option runs cupsd in the foreground but detaches the process from the controlling terminal and also from the current directory. This is very useful for running cupsd from init.
cupsd -h: This option shows the program usage.
cupsd -l config-file: This option passed to cupsd when it is being run from launchd or systemd command.
cupsd -t: This option tests the configuration file for syntax errors.
cupsd command with help option: It will print the general syntax of the command along with the various options that can be used with the cupsd command as well as gives a brief description about each option.Example:
Example:
Web Interface: CUPS can be easily configured and can be monitored using a web interface, which is by default available at http://localhost:631/admin. The web interface can be used to perform all the printer management tasks.
In order to perform the administrative tasks through the web interface, you must either have the root account enabled on your server, or you need to authenticate as a user in the lpadmin group. For security reasons, CUPS by default won’t authenticate a user that doesn’t have a password.
To add a user to the lpadmin group, run at the following command in your terminal prompt:
sudo usermod -aG lpadmin username
Examples:
Run the cupsd in the background with all the default configuration file:cupsd
cupsd
Test a configuration file known to be test.conf:cupsd -t -c test.conf
cupsd -t -c test.conf
Run cupsd command in the foreground with a test configuration file known to be test.conf:cupsd -f -c test.conf
cupsd -f -c test.conf
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Numpy count_nonzero method | Python

22 Apr, 2020
numpy.count_nonzero() function counts the number of non-zero values in the array arr.
Syntax : numpy.count_nonzero(arr, axis=None)
Parameters :arr : [array_like] The array for which to count non-zeros.axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr.
Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.
Code #1 :
# Python program explaining# numpy.count_nonzero() function  # importing numpy as geek import numpy as geek  arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]]  gfg = geek.count_nonzero(arr)  print (gfg) 
Output :
6

 Code #2 :
# Python program explaining# numpy.count_nonzero() function  # importing numpy as geek import numpy as geek  arr = [[0, 1, 2, 3, 4], [5, 0, 6, 0, 7]]  gfg = geek.count_nonzero(arr, axis = 0)  print (gfg) 
Output :
7

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print the element at a given index in a Set in C++

12 Jan, 2022
Given a Set of integers sett and an integer index, the task is to find the element in the set which is present at index. If the index is beyond limits, then print “Invalid index”.Examples:  
Input: sett = {11, 44, 66, 72, 88, 99}, index = 2 Output: The element at index 2 is : 66 Explaination: The element 66 is present in the set and it is present at index 2.Input: sett = {11, 44, 66, 72, 88, 99}, index = 6 Output: Invalid index  
 
Approach: 
Define a template getNthElement which find the index of particular element by using next() function. 
next() function returns an iterator pointing to the element after being advanced by certain number of positions. It is defined inside the header file.
Using the next() function, getNthElement return a pair of boolean and integer values. The boolean value denotes if index is found the set or not. The integer value contains the integer stored at index in the set.
If the boolean value is set true, which indicates index to be a valid index, print the integer value stored in the pair. Otherwise print “Invalid index”.
Below is the implementation of the above approach:  
C++
// C++ program to access a// set element by its index #include <bits/stdc++.h>using namespace std; // Generic templatetemplate <typename T>pair<T, bool> getNthElement(set<T>& searchSet,                            int index){    pair<T, bool> result;     // Check if index is valid or not    if (searchSet.size() > index) {        result.first            = *(std::next(                searchSet.begin(),                index));        result.second = true;    }     else        result.second = false;     // Return the pair    return result;} // Driver Programint main(){    set<int> sett = { 11, 44, 66,                      72, 88, 99 };    int index = 2;     pair<int, bool> result        = getNthElement(            sett, index);     if (result.second)        cout << "The element at index "             << index << " is "             << result.first;    else        cout << "Invalid index";    return 0;}
The element at index 2 is 66
 
Time Complexity: O(N) Auxiliary Space: O(1) 
as5853535
C++-Templates
cpp-set
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Different ways to print elements of vector
Dynamic _Cast in C++
string::npos in C++ with Examples
Why it is important to write "using namespace std" in C++ program?
How to convert a Vector to Set in C++
Maximum value of long long int in C++
Difference between split() and explode() functions for String manipulation in PHP

27 Oct, 2021
In this article, we will see the differences between split() and explode() functions for String manipulation in PHP. The split() and explode() functions are available in base PHP and are used to perform string manipulations as well as conversions.
split() Function: The split() function in PHP is used to segregate the input string into different elements. The elements are divided based on the occurrence of patterns in the string. The optional parameter depicts the number of elements to divide the array. It begins from the left to the right of the string. The method returns an array. 
array split (string pattern, string string [, int limit])
Parameters: 
pattern – The separator to break the string.
string – The string to split into parts.
PHP
<?php$str = "Geeks_for_geeks_is_fun!";$arr = split("\_", $str);print("String components : ");print_r($arr);?>
Output
String components : Array ( 
    [0] => Geeks 
    [1] => for 
    [2] => geeks 
    [3] => is 
    [4] => fun! 
)
explode() Function: The explode() function in PHP is used to divide the string into array components depending on the separator specified. The limit parameter indicates the number of parts into which to divide the array into. This method returns an indexed array with indexes mapped to array elements. 
explode(separator, string, limit)
Parameters: 
separator – The separator break the string.
string – The string to split into parts.
limit – Indicator of the number of array elements to divide the array into parts. More than 0 – Returns an array with a maximum of limit element(s)Less than 0 – Returns an array except for the last –limit elements()Equal to 0 – Returns an array with one element
More than 0 – Returns an array with a maximum of limit element(s)
Less than 0 – Returns an array except for the last –limit elements()
Equal to 0 – Returns an array with one element
PHP
<?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str);print("String components : ");print_r($arr);  ?>
String components : Array
(
    [0] => Geeks
    [1] => for
    [2] => geeks
    [3] => is
    [4] => fun!
)

The following code snippet divides the string into a single array component: 
PHP
<?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str, 0);print("String components : ");print_r($arr);?>
String components : Array
(
    [0] => Geeks for geeks is fun!
)

The following code snippet indicates the usage of the last parameter less than 1: 
PHP
<?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str, -1);print("String components : ");print_r($arr);?>
String components : Array
(
    [0] => Geeks
    [1] => for
    [2] => geeks
    [3] => is
)

split() Function
explode() Function
PHP-function
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MD5 hash in Python

21 Apr, 2020
Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases.There are many hash functions defined in the “hashlib” library in python.This article deals with explanation and working of MD5 hash.
This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has security issues.
Functions associated :
encode() : Converts the string into bytes to be acceptable by hash function.
digest() : Returns the encoded data in byte format.
hexdigest() : Returns the encoded data in hexadecimal format.
The below code demonstrates the working of MD5 hash accepting bytes and output as bytes.
# Python 3 code to demonstrate the # working of MD5 (byte - byte)  import hashlib  # encoding GeeksforGeeks using md5 hash# function result = hashlib.md5(b'GeeksforGeeks')  # printing the equivalent byte value.print("The byte equivalent of hash is : ", end ="")print(result.digest())
Output:
The byte equivalent of hash is : b'\xf1\xe0ix~\xcetS\x1d\x11%Y\x94\\hq'

Explanation : The above code takes byte and can be accepted by the hash function. The md5 hash function encodes it and then using digest(), byte equivalent encoded string is printed.
Below code demonstrated how to take string as input and output hexadecimal equivalent of the encoded value.
# Python 3 code to demonstrate the # working of MD5 (string - hexadecimal)  import hashlib  # initializing stringstr2hash = "GeeksforGeeks"  # encoding GeeksforGeeks using encode()# then sending to md5()result = hashlib.md5(str2hash.encode())  # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of hash is : ", end ="")print(result.hexdigest())
Output:
The hexadecimal equivalent of hash is : f1e069787ece74531d112559945c6871

Explanation : The above code takes string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The md5 hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed.
andecker91
cryptography
Python
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Python | Dictionary with index as value

29 Apr, 2019
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index where element occurs. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using dictionary comprehension + enumerate()
This problem can be solved easily using the combination of above functions, dictionary comprehension can perform the task of constructing the dictionary and enumerate function can be used to access the index value along with the element.
# Python3 code to demonstrate# Dictionary with index as value# using Dictionary comprehension + enumerate()  # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']  # printing original listprint("The original list : " + str(test_list))  # using Dictionary comprehension + enumerate()# Dictionary with index as valueres = {val : idx + 1 for idx, val in enumerate(test_list)}  # print resultprint("The Dictionary after index keys : " + str(res))
The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3}

 
Method #2 : Using dict() + zip()
This problem can also be solved using the combination of above 2 functions, the dict method can be used to convert to dictionary and zip function can be used to map the indices with the keys.
# Python3 code to demonstrate# Dictionary with index as value# using dict() + zip()  # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']  # printing original listprint("The original list : " + str(test_list))  # using dict() + zip()# Dictionary with index as valueres = dict(zip(test_list, range(1, len(test_list)+1)))  # print resultprint("The Dictionary after index keys : " + str(res))
The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3}

Python dictionary-programs
Python list-programs
Python
Python Programs
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
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