code-rag-bench/online-tutorials huggingface dataset:
Fix: ERROR 1396 (HY000): Operation CREATE USER failed in MySQL?

To fix the error, let us see how to create a user correctly. Let us create a user −
mysql> create user 'Emma'@'localhost' IDENTIFIED BY 'emma_654';
Query OK, 0 rows affected (0.00 sec)
Let us display all users along with host −
mysql> select user,host from MySQL.user;
This will produce the following output. The new user created above is visible in the below list of all users along with host −
+------------------+-----------+
| user             |      host |
+------------------+-----------+
| Bob              |         % |
| Charlie          |         % |
| Robert           |         % |
| User2            |         % |
| mysql.infoschema |         % |
| mysql.session    |         % |
| mysql.sys        |         % |
| root             |         % |
| @UserName@       | localhost |
| Adam             | localhost |
| Adam Smith       | localhost |
| Chris            | localhost |
| David            | localhost |
| Emma             | localhost |
| Jace             | localhost |
| James            | localhost |
| John             | localhost |
| John Doe         | localhost |
| Michael          | localhost |
| Mike             | localhost |
| Robert           | localhost |
| User1            | localhost |
| am               | localhost |
| hbstudent        | localhost |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
+------------------+-----------+
26 rows in set (0.00 sec)
How to Convert LinkedHashMap to List in Java? - GeeksforGeeks

17 Dec, 2020

LinkedHashMap is predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, in LinkedHashMap insertion order is preserved.
We to convert LinkedHashMap to  ArrayList. A Map store data in pair of Key and Value while converting a LinkedHashMAp to ArrayList we will store keys of Map in a separate List, similarly store value in another List, look example and algorithm for better understanding.
Example :
Input : { 1 = 3, 4 = 2, 6 = 5, 2 = 1 }

output : Key   -> [ 1, 4, 6, 2 ]
         value -> [ 3, 2, 5, 1]
         
Input : { 2 = 10, 4 = 4, 6 = 23, 8 = 12 }

output : Key   -> [ 2, 4, 6, 6 ]
         value -> [ 10, 4, 23, 12]
Algorithm :
Use For/while loop for iteration in LinkedHashMap 
Take two different ArrayList for Keys and their Respected Values. 
Now iterate through for-Each Loop in LinkedhashMap and add keys and values with their defined ArrayList
Pseudo code : 
for (Map.Entry<Object, Object> it : l.entrySet()) {
            l1.add(it.getKey());
            l2.add(it.getValue());
}

Here, l is LinkedHashMap
      l1 is Arraylist for keys
      l2 is Arraylist for Values
Example:
Java
 

 
 










// Java program to convert LinkedHashMap 
// to List 
  
import java.util.*; 
import java.io.*; 
  
class GFG { 
    
    public static void main(String[] args) 
    { 
        LinkedHashMap<Object, Object> l = new LinkedHashMap<>(); 
        
        l.put(2, 5); 
        l.put(4, 6); 
        l.put(5, 16); 
        l.put(6, 63); 
        l.put(3, 18); 
        
          // Taking two ArrayList 
        ArrayList<Object> l1 = new ArrayList<>(); 
  
        ArrayList<Object> l2 = new ArrayList<>(); 
  
        for (Map.Entry<Object, Object> it : l.entrySet()) { 
            l1.add(it.getKey()); 
            l2.add(it.getValue()); 
        } 
  
        System.out.print("Key -> "); 
        System.out.println(l1); 
        System.out.print("Value -> "); 
        System.out.println(l2); 
    } 
}






Key -> [2, 4, 5, 6, 3]
Value -> [5, 6, 16, 63, 18]
Time Complexity : O(n)

Java-LinkedHashMap


Picked


Technical Scripter 2020


Java


Java Programs


Technical Scripter

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Python VLC MediaPlayer - Getting Play Rate - GeeksforGeeks

11 Apr, 2022
In this article we will see how we can get media play rate of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media play rate is basically is the speed of the video, more the rate faster the video get played, default value is 1.0, in order to slow down the video set rate value less than 1. This rate can be set with the help of set_rate method. 
In order to do this we will use set_rate method with the MediaPlayer objectSyntax : media_player.set_rate()Argument : It takes no argumentReturn : It returns float value  
Below is the implementation  
Python3
# importing vlc moduleimport vlc # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # setting play rate# doubles the speed of the videomedia_player.set_rate(2)  # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint("Play Rate : ")print(value)
Output :  
 
