code-rag-bench/online-tutorials huggingface dataset:
Display the student marks in a single column on the basis of subject in MySQL?

For this, use UNION ALL.
Let us first create a table:
mysql> create table DemoTable729 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   MySQLMarks int,
   CMarks int,
   JavaMarks int
);
Query OK, 0 rows affected (0.40 sec)
Insert some records in the table using insert command:
mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('Chris',94,67,75);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('Robert',45,99,54);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable729(StudentName,MySQLMarks,CMarks,JavaMarks) values('David',57,89,43);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement:
mysql> select *from DemoTable729;
This will produce the following output -
+-----------+-------------+------------+--------+-----------+
| StudentId | StudentName | MySQLMarks | CMarks | JavaMarks |
+-----------+-------------+------------+--------+-----------+
| 1         | Chris       | 94         | 67     | 75        |
| 2         | Robert      | 45         | 99     | 54        |
| 3         | David       | 57         | 89     | 43        |
+-----------+-------------+------------+--------+-----------+
3 rows in set (0.00 sec)
Following is the query to display student marks in a single column:
mysql> select StudentId,StudentName,'MySQL' as SubjectName, MySQLMarks as Score
from DemoTable729
UNION ALL
select StudentId,StudentName, 'C' as SubjectName, CMarks as Score
from DemoTable729
UNION ALL
select StudentId,StudentName, 'Java' as SubjectName, JavaMarks as Score
from DemoTable729;
This will produce the following output -
+-----------+-------------+-------------+-------+
| StudentId | StudentName | SubjectName | Score |
+-----------+-------------+-------------+-------+
| 1         | Chris       | MySQL       | 94    |
| 2         | Robert      | MySQL       | 45    |
| 3         | David       | MySQL       | 57    |
| 1         | Chris       | C           | 67    |
| 2         | Robert      | C           | 99    |
| 3         | David       | C           | 89    |
| 1         | Chris       | Java        | 75    |
| 2         | Robert      | Java        | 54    |
| 3         | David       | Java        | 43    |
+-----------+-------------+-------------+-------+
9 rows in set (0.00 sec)
HiveQL - Select-Group By

This chapter explains the details of GROUP BY clause in a SELECT statement. The GROUP BY clause is used to group all the records in a result set using a particular collection column. It is used to query a group of records.
The syntax of GROUP BY clause is as follows:
SELECT [ALL | DISTINCT] select_expr, select_expr, ... 
FROM table_reference 
[WHERE where_condition] 
[GROUP BY col_list] 
[HAVING having_condition] 
[ORDER BY col_list]] 
[LIMIT number];
Let us take an example of SELECT...GROUP BY clause. Assume employee table as given below, with Id, Name, Salary, Designation, and Dept fields. Generate a query to retrieve the number of employees in each department.
+------+--------------+-------------+-------------------+--------+ 
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+ 
|1201  | Gopal        | 45000       | Technical manager | TP     | 
|1202  | Manisha      | 45000       | Proofreader       | PR     | 
|1203  | Masthanvali  | 40000       | Technical writer  | TP     | 
|1204  | Krian        | 45000       | Proofreader       | PR     | 
|1205  | Kranthi      | 30000       | Op Admin          | Admin  |
+------+--------------+-------------+-------------------+--------+

The following query retrieves the employee details using the above scenario.
hive> SELECT Dept,count(*) FROM employee GROUP BY DEPT;
On successful execution of the query, you get to see the following response:
+------+--------------+ 
| Dept | Count(*)     | 
+------+--------------+ 
|Admin |    1         | 
|PR    |    2         | 
|TP    |    3         | 
+------+--------------+

Given below is the JDBC program to apply the Group By clause for the given example.
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class HiveQLGroupBy {
   private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
   
   public static void main(String[] args) throws SQLException {
   
      // Register driver and create driver instance
      Class.forName(driverName);
      
      // get connection
      Connection con = DriverManager.
      getConnection("jdbc:hive://localhost:10000/userdb", "", "");
      
      // create statement
      Statement stmt = con.createStatement();
      
      // execute statement
      Resultset res = stmt.executeQuery(“SELECT Dept,count(*) ” + “FROM employee GROUP BY DEPT; ”);
      System.out.println(" Dept \t count(*)");
      
      while (res.next()) {
         System.out.println(res.getString(1) + " " + res.getInt(2)); 
      }
      con.close();
   }
}
Save the program in a file named HiveQLGroupBy.java. Use the following commands to compile and execute this program.
$ javac HiveQLGroupBy.java
$ java HiveQLGroupBy
 Dept     Count(*)
 Admin       1
 PR          2
 TP          3


    50 Lectures 
     4 hours 

 Navdeep Kaur

    67 Lectures 
     4 hours 

 Bigdata Engineer

    109 Lectures 
     2 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Python List cmp() Method

Python list method cmp() compares elements of two lists.
Following is the syntax for cmp() method −
cmp(list1, list2)

list1 − This is the first list to be compared.
list1 − This is the first list to be compared.
list2 − This is the second list to be compared.
list2 − This is the second list to be compared.
If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary and compare.
If either element is a number, then the other element is "larger" (numbers are "smallest").
Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned.
The following example shows the usage of cmp() method.
#!/usr/bin/python

list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
When we run above program, it produces following result −
-1
1
-1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Overlay Histogram with Fitted Density Curve in R - GeeksforGeeks

17 Jun, 2021
In this article, we will be looking at the different approaches to overlay histogram with fitted density curve in R programming language.
In this approach for overlaying histogram with the fitted density curve user need not install or import any library as all the function are the base functions of the R programming language programming the user first needs to call the hist() functions for plotting the histogram with the given data, and further with that use lines() function with the combination of the density() function it will lead to the density curve fitted to the plotted histogram on the same plot in the R programming language.
hist() is a generic function hist computes a histogram of the given data values.
Syntax: hist(x, breaks = “Sturges”, freq = NULL, probability = !freq, include.lowest = TRUE, right = TRUE, density = NULL, angle = 45, col = NULL, border = NULL,  main = paste(“Histogram of” , xname), xlim = range(breaks), ylim = NULL,  xlab = xname, ylab, axes = TRUE, plot = TRUE, labels = FALSE, nclass = NULL, warn.unused = TRUE, ...)
lines() is a generic function taking coordinates given in various ways and joining the corresponding points with line segments.
Syntax: lines(x, ...)
density() is a generic function density that computes kernel density estimates.
Syntax: density(x,...)
Example:
R
gfg <-rnorm(500)   hist(gfg, prob = TRUE)   lines(density(gfg), col = "green")
Output:
In this method to overlay the histogram with the fitted density curve, the user first needs to install and import the ggplot2 package in the R console, and call the ggplot() function which will create the plot of the given data with the required parameters and add the geom_histogram()  to create the histogram of the data with the combination of  geom_density() function which will be plotting the density curve on that plot with the histogram in the R programming language.
geom_histogram() function is used to create the histogram in ggplot of the given data.
Syntax: geom_histogram(mapping = NULL, data = NULL, stat = “bin”, position = “stack”, ...)
 geom_density() function computes and draws kernel density estimate, which is a smoothed version of the histogram.
Syntax:
geom_density(mapping = NULL, data = NULL, stat = “density”, position = “identity”, ..., na.rm = FALSE,  orientation = NA, show.legend = NA,inherit.aes = TRUE, outline.type = “upper”)
Example:
R
library("ggplot2")  gfg <-data.frame(x=rnorm(500))  ggplot(gfg, aes(x)) +geom_histogram(aes(y = stat(density))) +  geom_density(col = "green")
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
How to change Colors in ggplot2 Line Plot in R ?
How to filter R DataFrame by values in a column?
Linear Discriminant Analysis in R Programming
R - Operators
Python Pandas - DataFrame.copy() function - GeeksforGeeks

26 Nov, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
There are many ways to copy DataFrame in pandas. The first way is a simple way of assigning a dataframe object to a variable, but this has some drawbacks.
Syntax: DataFrame.copy(deep=True)
When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).
When deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).
Step 1) Let us first make a dummy data frame, which we will use for our illustration
Step 2) Assign that dataframe object to a variable
Step 3) Make changes in the original dataframe to see if there is any difference in copied variable
Python3
import pandas as pd  #Create Seriess = pd.Series([3,4,5],['earth','mars','jupiter'])k = pd.Series([1,2,3],['earth','mars','jupiter'])  #Create DataFrame df from two seriesdf = pd.DataFrame({'mass':s,'diameter':k})  df
Output:
Dummy DataFrame df
Now, let’s assign the dataframe df to a variable and perform changes:
Python3
#Assign df to variable_copyvariable_copy = df  print(variable_copy) #Update the value of mass of earth in original dataframedf['mass']['earth']=8  print(variable_copy)
Output:
Here, we can see that if we change the values in the original dataframe, then the data in the copied variable also changes. To overcome this, we use DataFrame.copy() 
Let us see this, with examples when deep=True(default ):
Python3
res = df.copy(deep=True)print(res)
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
C# Program to find the smallest element from an array