Play Rate : 
2.0
Another example Below is the implementation  
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # setting play rate# halves the speed of the videomedia_player.set_rate(0.5)  # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint("Play Rate : ")print(value)
Output :  
 
Play Rate : 
0.5
 
surinderdawra388
simranarora5sos
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to visualize a data frame that contains missing values in R?

If a data frame contains missing value then visualising it in base R is not easily possible but we can make use of visdat package for this purpose. The vis_dat function of visdat package helps to visualize any data frame even if it contains missing values. For example, if a data frame df contains missing value then it can be visualized as vis_dat(df).
Consider the below data frame −
Live Demo
> x1<-sample(c(NA,1:2),20,replace=TRUE)
> x2<-sample(c(NA,21:24),20,replace=TRUE)
> x3<-sample(c(NA,5,10),20,replace=TRUE)
> df1<-data.frame(x1,x2,x3)
> df1
 x1 x2 x3
1 1 23 10
2 1 23 NA
3 NA NA 10
4 NA NA 10
5 1 24 NA
6 2 22 NA
7 2 24 NA
8 2 24 NA
9 2 21 NA
10 1 23 10
11 NA 24 NA
12 2 22 NA
13 2 NA 10
14 NA 24 10
15 2 NA 5
16 2 21 NA
17 2 23 NA
18 2 NA 5
19 NA 21 10
20 2 NA 5
Loading visdat package and creating the plot of the data frame −
> library(visdat)
> vis_dat(df1)
Live Demo
> y1<-sample(c(NA,rpois(5,2)),20,replace=TRUE)
> y2<-rnorm(20)
> y3<-sample(c(NA,rnorm(5,2,2.1)),20,replace=TRUE)
> y4<-sample(c(NA,runif(5,2,3)),20,replace=TRUE)
> df2<-data.frame(y1,y2,y3,y4)
> df2
  y1 y2 y3 y4
1 4 0.61081616 NA NA
2 3 0.97203884 NA 2.039603
3 1 -0.19848158 2.798295 2.996374
4 NA -0.06643532 1.327976 NA
5 1 -0.08782965 1.327976 2.996374
6 1 -1.74682203 NA 2.996374
7 NA -1.07706177 3.255620 2.039603
8 1 -0.47827253 1.327976 2.670070
9 1 -1.52099043 1.524140 2.773155
10 3 0.80431131 2.798295 2.773155
11 4 -0.92503650 NA 2.996374
12 1 0.09717851 1.524140 2.429227
13 NA 0.59296946 NA 2.039603
14 4 0.40156867 1.524140 2.996374
15 1 -0.25442642 NA 2.773155
16 1 -1.65687286 2.798295 2.996374
17 1 0.35774521 1.524140 2.773155
18 NA 0.09490436 1.524140 2.773155
19 4 -0.63289635 NA 2.773155
20 1 -0.48500639 1.524140 NA
> vis_dat(df2)
Linear Regression in 6 lines of Python | by Adarsh Menon | Towards Data Science

In this quick post, I wanted to share a method with which you can perform linear as well as multiple linear regression, in literally 6 lines of Python code.
In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. I you would like to know more about linear regression and how it is implemented, check out these two methods to perform Linear Regression from scratch:
towardsdatascience.com
towardsdatascience.com
Today to perform Linear Regression quickly, we will be using the library scikit-learn. If you don’t have it already you can install it using pip:
pip install scikit-learn
So now lets start by making a few imports:
We need numpy to perform calculations, pandas to import the data set which is in csv format in this case and matplotlib to visualize our data and regression line. We will use the LinearRegression class to perform the linear regression.
Now lets perform the regression:
We have our predictions in Y_pred. Now lets visualize the data set and the regression line:
That’s it! You can use any data set of you choice, and even perform Multiple Linear Regression (more than one independent variable) using the LinearRegression class in sklearn.linear_model. Also this class uses the ordinary Least Squares method to perform this regression. So accuracy wont be high, when compared to other techniques. But if you want to make some quick predictions and get some insight into the data set given to you, then this is a very handy tool.
Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/03%20Linear%20Regression%20in%202%20minutes
Got questions ? Need help ? Contact me!
LinkedList descendingIterator() method in Java with Examples - GeeksforGeeks