Declare an array −
int[] arr = { 5, 9, 2, 7 };
Now to get the smallest element from an array, use the Min() method −
arr.Min());
Here is the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      int[] arr = { 5, 9, 2, 7 };
      Console.WriteLine(arr.Min());
   }
}
2
Convert case of elements in a list of strings in Python

As part of data manipulation, we will come across the need to have a single case for all the letters in a string. In this article we will see how to take a list which has string elements with mixed cases. We then apply some python functions to convert them all to a single case.
The lower function is a string function that can convert the entire string to lower case. So we use lambda and map to apply the lower function to each of the elements in the list.
 Live Demo
listA = ['MoN', 'TuE', 'FRI']
# Given list
print("Given list : \n",listA)
res = list(map(lambda x: x.lower(), listA ))
# printing output
print("New all lowercase list: \n",res)
Running the above code gives us the following result −
Given list :
['MoN', 'TuE', 'FRI']
New all lowercase list:
['mon', 'tue', 'fri']
In this approach we directly apply the upper() to the list through a for loop. So each string gets converted to uppercase letters.
 Live Demo
listA = ['MoN', 'TuE', 'FRI']
# Given list
print("Given list : \n",listA)
res = [x.upper() for x in listA]
# printing output
print("New all uppercase list: \n",res)
Running the above code gives us the following result −
Given list :
['MoN', 'TuE', 'FRI']
New all uppercase list:
['MON', 'TUE', 'FRI']
How to get page source as it is in browser using selenium?

We can get page source as it is in browser using Selenium webdriver using the getPageSource method. It allows us to obtain the code of the page source.
String p = driver.getPageSource();
We can also obtain the page source by identifying the body tag with the help offindElement method and then apply the getText method on it. The parameter By.tagName is passed as a parameter to the findElement method.
WebElement l= driver.findElement(By.tagName("body"));
String p = l.getText();
Code Implementation with getPageSource
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get ("https://www.tutorialspoint.com/about/about_careers.htm");
      //get page source
      String p = driver.getPageSource();
      System.out.println("Page Source is : " + p);
      driver.close();
   }
}
Code Implementation with body tagname
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrcBody{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //get page source with getText method
      WebElement l= driver.findElement(By.tagName("body"));
      String p = l.getText();
      System.out.println("Page Source is : " + p);
      driver.close();
   }
}
Tryit Editor v3.7

Tryit: HTML deleted text
How to remove all non-alphanumeric characters from a string in MySQL?

Non-alphanumeric characters are as follows −
@,!,#,&,(),?, /