10 Dec, 2018
The descendingIterator() method of java.util.LinkedList class is used to return an iterator over the elements in this LinkedList in reverse sequential order. The elements will be returned in order from last (tail) to first (head).
Syntax:
public Iterator descendingIterator()
Return Value: This method returns an iterator over the elements in this LinkedList in reverse sequence.
Below are the examples to illustrate the descendingIterator() method
Example 1:
// Java program to demonstrate// descendingIterator() method// for String value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          try {              // creating object of TreeMap<Integer, String>            LinkedList<String> list = new LinkedList<String>();              // add some elements to list            list.add("A");            list.add("B");            list.add("C");              // print the linked list            System.out.println("LinkedList:" + list);              // set Iterator as descending            // using descendingIterator() method            Iterator x = list.descendingIterator();              // print list with descending order            while (x.hasNext()) {                System.out.println("Value is : "                                   + x.next());            }        }          catch (NullPointerException e) {            System.out.println("Exception thrown : "                               + e);        }    }}
LinkedList:[A, B, C]
Value is : C
Value is : B
Value is : A

Example 2:
// Java program to demonstrate// descendingIterator() method// for Integer value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          try {              // creating object of TreeMap<Integer, String>            LinkedList<Integer>                list = new LinkedList<Integer>();              // add some elements to list            list.add(10);            list.add(20);            list.add(30);              // print the linked list            System.out.println("LinkedList:" + list);              // set Iterator as descending            // using descendingIterator() method            Iterator x = list.descendingIterator();              // print list with descending order            while (x.hasNext()) {                System.out.println("Value is : "                                   + x.next());            }        }          catch (NullPointerException e) {            System.out.println("Exception thrown : " + e);        }    }}
LinkedList:[10, 20, 30]
Value is : 30
Value is : 20
Value is : 10

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
Queue Interface In Java
Lua - for Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in Lua programming language is as follows −
for init,max/min value, increment
do
   statement(s)
end

Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value.
Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value.
After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables.
After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
for i = 10,1,-1 
do 
   print(i) 
end
When the above code is built and executed, it produces the following result −
GATE | GATE-CS-2015 (Set 3) | Question 65

28 Jun, 2021
Consider the following array of elements. 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉. The minimum number of interchanges needed to convert it into a max-heap is(A) 4(B) 5(C) 2(D) 3Answer: (D)Explanation: 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉

           89
      /         \
     19          50
    /  \        /  \  
  17    12     15    2
 /  \   / \   /  \
5   7  11  6  9  100

Minimum number of swaps required to convert above tree 
to Max heap is 3. Below are 3 swap operations.
Swap 100 with 15
Swap 100 with 50
Swap 100 with 89 

           100
      /         \
     19          89
    /  \        /  \  
  17    12     50    5 
 /  \   / \   /  \
7   11  6  9  2   15
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
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 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE IT 2006 | Question 20
GATE | GATE-CS-2016 (Set 1) | Question 45
Java program to merge two files into a third file

30 May, 2018
Prerequisite : PrintWriter , BufferedReader
Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge.
Create PrintWriter object for file3.txtOpen BufferedReader for file1.txtRun a loop to copy each line of file1.txt to file3.txtOpen BufferedReader for file2.txtRun a loop to copy each line of file2.txt to file3.txtFlush PrintWriter stream and close resources.
Create PrintWriter object for file3.txt
Open BufferedReader for file1.txt
Run a loop to copy each line of file1.txt to file3.txt
Open BufferedReader for file2.txt
Run a loop to copy each line of file2.txt to file3.txt
Flush PrintWriter stream and close resources.
To successfully run the below program file1.txt and file2.txt must exits in same folder OR provide full path for them.
// Java program to merge two // files  into third file  import java.io.*;  public class FileMerge {    public static void main(String[] args) throws IOException     {        // PrintWriter object for file3.txt        PrintWriter pw = new PrintWriter("file3.txt");                  // BufferedReader object for file1.txt        BufferedReader br = new BufferedReader(new FileReader("file1.txt"));                  String line = br.readLine();                  // loop to copy each line of         // file1.txt to  file3.txt        while (line != null)        {            pw.println(line);            line = br.readLine();        }                  br = new BufferedReader(new FileReader("file2.txt"));                  line = br.readLine();                  // loop to copy each line of         // file2.txt to  file3.txt        while(line != null)        {            pw.println(line);            line = br.readLine();        }                  pw.flush();                  // closing resources        br.close();        pw.close();                  System.out.println("Merged file1.txt and file2.txt into file3.txt");    }}
Output:
Merged file1.txt and file2.txt into file3.txt