There is no inbuilt function to remove non-alphanumeric characters from a string in MySQL. Therefore, we create a function which removes all non-alphanumeric characters. The function declaration and definition is as follows.
mysql> delimiter //
mysql> CREATE FUNCTION RemoveNonAlphaNumeric( s CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
   -> BEGIN
   ->   DECLARE var1, length SMALLINT DEFAULT 1;
   ->   DECLARE result CHAR(255) DEFAULT '';
   ->   DECLARE ch CHAR(1);
   ->   SET length  = CHAR_LENGTH( s );
   ->   REPEAT
   ->     BEGIN
   ->       SET ch = MID( s, var1, 1 );
   ->       IF ch REGEXP '[[:alnum:]]' THEN
   ->         SET result =CONCAT(result ,ch);
   ->       END IF;
   ->       SET var1 = var1 + 1;
   ->     END;
   ->   UNTIL var1 >length  END REPEAT;
   ->   RETURN result ;
   -> END //
Query OK, 0 rows affected (0.10 sec)
The function named ‘RemoveNonAlphaNumeric’ removes all non-alphanumeric characters from a string. To check, we will now call the user-defined function.
mysql>delimiter ;
mysql>  select 'My Email id is test@123!',RemoveNonAlphaNumeric('My Email id is test@123!');
The following is the output that displays the successful removal of alphanumeric characters using the function “RemoveNonAlphaNumeric”.
+--------------------------+---------------------------------------------------+
| My Email id is test@123! | removeNonAlphaNumeric('My Email id is test@123!') |
+--------------------------+---------------------------------------------------+
| My Email id is test@123! | MyEmailidistest123                                |
+--------------------------+---------------------------------------------------+
1 row in set (0.15 sec)

In this string (MyEmailidistest123 ),there are no @ and ! symbols now, which means the function is working correctly.
Google Maps - Localization

By default, the city names and option names given on the map will be in English. If required, we can display such information in other languages as well. This process is known as localization. In this chapter, we will learn how to localize a map.
You can customize (localize) the language of the map by specifying the language option in the URL as shown below.
<script src = "https://maps.googleapis.com/maps/api/js?language=zh-Hans"></script>
Here is an example that shows how to localize GoogleMaps. Here you can see a roadmap of China that is localized to Chinese language.
<!DOCTYPE html>
<html>
   <head>
      <script src = "https://maps.googleapis.com/maps/api/js?language=zh-Hans"></script>
      
      <script>
         function loadMap() {
			
            var mapOptions = {
               center:new google.maps.LatLng(32.870360, 101.645508),
               zoom:9, 
               mapTypeId:google.maps.MapTypeId.ROADMAP
            };
				
            var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
         }
      </script>
      
   </head>
   
   <body onload = "loadMap()">
      <div id = "sample" style = "width:580px; height:400px;"></div>
   </body>

</html>
It will produce the following output −

    20 Lectures 
     2.5 hours 

 Asif Hussain

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    33 Lectures 
     2.5 hours 

 Sasha Miller

    22 Lectures 
     1.5 hours 

 Zach Miller

    16 Lectures 
     1.5 hours 

 Sasha Miller

    23 Lectures 
     2.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
How to change the color of a particular bar using geom_bar in R?

To change the color of a particular bar using geom_bar in R, we can provide the count
corresponding to the value for which we want to change the color inside aes function.
For Example, if we have a data frame called df that contains two columns say V and F
where V is categorical and F is for frequency and we want to change the color of
frequency 10 in bar plot then we can use the below mentioned command −
ggplot(df,aes(V,F))+geom_bar(aes(fill=..F..==10),stat="identity")
Following snippet creates a sample data frame −
x<-c("Low","Medium","High")
Count<-c(20,28,40)
df<-data.frame(x,Count)
df
The following dataframe is created
    x  Count
1 Low    20
2 Medium 28
3 High   40
To load ggplot2 package and create bar plot for data in df on the above created data
frame, add the following code to the above snippet −
x<-c("Low","Medium","High")
Count<-c(20,28,40)
df<-data.frame(x,Count)
library(ggplot2)
ggplot(df,aes(x,Count))+geom_bar(stat="identity")
If you execute all the above given snippets as a single program, it generates the
following Output −
To create bar plot for data in df with bar in different color having Count = 20 on the
above created data frame, add the following code to the above snippet −
x<-c("Low","Medium","High")
Count<-c(20,28,40)
df<-data.frame(x,Count)
library(ggplot2)
ggplot(df,aes(x,Count))+geom_bar(aes(fill=..Count..==20),stat="identity")
If you execute all the above given snippets as a single program, it generates the
following Output −
Pre-order traversal in a Javascript Tree

In this traversal method, the root node is visited first, then the left subtree and finally the right subtree.
We start from A, and following pre-order traversal, we first visit A itself and then move to its left subtree B. B is also traversed pre-order. The process goes on until all the nodes are visited. The output of pre-order traversal of this tree will be −
A → B → D → E → C → F → G
This is the algorithm we'll be implementing:
Print the node's data
Recursively traverse left subtree
Recursively traverse right subtree
Let us look at how we'd implement it in our class. 
preOrder() {
   preOrderHelper(this.root);
}
Helper function: 
function preOrderHelper(root) {
   if (root !== null) {
      console.log(root.data);
      preOrderHelper(root.left);
      preOrderHelper(root.right);
   }
}
You can test this using − 
let BST = new BinarySearchTree();
BST.insertRec(10);
BST.insertRec(15);
BST.insertRec(5);
BST.insertRec(50);
BST.insertRec(3);
BST.insertRec(7);
BST.insertRec(12);
BST.preOrder();
This will give the output −
10
5
3
7
15
12
50
How to query documents by a condition on the subdocument in MongoDB?

Let us first create a collection with documents −
> db.demo394.insertOne(
...    {
...
...       details: [
...       {
...          _id: '1',
...          startDate: '2018-01-11T07:00:00.000Z',
...          endDate: '2019-01-12T07:59:59.999Z'
...       },
...       {
...          _id: '2',
...          startDate: '2019-01-21T07:00:00.000Z',
...          endDate: '2020-01-04T07:59:59.999Z'
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5e716817aa3ef9ab8ab202")
}
Display all documents from a collection with the help of find() method −
> db.demo394.find();
This will produce the following output −
{
   "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [
      { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" },
      { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" }
   ]
}
Following is how to query documents by a condition on the subdocument −
> db.demo394.find({
...    $expr: {
...       $let: {
...          vars: { "d": { $arrayElemAt: [ "$details", -1 ] } },
...          in: { $eq: [ "$$d.endDate", "2020-01-04T07:59:59.999Z" ] }
...       }
...    }
... })
This will produce the following output −
{
   "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [
      { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" },
      { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" }
   ] 
}
C program to Replace a word in a text by another given word

In this program, we have given three strings txt, oldword, newword. Our task is to create a C program to replace a word in a text by another given word.
The program will search for all the occurrences of the oldword in the text and replace it with newword.
Let’s take an example to understand the problem −
text = “I am learning programming”
oldword = “learning”
newword = “practicing”
“I am practicing programming”
To solve this problem, we will first find the number of occurrence of the oldword in the string and then create a new string which will store the text with replaced words.
// C program to Replace a word in a text by another given word
 Live Demo
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void replaceWordInText(const char *text, const char *oldWord, const char *newWord) {
   int i = 0, cnt = 0;
   int len1 = strlen(newWord);
   int len2 = strlen(oldWord);
   for (i = 0; text[i] != '\0'; i++) {
      if (strstr(&text[i], oldWord) == &text[i]) {
         cnt++;
         i += len2 - 1;
      }
   }
   char *newString = (char *)malloc(i + cnt * (len1 - len2) + 1);
   i = 0;
   while (*text) {
      if (strstr(text, oldWord) == text) {
         strcpy(&newString[i], newWord);
         i += len1;
         text += len2;
      }
      else
      newString[i++] = *text++;
   }
   printf("New String: %s\n", newString);
}
int main() {
   char str[] = "I am learning programming";
   char c[] = "learning";
   char d[] = "practicing";
   char *result = NULL;
   printf("Original string: %s\n", str);
   replaceWordInText(str, c, d);
   return 0;
}
Original string: I am learning programming
New String: I am practicing programming
Python Program for Radix Sort - GeeksforGeeks

18 Jan, 2022
The Radix Sort Algorithm 1) Do the following for each digit i where i varies from the least significant digit to the most significant digit. 
Sort input array using counting sort (or any stable sort) according to the i\’th digit.   
Python3
# Python program for implementation of Radix Sort   # A function to do counting sort of arr[] according to# the digit represented by exp.def countingSort(arr, exp1):       n = len(arr)       # The output array elements that will have sorted arr    output = [0] * (n)       # initialize count array as 0    count = [0] * (10)       # Store count of occurrences in count[]    for i in range(0, n):        index = (arr[i]/exp1)        count[int((index)%10)] += 1       # Change count[i] so that count[i] now contains actual    #  position of this digit in output array    for i in range(1,10):        count[i] += count[i-1]       # Build the output array    i = n-1    while i>=0:        index = (arr[i]/exp1)        output[ count[ int((index)%10) ] - 1] = arr[i]        count[int((index)%10)] -= 1        i -= 1       # Copying the output array to arr[],    # so that arr now contains sorted numbers    i = 0    for i in range(0,len(arr)):        arr[i] = output[i] # Method to do Radix Sortdef radixSort(arr):     # Find the maximum number to know number of digits    max1 = max(arr)     # Do counting sort for every digit. Note that instead    # of passing digit number, exp is passed. exp is 10^i    # where i is current digit number    exp = 1    while max1/exp > 0:        countingSort(arr,exp)        exp *= 10 # Driver code to test abovearr = [ 170, 45, 75, 90, 802, 24, 2, 66]radixSort(arr) for i in range(len(arr)):    print(arr[i],end=" ") # This code is contributed by Mohit Kumra# This code is updated by Sudeep Saxena(saxenasudeepcse@gmail.com) on July 9, 2020
Output:
2 24 45 66 75 90 170 802
Please refer complete article on Radix Sort for more details!
sudeepsaxena
amartyaghoshgfg
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Iterate over characters of a string in Python
Python program to add two numbers
Python Program for factorial of a number
Python Program for Bubble Sort
Python | Convert set into a list
jQuery - preventDefault() Method

The preventDefault() method prevents the browser from executing the default action.
You can use the method isDefaultPrevented to know whether this method was ever called (on that event object).
Here is the simple syntax to use this method −
event.preventDefault() 

Here is the description of all the parameters used by this method −
NA
NA
Following is a simple example a simple showing the usage of this method. This example demonstrate how you can stop the browser from changing the page to the href of any anchors.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("a").click(function(event){
               event.preventDefault();
               alert( "Default behavior is disabled!" );
            });
         });
      </script>
   </head>
	
   <body>
      <span>Click the following link and it won't work:</span>
      <a href = "https://www.google.com">GOOGLE Inc.</a>
   </body>
</html>
This will produce following result −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
DateTime.AddMinutes() Method in C#

The DateTime.AddMinutes() method in C# is used to add the specified number of minutes to the value of this instance. It returns the new DateTime.
Following is the syntax −
public DateTime AddMinutes (double m);
Above, m are the minutes to be added. If a negative value is added, then the minutes will get subtracted.
Let us now see an example to implement the DateTime.AddMinutes() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 09, 10, 5, 15, 25);
      DateTime d2 = d1.AddMinutes(25);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("\nNew DateTime (After adding minutes) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
   }
}
This will produce the following output −
Initial DateTime = 10 September 2019, 05:15:25
New DateTime (After adding minutes) = 10 September 2019, 05:40:25
Let us now see another example to implement the DateTime.AddMinutes() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 09, 10, 5, 15, 25);
      DateTime d2 = d1.AddMinutes(-15);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("\nNew DateTime (After subtracting minutes) = {0:dd} {0:y}, {0:hh}:   {0:mm}:{0:ss} ", d2);
   }
}
This will produce the following output −
Initial DateTime = 10 September 2019, 05:15:25
New DateTime (After subtracting minutes) = 10 September 2019, 05:00:25
How to create stacked barplot using barplot function in R?