Note : If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.
Related Article :
C Program to merge contents of two files into a third file
Java program to merge two files alternatively into third file
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-file-handling
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
Introduction to Java
Initialize an ArrayList in Java
exportfs - Unix, Linux Command

Normally this
xtab file is initialized with the list of all file systems named in
/etc/exports by invoking
exportfs -a. 

However, administrators can choose to add and delete individual file systems
without modifying
/etc/exports using
exportfs. 

exportfs and it’s partner program
mountd work in one of two modes, a legacy mode which applies to 2.4 and
earlier versions of the Linux kernel, and a new mode which applies to
2.6 and later versions providing the
nfsd virtual filesystem has been mounted at
/proc/fs/nfsd or
/proc/fs/nfs. If this filesystem is not mounted in 2.6, the legacy mode is used.


In the new mode,
exportfs does not give any information to the kernel but only provides it to
mountd through the
/var/lib/nfs/xtab file.
mountd will listen to requests from the kernel and will provide information
as needed.


In the legacy mode,
any export requests which identify a specific host (rather than a
subnet or netgroup etc) are entered directly into the kernel’s export
table as well as being written to
/var/lib/nfs/xtab. Further, any mount points listed in
/var/lib/nfs/rmtab which match a non host-specific export request will cause an
appropriate export entry for the host given in
rmtab to be entered
into the kernel’s export table.


The
host:/path argument specifies the directory to export along with the host or hosts to
export it to. All formats described in
exports(5) are supported; to export a directory to the world, simply specify
:/path. 

The export options for a particular host/directory pair derive from
several sources.  There is a set of default options which can be overridden by
entries in
/etc/exports (unless the
-i option is given).
In addition, the administrator may overide any options from these sources
using the
-o argument which takes a comma-separated list of options in the same fashion
as one would specify them in
exports(5) .
Thus,
exportfs can also be used to modify the export options of an already exported
directory.


Modifications of the kernel export table used by
nfsd(8) take place immediately after parsing the command line and updating the
xtab file.


The default export options are
sync,ro,root_squash,wdelay. 

To remove individial export entries, one can specify a
host:/path pair. This deletes the specified entry from
xtab and removes the corresponding kernel entry (if any).





# exportfs -a 


To export the
/usr/tmp directory to host
django, allowing asynchronous writes, one would do this:



# exportfs -o async django:/usr/tmp 


When unexporting a network or domain entry, any current exports to members
of this group will be checked against the remaining valid exports and
if they themselves are nolonger valid they will be removed.
SQL Query to Match City Names Ending With Vowels

23 Sep, 2021
In this article, we will learn SQL Query How to Write an SQL Query to Match City Names Ending With Vowels in the Table. and we will implement with the help of an example for better understanding, first of all, we will create a database Name of the Database will Sample. and inside the database, we will create a table name As “office”.
Step 1: Create a Database
For database creation, there is the query we will use in SQL Platform. this is the query.
Query:
Create database sample;
Step 2: Use database
For using the database we will use another query in SQL Platform like Mysql, oracle, etc.
Query:
use Sample;
Step 3: Creation of table in Database
 For the creation of a table in a database. We need to execute a query in SQL. So that we can store Records in the table. 
Syntax:
create table table_name(
column1 type(size),
column2 type(size),
.

columnN type(size)
);
 Query:
CREATE TABLE office
(
EMPNAME VARCHAR(25),
DEPT VARCHAR(20),
CONTACTNO BIGINT NOT NULL,
CITY VARCHAR(15)
); 
Above Query will create a table in our database Sample. Here table name is office. After the creation of the table, we can Justify the view and metadata of the table with the help of the below Query. It will return Schema, column, data type, size, and constraints.
Syntax: 
EXEC sp_help table_name
Query:
EXEC sp_help office; 
Output:
EXEC sp_help table_name; Query is Similar as DESC table_name; query in another platform like Oracle, MySql, etc.
Step 4: Insert Data into a table
To insert data into the table there is the query we will use here in the SQL server.
Query:
INSERT INTO office
VALUES ('VISHAL','SALES',9193458625,'GAZIABAD'),
('VIPIN','MANAGER',7352158944,'BARIELLY'),
('ROHIT','IT',7830246946,'KOLKATA'),
('RAHUL','MARKETING',9635688441,'MEERUT'),
('SANJAY','SALES',9149335694,'MORADABAD'),
('ROHAN','MANAGER',7352158944,'BENGALURU'),
('RAJESH','SALES',9193458625,'VODODARA'),
('AMAN','IT',78359941265,'RAMPUR'),
('RAKESH','MARKETING',9645956441,'BOKARO'),
('VIJAY','SALES',9147844694,'Dehli');
Step 5: View Inserted data 
After inserting data into the table We can justify or confirm which data we have to insert correctly or not. With the help of the below query.
Query:
SELECT * FROM office;
 Output:
Step 6: Query for matching city end with vowels
Query:
SELECT EMPNAME,CITY FROM office
WHERE CITY LIKE '%a'
OR CITY LIKE '%e'
OR CITY LIKE '%i'
OR CITY LIKE '%o'
OR CITY LIKE '%u';
Output:
Picked
SQL-Query
sql-serevr
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
jQuery | after() with Examples

13 Feb, 2019
The after() is an inbuilt function in jQuery which is used to insert content, specified by the parameter for the each selected element in the set of matched element.Syntax:
$(selector).after(A);

Parameter: It accepts a parameter “A” which is either a content or function passed to the method.Return Value: It returns the selected element with the modification.
<html>  <head>    <meta charset="utf-8">    <style>        p {            background: lightgreen;            display: block;            width: 150px;            padding: 10px;            border: 2px solid green;        }    </style>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script></head>  <body>    <p>I would like to say: </p>    <script>        $("p").after("<b><h2>Hello Geeks</h2></b>");    </script></body>  </html>
Output:
Code #2:In the below code, function is passed to the method that will work after the selected element.
<html>  <head>    <meta charset="utf-8">    <style>        p {            background: lightgreen;            width: 250px;            padding: 10px;            border: 2px solid green;        }    </style>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script></head>  <body>    <p>This is first paragraph !!!</p>    <p>This is the second paragraph !!! </p>    <script>        $("p").after(function() {            return "<div>" + "GeeksforGeeks" + "</div>";        });    </script></body>  </html>
Output:
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
Scroll to the top of the page using JavaScript/jQuery
What’s the difference between ng-pristine and ng-dirty in AngularJS?

31 Dec, 2019
AngularJS supports client-side form validation. AngularJS keeps tracks of all the form and input field and it also stores the information about whether anyone has touched or modified the field or not.
Let’s See the two different class ng-dirty and ng-pristine that are used for form validation
ng-pristine: The ng-pristine class tells that the form has not been modified by the user. This returns true if the form has not been modified by the user.Return type:Return Boolean True if the form/input field is not modified by the user else it returns False.
ng-dirty: The ng-dirty class tells that the form has been made dirty (modified ) by the user. It returns true if the user has modified the form.Return type:Return Boolean True if the form/input field is modified by the user else it returns False.
Difference between ng-pristine and ng-dirty:The main difference between both of them is that ng-dirty is used to tell that the input field is modified by the user and the ng-pristine is used to tell us that the field is untouched by the user.Let’s see with the help of a small example to clear out everything.
<!DOCTYPE html><html>  <head>    <title>      Difference between ng-pristine and ng-dirty  </title></head>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js">      </script>        <form ng-app="" name="myForm">            <input name="email"                    ng-model="data.email">            <div class="info"                  ng-show="myForm.email.$pristine">                Now Pristine.            </div>            <div class="error"                  ng-show="myForm.email.$dirty">                Now Dirty            </div>        </form>    </center></body>  </html>
Output:Before:
After:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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 – Right and Left Shift characters in String