To create a stacked barplot using barplot function we need to use matrix instead of a data frame object because in R barplot function can be used for a vector or for a matrix only. We must be very careful if we want to create a stacked bar plot using barplot function because bar plots are created for count data only. Here, you will see some examples of count as well as continuous data, carefully read the graphs and understand how the graphs are different from each other.
 Live Demo
M1<−matrix(rnorm(40),ncol=4)
M1
      [,1]       [,2]       [,3]       [,4]
[1,] −1.3035243 1.3221939 1.9557782 0.1202694
[2,] −1.2548522 −1.7679306 0.5101073 0.9979115
[3,] 0.1095688 −1.5652809 1.1426236 −0.2278059
[4,] 0.6143122 −0.6680945 −0.9518161 0.7849978
[5,] 0.7078449 0.2490338 −1.1855153 0.3580386
[6,] −1.3651111 −1.2632633 −0.7954036 0.5127274
[7,] −0.4638549 −0.9650625 0.7063811 −2.2920743
[8,] −0.3006626 0.6249937 −0.5921453 0.5214382
[9,] 0.5874841 0.1630416 1.4858325 0.2483941
[10,] −0.5604357 −2.1200705 1.7315785 0.4596253
barplot(M1)
 Live Demo
M2<−matrix(rpois(40,10),ncol=4)
M2
[,1] [,2] [,3] [,4]
[1,] 12 11 11 8
[2,] 9 14 7 5
[3,] 11 6 8 14
[4,] 5 10 10 9
[5,] 8 8 14 10
[6,] 12 12 12 11
[7,] 6 15 4 11
[8,] 12 6 10 10
[9,] 6 10 11 11
[10,] 13 7 15 7
barplot(M2)
 Live Demo