22 Apr, 2020
Sometimes, while working with Python Strings, we can have problem in which we have both right and left rotate count of characters in String and would like to know the resultant condition of String. This type of problem occurs in competitive programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using String multiplication + string slicingThe combination of above functions can be used to perform this task. In this, we multiple string thrice, perform the concatenation and selectively slice string to get required result.
# Python3 code to demonstrate working of # Right and Left Shift characters in String# Using String multiplication + string slicing  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + test_str)  # initializing right rot r_rot = 7  # initializing left rot l_rot = 3  # Right and Left Shift characters in String# Using String multiplication + string slicingres = (test_str * 3)[len(test_str) + r_rot - l_rot :                   2 * len(test_str) + r_rot - l_rot]  # printing result print("The string after rotation is : " + str(res)) 
The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

 
Method #2 : Using % operator and string slicingThe combination of above functionalities can also be used to perform this task. In this, we find the mod of rotation difference with length to compute the string position.
# Python3 code to demonstrate working of # Right and Left Shift characters in String# Using % operator and string slicing  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + test_str)  # initializing right rot r_rot = 7  # initializing left rot l_rot = 3  # Right and Left Shift characters in String# Using % operator and string slicingtemp = (r_rot - l_rot) % len(test_str)res = test_str[temp : ] + test_str[ : temp]  # printing result print("The string after rotation is : " + str(res)) 
The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

Python string-programs
Python
Python Programs
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
Read a file line by line in Python
Python String | replace()
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
Program to find the transpose of given matrix in Python

Suppose we have a (n by n) matrix M, we have to find its transpose. As we know the transpose of a matrix switches the row and column indices. More formally, for every r and c, matrix[r][c] = matrix[c][r].
So, if the input is like
then the output will be
To solve this, we will follow these steps −
M := a new list
tracker := 0
while tracker < row count of matrix, dotemp := a new listfor each row in matrix, dotemp := join temp and a list with element row[tracker]M := M join another list with element temptracker := tracker + 1
temp := a new list
for each row in matrix, dotemp := join temp and a list with element row[tracker]
temp := join temp and a list with element row[tracker]
M := M join another list with element temp
tracker := tracker + 1
return M
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, matrix):
      M = []
      tracker = 0
      while tracker < len(matrix):
         temp = []
         for row in matrix:
            temp += [row[tracker]]
         M += [temp]
         tracker += 1
      return M
ob = Solution()
matrix = [ [7, 2, 6], [3, 7, 2], [5, 3, 7] ]
print(ob.solve(matrix))
[[7, 2, 6],
[3, 7, 2],
[5, 3, 7]]
[[7, 3, 5], [2, 7, 3],[6, 2, 7]]
How to setup 404 page in angular routing ?