M3<−matrix(sample(0:9,100,replace=TRUE),ncol=10)
M3
      [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]    [,8]    [,9]    [,10]
[1,]    2       8       7       4       3       2       1       1       1       4
[2,]    3       6       9       7       8       3       7       2       5       7
[3,]    7       1       3       9       7       9       7       0       5       7
[4,]    1       1       3       5       0       9       3       5       8       6
[5,]    4       2       6       2       3       8       4       8       2       8
[6,]    3       6       2       9       1       5       1       9       6       5
[7,]    2       1       9       3       6       8       1       3       2       2
[8,]    4       0       2       8       4       7       4       6       6       4
[9,]    0       6       9       9       7       5       8       2       0       7  
[10,]    1       3       5       3       9       7       8       4       0       3
barplot(M3)
How to see if a date is before or after another date in Java 8?

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system.
The now() method of this class obtains the current date from the system clock.
The isAfter() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date succeeds the given date (else, it returns false).
The isBefore() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date preceeds the given date (else, it returns false).
The isEqual() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date is equal to the given date (else, it returns false).
Following example accepts a date from user compares it with the current date using the above three methods.
import java.time.LocalDate;
import java.util.Scanner;
public class CurentTime {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the given date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      //Getting the current date
      LocalDate currentDate = LocalDate.now();
      if(currentDate.isAfter(givenDate)) {
         System.out.println("Current date succeeds the given date ");
      }else if(currentDate.isBefore(givenDate)) {
         System.out.println("Current date preceds the given date ");
      }else if(currentDate.isEqual(givenDate)) {
         System.out.println("Current date is equal to the given date ");
      }
   }
}
Enter the year:
2019
Enter the month:
06
Enter the day:
25
Current date succeeds the given date
Enter the year:
2020
Enter the month:
10
Enter the day:
2
Current date precedes the given date
Enter the year:
2019
Enter the month:
07
Enter the day:
25
Current date is equal to the given date
C# ToCharArray() Method

The ToCharArray() method in C# is used to copy the characters in this instance to a Unicode character array.
The syntax is as follows -
public char[] ToCharArray ();
public char[] ToCharArray (int begnIndex, int len);
Above, begnIndex is the beginning position of a substring in this instance. The len is the length of the substring in this instance.
Let us now see an example -
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Notebook";
      string str2 = "Ultrabook";
      char[] arr1 = str1.ToCharArray();
      char[] arr2 = str2.ToCharArray();
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4));
      Console.Write("Character array...String1 =");
      for (int i = 0; i < arr1.Length; i++)
         Console.Write(" " + arr1[i]);
      Console.WriteLine("\n\nString2 = "+str2);
      Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant());
      Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5));
      Console.Write("Character array...String2 =");
      for (int i = 0; i < arr2.Length; i++)
         Console.Write(" " + arr2[i]);
   }
}
String1 = Notebook
String1 ToUpperInvariant = NOTEBOOK
String1 Substring from index4 = book
Character array...String1 = N o t e b o o k
String2 = Ultrabook
String2 ToUpperInvariant = ultrabook
String2 Substring from index2 = Ultra
Character array...String2 = U l t r a b o o k
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Welcome!";
      string str2 = "Thisisit!";
      char[] arr1 = str1.ToCharArray(3,2);
      char[] arr2 = str2.ToCharArray(2,2);
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4));
      Console.Write("Character array...String1 =");
      for (int i = 0; i < arr1.Length; i++)
         Console.Write(" " + arr1[i]);
      Console.WriteLine("\n\nString2 = "+str2);
      Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant());
      Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5));
      Console.Write("Character array...String2 =");
      for (int i = 0; i < arr2.Length; i++)
         Console.Write(" " + arr2[i]);
   }
}
This will produce the following output -
String1 = Welcome!
String1 ToUpperInvariant = WELCOME!
String1 Substring from index4 = ome!
Character array...String1 = c o
String2 = Thisisit!
String2 ToUpperInvariant = thisisit!
String2 Substring from index2 = Thisi
Character array...String2 = i s
Difference between fail-fast and fail safe in Java

public class FailSafeExample{
   public static void main(String[] args){
      ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
      //Adding elements to map
      map.put("Dell", 1);
      map.put("IBM", 2);
      //Getting an Iterator from map
      Iterator<String> it = map.keySet().iterator();
      while (it.hasNext()){
      String key = (String) it.next();
         System.out.println(key+" : "+map.get(key));
         map.put("Google", 3);
      }
   }
}
IBM :2
Dell:1
public class FailFastExample{
   public static void main(String[] args){
      List<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(3);
      //Getting an Iterator from list
      Iterator<Integer> it = list.iterator();
      while (it.hasNext()){
         Integer integer = (Integer) it.next();
         list.add(4);
      }
   }
}
Exception in thread "main" java.util.ConcurrentModificationException
   at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
Counting with condition in MySQL?