26 May, 2021
To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. 
Creating Component: Run the below command to create pagenotfound component.
ng generate component pagenotfound
Project Structure: It will look like this.
Implementation: Add the below code inside HTML template of this component to display a simple 404 error message.
pagenotfound.component.html
<div>    <h1>404 Error</h1>    <h1>Page Not Found</h1></div>
Then inside the routing file, we have to provide this component route and make this available for every 404 requests. So, inside the app-routing.module.ts file, we have to create a new route for this PagenotfoundComponent.
app-routing.module.ts
import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { PagenotfoundComponent } from     './pagenotfound/pagenotfound.component';import { PostCreateComponent } from     './posts/post-create/post-create.component';import { PostListComponent } from     './posts/post-list/post-list.component';  const routes: Routes = [    { path: '', component: PostListComponent },    { path: 'create', component: PostCreateComponent },    { path: 'edit/:postId',         component: PostCreateComponent },      //Wild Card Route for 404 request    { path: '**', pathMatch: 'full',         component: PagenotfoundComponent },  ];@NgModule({    imports: [RouterModule.forRoot(routes)],    exports: [RouterModule],    providers: []})export class AppRoutingModule { }
Explanation: Here the route for PagenotfoundComponent is provided inside the routes array. Here any path except the provided routes is handled by this PagenotfoundComponent and our HTML template is displayed in the browser. So now if someone tries to send a request to any page that is not present in the routes array then that user is automatically navigated to this PagenotfoundComponent.
Steps to run the application: Run the following command to start the application:
ng serve
Now open the browser and go to http://localhost:4200, where everything is working fine. Now go to http://localhost:4200/anything, where we will get the 404 error as shown below.
AngularJS-Function
AngularJS-Questions
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
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 ?
Removing Levels from a Factor in R Programming – droplevels() Function

05 Jun, 2020
droplevels() function in R programming used to remove unused levels from a Factor.
Syntax:# For vector objectdroplevels(x, exclude = if(anyNA(levels(x))) NULL else NA, ...)
# For data frame objectdroplevels(x, except, exclude)
Parameter values:x represents object from which unused level has to be droppedexclude represents factor levels which should be excluded even if presentexcept represents indices of columns from which levels should not be dropped
Example 1:
# Defining vectorx <- c(1, 3, 4, 8, 1, 5, 4, 4, 5, 6)  # Defining factor object for vectorf <- factor(x)  # Print factor objectcat("Factor object before deleting value:\n")print(f)cat("\n")  # Delete value at index 2f <- f[-2]  # Print factor objectcat("Factor object after deleting value:\n")print(f)cat("\n")  cat("After dropping unused level:\n")new_f <- droplevels(f)print(new_f)
Output:
Factor object before deleting value:
 [1] 1 3 4 8 1 5 4 4 5 6
Levels: 1 3 4 5 6 8

Factor object after deleting value:
[1] 1 4 8 1 5 4 4 5 6
Levels: 1 3 4 5 6 8

After dropping unused level:
[1] 1 4 8 1 5 4 4 5 6
Levels: 1 4 5 6 8

Example 2:
# Defining columnsx <- factor(c(7, 3, 3, 7, 5, 5, 1))y <- factor(c(1, 1, 1, 4, 4, 4, 2))z <- c(1, 5, 3, 2, 9, 4, 7)  # Defining data framedf <- data.frame(x, y, z)df <- df[1:6, ]  # Print structure of data framestr(df)cat("\n")  # Drop levels from data framedf_drop <- droplevels(df)  # Print structure of new data framestr(df_drop)
Output:
'data.frame':   6 obs. of  3 variables:
 $ x: Factor w/ 4 levels "1", "3", "5", "7": 4 2 2 4 3 3
 $ y: Factor w/ 3 levels "1", "2", "4": 1 1 1 3 3 3
 $ z: num  1 5 3 2 9 4
 
 'data.frame':   6 obs. of  3 variables:
 $ x: Factor w/ 3 levels "3", "5", "7": 3 1 1 3 2 2
 $ y: Factor w/ 2 levels "1", "4": 1 1 1 2 2 2
 $ z: num  1 5 3 2 9 4

R Factor-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add simple DatePicker in Next.js ?

30 Nov, 2021
In this article, we are going to learn how we can add a Simple Datepicker in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Approach: To add our DatePicker we are going to use the react-datepicker package. The react-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the react-datepicker package and then we will add a DatePicker on our homepage.
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
Install the required package: Now we will install the react-datepicker package using the below command:
npm i react-datepicker
Project Structure: It will look like this
Adding the DatePicker: We can easily add the DatePicker in our app after installing the react-datepicker package. For this example, we are going to add the DatePicker to our homepage.
Add the below content in the file:
index.js
import React, { useState } from 'react';import DatePicker from "react-datindex.jsepicker";import "react-datepicker/dist/react-datepicker.css";  export default function GfgDatePicker() {  const [startDate, setStartDate] = useState(new Date());    return (    <div>      <h4>GeeksforGeeks - DatePicker</h4>      <DatePicker selected={startDate} onChange=              {(date) => setStartDate(date)} />    </div>  );}
Explanation: In the above example first, we are importing the DatePocker from the installed package and useState hook from react. After that, we are using creating a constant variable and used the useState hook to store the values. Then we will add our datepicker using the DatePicker component.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Next.js
JavaScript
Node.js
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Append multiple lists at once in Python

For various data analysis work in python we may be needed to combine many python lists into one list. This will help processing it as a single input list for the other parts of the program that need it. It provides performance gains by reducing number of loops required for processing the data further.
The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.
 Live Demo
listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

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

# using + operator
res_list = listA + listB + listC

# printing result
print("Combined list is : ",res_list)
Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]
The zip function brings together elements form each of the lists from the same index and then moves on to the next index. This type of appending is useful when you want to preserver the elements form the lists at the same index position together.
 Live Demo
listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

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

# using zip
res_list = list(zip(listA,listB , listC))

# printing result
print("Combined list is : ",res_list)
Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : [('Mon', '2 pm', 1), ('Tue', '11 am', 3), ('Wed', '1 pm', 6)]
The chain function from itertools module can bring the elements of the lists together preserving the sequence in which they are present.
 Live Demo
from itertools import chain

listA = ['Mon', 'Tue', 'Wed']
listB = ['2 pm', '11 am','1 pm']
listC = [1, 3, 6]

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

# using chain
res_list = list(chain(listA, listB, listC))

# printing result
print("Combined list is : ",res_list)

Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed']
Given list B: ['2 pm', '11 am', '1 pm']
Given list C: [1, 3, 6]
Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]
Program to Calculate Body Mass Index (BMI) - GeeksforGeeks

29 May, 2021
The Body Mass Index (BMI) or Quetelet index is a value derived from the mass (weight) and height of an individual, male or female. The BMI is defined as the body mass divided by the square of the body height and is universally expressed in units of kg/m2, resulting from the mass in kilograms and height in meters. The formula is:  
BMI = (mass or weight)/(height*height)
where,
mass or weight is in Kg,
height is in meters
Examples:  
Input : height(in meter): 1.79832
weight(in Kg): 70
Output : The BMI is 21.64532402096181, so Healthy.
Explanation : 70/(1.79832*1.79832)

Input : height(in meter): 1.58496
weight(in Kg): 85
Output : The BMI is 33.836256857260594 so Suffering from Obesity
Explanation : 70/(1.58496*1.58496)
 
 
Python3
#Python program to illustrate# how to calculate BMIdef BMI(height, weight):    bmi = weight/(height**2)    return bmi # Driver codeheight = 1.79832weight = 70 # calling the BMI functionbmi = BMI(height, weight)print("The BMI is", format(bmi), "so ", end='') # Conditions to find out BMI categoryif (bmi < 18.5):    print("underweight") elif ( bmi >= 18.5 and bmi < 24.9):    print("Healthy") elif ( bmi >= 24.9 and bmi < 30):    print("overweight") elif ( bmi >=30):    print("Suffering from Obesity")
Output:  
The BMI is 21.64532402096181 so Healthy
 
akshaysingh98088
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Constructors in C++
HTML - Email Links

It is not difficult to put an HTML email link on your webpage but it can cause unnecessary spamming problem for your email account. There are people, who can run programs to harvest these types of emails and later use them for spamming in various ways.
You can have another option to facilitate people to send you emails. One option could be to use HTML forms to collect user data and then use PHP or CGI script to send an email.
A simple example, check our Contact Us Form. We take user feedback using this form and then we are using one CGI program which is collecting this information and sending us email to the one given email ID.
Note − You will learn about HTML Forms in HTML Forms and you will learn about CGI in our another tutorial Perl CGI Programming.
HTML <a> tag provides you option to specify an email address to send an email. While using <a> tag as an email tag, you will use mailto: email address along with href attribute. Following is the syntax of using mailto instead of using http.
<a href = "mailto: abc@example.com">Send Email</a>

This code will generate the following link which you can use to send email.
Send Email 

Now, if a user clicks this link, it launches one Email Client (like Lotus Notes, Outlook Express etc. ) installed on your user's computer. There is another risk to use this option to send email because if user do not have email client installed on their computer then it would not be possible to send email.
You can specify a default email subject and email body along with your email address. Following is the example to use default subject and body.
<a href = "mailto:abc@example.com?subject = Feedback&body = Message">
Send Feedback
</a>

This code will generate the following link which you can use to send email.
Send Feedback


    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page