To count, use aggregate function SUM() and to count with condition, you need to set the condition with WHERE. Let us first create a table −
mysql> create table DemoTable1515
   -> (
   -> ClientId varchar(10),
   -> ClientName varchar(20)
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1515 values('CLI-101','Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1515 values('CLI-110','David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1515 values('CLI-101','Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1515 values('CLI-101','Mike');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1515 values('CLI-130','Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1515 values('CLI-101','Chris');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1515;
This will produce the following output −
+----------+------------+
| ClientId | ClientName |
+----------+------------+
| CLI-101  |    Chris   |
| CLI-110  |    David   |
| CLI-101  |      Bob   |
| CLI-101  |      Sam   |
| CLI-101  |      Sam   |
| CLI-101  |     Mike   |
| CLI-130  |     Mike   |
| CLI-101  |     Chris  |
| CLI-101  |      Sam   |
+----------+------------+
9 rows in set (0.00 sec)
Here is the query to count with condition −
mysql> select ClientId,sum(ClientName='Sam') as NameOn101Id,count(*) as TotalNameOn101 from DemoTable1515
   -> where ClientId='CLI-101';
This will produce the following output −
+----------+-------------+----------------+
| ClientId | NameOn101Id | TotalNameOn101 |
+----------+-------------+----------------+
| CLI-101  |           3 |              7 |
+----------+-------------+----------------+
1 row in set (0.00 sec)
hwclock - Unix, Linux Command

hwclock  - query and set the hardware clock (RTC)
hwclock [functions] [options]
Example-1:
To Display Hardware Clock Date and Time
# hwclock
# hwclock -r
# hwclock --show
output:
Sat 07 Jan 2017 06:17:43 PM IST  -0.146610 seconds
Example-2:
To Set Hardware Clock Date and Time Manually:
#  hwclock --set --date 1/1/2017
output:
# hwclock -rSun 01 Jan 2017 12:00:03 AM IST  -0.208884 seconds
Example-3:
To run hwclock Debug Mode
# hwclock --systohc --debug
# hwclock -hctosys --debug
# hwclock --setepoch --epoch=1952
output:
# hwclock --systohc --debughwclock from util-linux 2.20.1Using /dev interface to clock.Last drift adjustment done at 1483209000 seconds after 1969Last calibration done at 1483209000 seconds after 1969Hardware clock is on UTC timeAssuming hardware clock is kept in UTC time.Waiting for clock tick......got clock tickTime read from Hardware Clock: 2016/12/31 18:30:49Hw clock time : 2016/12/31 18:30:49 = 1483209049 seconds since 1969Time elapsed since reference time has been 0.809062 seconds.Delaying further to reach the new time.Setting Hardware Clock to 12:49:58 = 1483793398 seconds since 1969ioctl(RTC_SET_TIME) was successful.Not adjusting drift factor because it has been less than a day since the last calibration.

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Maximum element in tuple list in Python

When it is required to find the maximum element in a tuple list (i.e list of tuples), the 'max' method and the 'operator.itemgetter' method can be used.
The itemgetter fetches a specific item from its operand.
The 'max' method gives the maximum value present in an iterable that is passed as argument to it.
Below is a demonstration of the same −
Live Demo
from operator import itemgetter
my_list = [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]

print ("The list is : ")
print(my_list)

my_result = max(my_list, key = itemgetter(1))[0]

print ("The name that has the maximum value is : ")
print(my_result)
The list is :
[('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
The name that has the maximum value is :
Min
The required libraries are imported.
The list of tuples is defined, and is displayed on the console.
The 'max' method is used to go through the list, and specify the key as the first element of every tuple inside the list.
This result is assigned to a value.
It is displayed as output on the console.
Combining multiple rows into a comma delimited list in MySQL?

To combine multiple rows into a comma delimited list, use the GROUP_CONCAT() method. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(30),
   Marks int
   );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Marks) values('John',67);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(Name,Marks) values('Carol',69);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(Name,Marks) values('Sam',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('David',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(Name,Marks) values('Chris',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('Bob',67);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
| 1  | John  | 67    |
| 2  | Carol | 69    |
| 3  | Sam   | 69    |
| 4  | David | 78    |
| 5  | Chris | 69    |
| 6  | Bob   | 67    |
+----+-------+-------+
6 rows in set (0.00 sec)
Following is the query to combine multiple rows into a comma delimited list in MySQL −
mysql> SELECT Marks, GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ')
   from DemoTable GROUP BY Marks;
+-------+-----------------------------------------------------+
| Marks | GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ') |
+-------+-----------------------------------------------------+
| 67    | Bob, John                                           |
| 69    | Carol, Chris, Sam                                   |
| 78    | David                                               |
+-------+-----------------------------------------------------+
3 rows in set (0.00 sec)
Find distinct elements - JavaScript

We are required to write a JavaScript function that takes in an array of literals, such that some array elements are repeated. We are required to return an array that contains that appear only once (not repeated).
For example: If the array is:>
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
Then the output should be −
const output = [5, 6];
Following is the code −
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
const findDistinct = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
         continue;
      };
      res.push(arr[i]);
   };
   return res;
};
console.log(findDistinct(arr));
Following is the output in the console −
[5, 6]