code-rag-bench/online-tutorials huggingface dataset:
Difference Between String and StringBuffer Class in Java

In this post, we will understand the difference between String and StringBuffer class in Java.
It is an immutable class.
It is an immutable class.
This means changes can’t be made to elements of the class.
This means changes can’t be made to elements of the class.
It is slow.
It is slow.
It consumes less memory when strings are concatenated.
It consumes less memory when strings are concatenated.
This is because every time, a new instance is created.
This is because every time, a new instance is created.
It overrides the equals() method of Object class.
It overrides the equals() method of Object class.
Hence, the ‘equals’ method can be used to compare two strings.
Hence, the ‘equals’ method can be used to compare two strings.
Following is an example of the String class −
public class StringDemo {
   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}
It is a mutable class.
It is a mutable class.
This means changes can be made to the elements in this class.
This means changes can be made to the elements in this class.
It is fast.
It is fast.
It uses less memory when strings are concatenated.
It uses less memory when strings are concatenated.
It class doesn't override the equals() method of Object class.
It class doesn't override the equals() method of Object class.
Following is an example of the StringBuffer class −
public class Demo {
   public static void main(String args[]) {
      StringBuffer sBuffer = new StringBuffer("test");
      sBuffer.append(" String Buffer");
      System.out.println(sBuffer);
   }
}
What is a Global Object in JavaScript?

Objects in JavaScript are different from the Global Object. Using the new operator, you cannot create global objects. It comes into existence when the scripting engine is initialized. After it is initialized, the functions and constants are available for use.
A global object allows you to do the following −
It gives access to built-in functions and values. Call alert directly like the below code snippet, with window −
It gives access to built-in functions and values. Call alert directly like the below code snippet, with window −
alert("Demo Text");
// or
window.alert("Demo Text");
It also gives access to global function declarations and var variables −
It also gives access to global function declarations and var variables −
<html>
   <head>
      <script>
         var str = "Demo Text";
         // using window
         alert( window.str );
      </script>
   </head>
   
   <body>
   </body>
</html>
HTML DOM createElement() method

The HTML DOM createElement() method is used for creating an HTML element dynamically using JavaScript. It takes the element name as the parameter and creates that element node. You need to use the appendChild() method to have the newly created element as part of DOM .
Following is the syntax for createElement() method −
document.createElement(nodename)
Let us look at an example for the createElement() method −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>createElement() example</h1>
<p>Click the below button to create more buttons</p>
<button onclick="createButton()">CREATE</button>
<br><br>
<script>
   var i=0;
   function createButton() {
      i++;
      var btn = document.createElement("BUTTON");
      btn.innerHTML="BUTTON"+i;
      var br= document.createElement("BR");
      document.body.appendChild(btn);
      document.body.appendChild(br);
   }
</script>
</body>
</html>
This will produce the following output −
On clicking the CREATE button three times. One click for one button −
In the above example −
We have created a button CREATE that will execute the createButton() method on being clicked by the user.
<button onclick="createButton()">CREATE</button>
The createButton() function creates a <button> element using the createElement() method of the document object. Using the innerHTML, we set the text that will be displayed on the top of the button. We create another element <br> using the createElement() method of the document object. The <button> element and the <br> element are then appended to the document body using the appendChild() method −
var i=0;
function createButton() {
   i++;
   var btn = document.createElement("BUTTON");
   btn.innerHTML="BUTTON"+i;
   var br= document.createElement("BR");
   document.body.appendChild(btn);
   document.body.appendChild(br);
}
C library function - fmod()

The C library function double fmod(double x, double y) returns the remainder of x divided by y.
Following is the declaration for fmod() function.
double fmod(double x, double y)
x − This is the floating point value with the division numerator i.e. x.
x − This is the floating point value with the division numerator i.e. x.
y − This is the floating point value with the division denominator i.e. y.
y − This is the floating point value with the division denominator i.e. y.
This function returns the remainder of dividing x/y.
The following example shows the usage of fmod() function.
#include <stdio.h>
#include <math.h>

int main () {
   float a, b;
   int c;
   a = 9.2;
   b = 3.7;
   c = 2;
   printf("Remainder of %f / %d is %lf\n", a, c, fmod(a,c));
   printf("Remainder of %f / %f is %lf\n", a, b, fmod(a,b));
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Remainder of 9.200000 / 2 is 1.200000
Remainder of 9.200000 / 3.700000 is 1.800000


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Sum of rows based on column value in R dataframe - GeeksforGeeks

01 Apr, 2021
In this article, we will be discussing how we can sum up row values based on column value in a data frame in R Programming Language. Suppose you have a data frame like this:
 
fruits
shop_1
shop_2
1.
Apple
1
13
2.
Mango
9
5
3.
Strawberry
2
14
4.
Apple
10
6
5.
Apple
3
15
6.
Strawberry
11
7
7.
Mango
4
16
8.
Strawberry
12
8
This dataset consists of fruits name and shop_1, shop_2 as a column name. Here shop_1 and shop_2 show the number of fruits available in shops. Now you want to find the aggregate sum of all the rows in shope_1 that have the same fruit value. So our dataset looks like this :
 
fruits
shop_1
shop_2
1.
Apple
14
34
2.
Mango
13
21
3.
Strawberry
25
29
The aggregate function creates a subset of the original data and computes the statistical function for each subset and returns the result.
Syntax:
aggregate(.~fruit,data=df,FUN=sum)
Example:
R
# Sum of rows based on column values  # Creating dataset # creating fuits columnx <- c("Apple","Mango","Strawberry",       "Apple","Apple","Strawberry",       "Mango","Strawberry")  # creating shop_1 columny <- c(1,9,2,10,3,11,4,12)  # creating shop_2 columnz <- c(13,5,14,6,15,7,16,8)  # creating dataframedf <- data.frame(fruits=x,shop_1=y,shop_2=z)  # applying aggregate functionaggregate(.~fruits,data=df,FUN=sum)
Output:
Using aggregate function
ddply  simply split the given data frame and perform any  operation on it (probably apply a  function) and return the data frame.
colwise is a function from the famous plyr package. colwise function is used to compute a function on each column in data frame, it computes column wise.
Example:
R
# Sum of rows based on column values  # loading librarylibrary(plyr)  # Creating dataset # creating fuits columnx <- c("toy1","toy2","toy3",       "toy1","toy1","toy3",       "toy2","toy3")  # creating stock_1 columny <- c(1,2,3,4,5,6,4,8)  # creating stock_2 columnz <- c(9,1,10,5,2,6,4,8)  # creating dataframedf <- data.frame(toys=x,stock_1=y,stock_2=z)  # using sum function colwiseddply(df,"toys",numcolwise(sum))
Output: 
Using ddply
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Merge DataFrames by Column Names in R
Java program to calculate mean of given numbers

Mean is an average value of given set of numbers. It is calculated similarly to that of the average value. Adding all given number together and then dividing them by the total number of values produces mean.
For Example 
Mean of 3, 5, 2, 7, 3 is (3 + 5 + 2 + 7 + 3) / 5 = 4
Take an integer set A of n values.
Add all values of A together.
Divide result of Step 2 by n.
The result is mean of A's values.
public class CaculatingMean {
   public static void main(String args[]){
      float mean;
      int sum, i;
      int n = 5;
      int a[] = {2,6,7,4,9};
      sum = 0;

      for(i = 0; i < n; i++) {
         sum+=a[i];
      }
      System.out.println("Mean ::"+ sum/(float)n);
   }
}
Mean::5.6
C++ program to Reverse a Sentence Using Recursion

A string is a one dimensional character array that is terminated by a null character. The reverse of a string is the same string in opposite order. For example.
Original String: Apple is red
Reversed String: der si elppA
A program that reverses a sentence in the form of a string using recursion is given as follows.
 Live Demo
#include <iostream>
using namespace std;
void reverse(char *str) {
   if(*str == '\0')
   return;
   else {
      reverse(str+1);
      cout<<*str;
   }
}
int main() {
   char str[] = "C++ is fun";
   cout<<"Original String: "<<str<<endl;
   cout<<"Reversed String: ";
   reverse(str);
   return 0;
}
Original String: C++ is fun
Reversed String: nuf si ++C
In the above program, the function reverse() is a recursive function that reverses a string.
Initially reverse() accepts *str which is a pointer that points to the start of the string. If the value is null, then the function returns. If not, then the function recursively calls itself with the value str+1 i.e the next element in the string. Eventually, when str is null, the values of str are printed for back to front. So, the reversed string is printed. This is shown by the following code snippet.
if(*str == '\0')
   return;
   else {
      reverse(str+1);
      cout<<*str;
   }
In the main() function, the string is initialized. Also, the original string and the reversed string are displayed. This is shown as follows −
char str[] = "C++ is fun";
cout<<"Original String: "<<str<<endl;
cout<<"Reversed String: ";
reverse(str);
Calling a method using null in Java - GeeksforGeeks

29 Oct, 2017
Prerequisite: null in Java, Static in Java
Can you predict the output of the following program??Before answering, please observe the fact that in given code, fun() is a static member that belongs to the class and not to any instance.
// Java program to illustrate calling// static method using Nullpublic class GFG {    public static void fun()    {        System.out.println("Welcome to GeeksforGeeks!!");    }      public static void main(String[] args)    {        ((GFG)null).fun();    }}
Output:
Welcome to GeeksforGeeks!!
Explanation:This program looks as though it is ought to throw a NullPointerException. However, the main method invokes the greet method (fun) on the constant null, and you can’t invoke a method on null.But, when you run the program, it prints “Welcome to GeeksforGeeks!!”. Let’s see how:
The key to understanding this puzzle is that GFG.fun is a static method.
Although, it is a bad idea to use an expression as the qualifier in a static method invocation, but that is exactly what this program does.
Not only does the run-time type of the object referenced by the expression’s value play no role in determining which method gets invoked, but also the identity of the object, if any, plays no role.
In this case, there is no object, but that makes no difference. A qualifying expression for a static method invocation is evaluated, but its value is ignored. There is no requirement that the value be non-null.
This article is contributed by Shubham Juneja. 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-Functions
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
Find common elements in list of lists in Python

It is possible to have a list whose inner elements are also lists. In such cases we may come across a need when we have to find out the common elements among these inner lists. In this article we will find out the approaches to achieve this.
Intersection is a simple mathematical concept of finding the common elements between different sets. Python has the set method which returns a set that contains the similarity between two or more sets. So we first convert the elements of the list into set through a map function and then apply the set method to all this converted lists.
 Live Demo
listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]

# Given list
print("Given list of lists : \n",listA)

# Applying intersection
res = list(set.intersection(*map(set, listA)))

# Result
print("The common elements among inners lists : ",res)
Running the above code gives us the following result −
Given list of lists :
[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]
The common elements among inners lists : ['Tue', 7]
We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them .
 Live Demo
from functools import reduce
listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]

# Given list
print("Given list of lists : \n",listA)

# Applying reduce
res = list(reduce(lambda i, j: i & j, (set(n) for n in listA)))

# Result
print("The common elements among inners lists : ",res)
Running the above code gives us the following result −
Given list of lists :
[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]
The common elements among inners lists : ['Tue', 7]
C++ List Library - list() Function

The C++ fill constructor std::list::list() constructs a new list with n elements and assign zero value to each element of list.
Following is the declaration for std::list::list() constructor form std::list header.
explicit list (size_type n);

n − Number of elements to be inserted into container.
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::list::list() constructor.
#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l(5);

   cout << "List contains following element" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
List contains following element
0
0
0
0
0

 Print
 Add Notes
 Bookmark this page
How to change the DPI of a Pandas Dataframe Plot in Matplotlib?

To change the DPI of a Pandas DataFrame plot, we can use rcParams to set the dot per inch.
Set the figure size and adjust the padding between and around the subplots.
Set the DPI values in .rcParams["figure.dpi"] = 120
Create a Pandas dataframe to make a plot.
Plot the dataframe.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

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

plt.rcParams["figure.dpi"] = 120

data = pd.DataFrame({"column1": [4, 6, 7, 1, 8]})
data.plot()

plt.show()
How to convert time seconds to h:m:s format in Python?

If you have a function that returns information in seconds, but you need that information in hours:minutes:seconds format, you can use the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
seconds = 56741
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print "%d:%02d:%02d" % (h, m, s)
This will give the output −
15:45:41
You can also use the timedelta function to get the same functionality but at a cost to performance. 
import datetime
timedelta_obj = datetime.timedelta(seconds=56741)
print(timedelta_obj)
This will give the output −
15:45:41
What is the role of Browser Object Model (BOM) in JavaScript?

The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser.
BOM provides you with a window objects, for example, to show the width and height of the window. It also includes the window.screen object to show the width and height of the screen.
You can try to run the following code to learn how to get screen height and width −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         document.write("Screen width: " + screen.width);
         document.write("<br>Screen width: " + screen.width);
      </script>
   </body>
</html>
SQL Tryit Editor v1.6

SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Naming Conventions in C#

A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The following are the conventions for class names.
The coding conventions for a class name is the the name of the class names, for example, it should being PascalCasing.
public class EmployeeDetails {}
Above, the class name EmployeeDetails is in PascalCasing.
Prefer adding class names as noun or noun phrases −
public class Employee {}

Identifier is a name used to identify a class, variable, function, or any other user-defined item.The following are the naming convetions for Identifiers −
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a C# keyword.
It should not be a C# keyword.
C# Program to get the absolute value of the time

To get the absolute value of time, use the TimesSpan Duration() method.
Let’s say the following is our TimeSpan.
TimeSpan ts = new TimeSpan(-7, -50, -25);
Now to get the absolute value.
TimeSpan duration = ts.Duration();
Let us see the complete code.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan ts = new TimeSpan(-7, -50, -25);
      TimeSpan duration = ts.Duration();
      Console.WriteLine(duration);
   }
}
07:50:25
Grav - Modular Pages

Modular pages are difficult to understand at first but once you get to know about it, it would be very easy to work with. It enables to create a single page from its child pages. It has the ability to build complex one page layouts from modular content pages.
Modular pages are set as non-routable because they cannot be reached directly through an URL. They are identified by _ (underscore) before the folder name. It is a collection of pages that are displayed one above each to get a single page. For example, user/pages/home/_header..
In case of one-page skeleton, you can find this page in the 01.home folder. In this, you get a single modular .md file that tells which pages must be included and the order of the pages to display. modular.html.twig can be found in your present theme folder.
In the image below, you can see a folder structure that has been created for modular pages.
Every sub-folder must contain a .md file that describes a markdown file.
Firstly, you must create sub folders in /users/pages/01.home folder. Next, each folder must contain a .md file and a modular.md file.
When you create the sub folder, the image and file both must be in the same folder.
To create modular pages, you must follow the given steps.
Step 1 − Create a few pages in /user/pages/01.home/. folder. In the image below, you can see we have created two folders along with a modular.md file.
Step 2 − To create a modular page, you must create a file in each folder and name it as text.md.
Step 3 − Next, add your code in text.md file, save it and run the same.
Example
Save all the four pages as .md file. Here we have created 4 pages and named as text.md, text1.md, text2.md and text3.md.
---
title: Bio-diversity
---

## Bio-diversity

Biodiversity refers to the variety of life. It is seen in the number of species in an 
[ecosystem](https://simple.wikipedia.org/wiki/Ecosystem) or on the entire [Earth]
(https://simple.wikipedia.org/wiki/Earth). Biodiversity gets used as a measure of the
health of biological systems, and to see if there is a danger that too many species
become[extinct](https://simple.wikipedia.org/wiki/Extinct).

Now, create 4 pages, add them to the \templates\modular folder as shown below.
Next, go to home page and refresh, you can see the changes.
In the new navigation bar, you can see the four file links.

    19 Lectures 
     3 hours 

 Mr. Pradeep Kshetrapal

    30 Lectures 
     4 hours 

 Priyanka Choudhary

    55 Lectures 
     4.5 hours 

 University Code

    24 Lectures 
     1 hours 

 Mike Clayton
 Print
 Add Notes
 Bookmark this page
How to get Resource name using Resource id in Android?

This example demonstrates how do I get resource name using Resource id in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:text=""
      android:textSize="16sp"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      int text = textView.getId();
      String string = getResources().getResourceName(text);
      textView.setText("Resource ID: " + string);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
What is the use of ALLOW_INVALID_DATES SQL mode?

As the name suggests, enabling ALLOW_INVALID_DATES SQL mode will allow us to store invalid dates in the table. The example is given below to understand it −
mysql> SET sql_mode = ALLOW_INVALID_DATES;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> Insert Into detail_bday(Name, Birth_Date) values('Sonia','1993-11-31');
Query OK, 1 row affected (0.09 sec)

mysql> Insert Into detail_bday(Name, Birth_Date) values('Ram','0000-00-00');
Query OK, 1 row affected (0.10 sec)

mysql> Select * from detail_bday;
+----+---------+------------+
| Sr | Name    | Birth_Date |
+----+---------+------------+
| 1  | Saurabh | 1990-05-12 |
| 2  | Raman   | 1993-06-11 |
| 3  | Gaurav  | 1984-01-17 |
| 4  | Rahul   | 1993-06-11 |
| 5  | Sonia   | 1993-11-31 |
| 6  | Ram     | 0000-00-00 |
+----+---------+------------+
6 rows in set (0.00 sec)
Above result set shows that MySQL allows us to store invalid date like ‘1993-11-31’ and ‘0000-00-00’ after enabling the ALOOW_INVALID_DATES SQL mode.
How to include groups of table columns in HTML?

Use the <colgroup> tag to include groups of table columns.The HTML <colgroup> tag is used for specifying properties for a group of columns within a table. If you need to apply different properties to a column within a colgroup, you can use the HTML col tag within the colgroup tag.
The following are the attributes −
You can try to run the following code to implement <colgroup> tag in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML col Tag</title>
   </head>
   <body>
      <p>This example shows a colgroup that has three columns of different widths:</p>
      <table border = "1">
         <colgroup span = "4">
            <col width = "40"></col>
            <col width = "70"></col>
            <col width = "100"></col>
            <col width = "130"></col>
            <col width = "160"></col>
            </colgroup>
         <tr>
            <td>One</td>
            <td>Two</td>
            <td>Three</td>
            <td>Four</td>
            <td>Five</td>
         </tr>
      </table>
   </body>
</html>
Iterator vs Collection in Java - GeeksforGeeks

16 Sep, 2021
Iterator and Collection, both has helped and comforted the programmers at many a times. But there usage and application has a very wide difference. 
1. Iterator 
Declaration 
public interface Iterator

Type Parameters:
E - the type of elements returned by this iterator
Iterators are used in Collection framework in Java to retrieve elements one by one. 
Method Summary 
2. Collection 
Declaration: 
public interface Collection<E> extends Iterable<E>

Type Parameters:
E - the type of elements returned by this iterator
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. 
Method Summary 
Iterator Vs. Collection  
Iterator can only move to next() element or remove() an element. However Collection can add(), iterate, remove() or clear() the elements of the collection. 
Iterator provides a better speed than Collections, as the Iterator interface has limited number of operations. 
java.sql.SQLException extends Iterable. Hence it allows the caller to safely iterate over causes of SQLException. Using a collection, in this case, would be expensive because, in a chain of n exceptions, use of a collection in the SQLException interface would potentially require the construction of O(n^2) elements. However, use of Iterable provides O(n) access to the exception chain.  
 
chhabradhanvi
Java - util package
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
React JS useRef Hook - GeeksforGeeks

19 Oct, 2021
The useRef hook is the new addition in React 16.8. Before proceeding to this article there is a prerequisite to know about the ref in react.The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. 
Syntax:
const refContainer = useRef(initialValue);
The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component. 
Example: How to access the DOM using useRef hook.
Javascript
import React, {Fragment, useRef} from 'react'; function App() {   // Creating a ref object using useRef hook  const focusPoint = useRef(null);  const onClickHandler = () => {    focusPoint.current.value =      "The quick brown fox jumps over the lazy dog";      focusPoint.current.focus();  };  return (    <Fragment>      <div>        <button onClick={onClickHandler}>         ACTION        </button>      </div>      <label>       Click on the action button to       focus and populate the text.      </label><br/>      <textarea ref={focusPoint} />    </Fragment>  );}; export default App;
  
Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook. The focusPoint is the useRef object which is initialised to null and the value is changing to onClick event. Let’s see the output of the above code.
 
 
surindertarika1234
mikkey
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to apply style to parent if it has child with CSS?
Python | Key-Value to URL Parameter Conversion - GeeksforGeeks

13 Aug, 2019
Many times, while working in web development domain, we can encounter a problem in which we require to set as URL parameter some of the key-value pairs we have, either in form of tuples, or a key and value list. Let’s discuss a solution for both the cases.
Method #1 : Using urllib.urlencode() ( with tuples )The urlencode function is root function that can perform the task that we wish to achieve. In case of tuples, we can just pass the tuples and encoder does the rest of conversion of string. Works only with Python2.
# Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with tuples )import urllib  # initializing tuplestest_tuples = (('Gfg', 1), ('is', 2), ('best', 3))  # printing original tuplesprint("The original tuples are : " + str(test_tuples))  # Using urllib.urlencode() ( with tuples )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_tuples)  # printing URL stringprint("The URL parameter string is : " + str(res))
The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : Gfg=1&is=2&best=3

 
Method #2 : Using urllib.urlencode() ( with dictionary value list )This method is when we have a dictionary key and many values corresponding to them as a potential candidate for being the URL parameter. In this case we perform this function. This also works with just Python2.
# Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with dictionary value list )import urllib  # initializing dictionarytest_dict = {'gfg' : [1, 2, 3]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using urllib.urlencode() ( with dictionary value list )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_dict, doseq = True)  # printing URL stringprint("The URL parameter string is : " + str(res))
The original dictionary is : {'gfg': [1, 2, 3]}
The URL parameter string is : gfg=1&gfg=2&gfg=3

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
MATLAB | Convert video into slow motion - GeeksforGeeks

29 Mar, 2019
MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, python, java etc.
Video:A video is a set of images known as frames. It contains four dimensions i.e. 1st dimension is for the rows, the 2nd one is for the columns, 3rd is for the RGB channel representation and the other dimension also gets added called time or frame number.
Framerate:Frame rate is defined as the number of frames per second or fps. It is the frequency (rate) at which consecutive images called frames to appear on a display.
To convert a video in slow motion we have the decrease framerate of the video.
Approach:
Load the video into a variable obj by using VideoReader()
Use a new variable obj2 to create a new copy of this video which is appearing in fast mode by usingVideoWriter()
decrease the framerate of the video.
open obj2.
read all the frames one by one from obj and store them into a variable k.
Write all the frames in obj2 using writeVideo()
Close obj2.
To get the link to the input video, click here.
Below is the imnplementaions:
% MATLAB program to convert video into slow motionclc;clear;close all;   % load the video.obj = VideoReader('C:/Users/Gfg/Desktop/Sample1280.avi');    % Write in new variableobj2= VideoWriter('xyz.avi');      % decrease framerate obj2.FrameRate = 10;              open(obj2);  % for reading frames one by onewhile hasFrame(obj)                  k = readFrame(obj);       % write the frames in obj2.             obj2.writeVideo(k);          end  close(obj2);
Output:
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
System Design Tutorial
Decision Tree Introduction with example
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
KDD Process in Data Mining
column command in Linux with examples - GeeksforGeeks

28 Sep, 2021
column command in Linux is used to display the contents of a file in columns. The input may be taken from the standard input or from the file. This command basically breaks the input into multiple columns. Rows are filled before columns. Empty lines from the input are ignored unless the -e option is used. 
Syntax: 
column [-entx] [-c columns] [-s sep] [file ...]
Example:  
Suppose you have a text file with the following contents: 
sample file
To display the information of the text file in form of columns, you enter the command: 
column filename.txt
displays result
Suppose, you want to sort into different columns the entries that are separated by particular delimiters. For example, this sample text file: 
Sample text file
To separate the column based on the delimiter “|”, you would give the following command, which in turn produces the given output: 
output based on delimiter specified
In case you give multiple delimiters(same type), the command treats them as a single one. For example: 
sample text file
Upon application of command yields the output: 
Output(with multiple delimiters of same type)
Options:  
-J : This option specifies the system to display the output in JSON format.
-c : Defines the width of the output based upon the total number of characters allowed in one row.
-d : Used to define that the header is NOT to be printed.
-N : It defines the column names, and each name is separated by a comma(“, “).
-H : It is used to hide the specified columns from being displayed.
-V : Displays version information and exits.
-h : Shows help information and exits.
-s : Defines the column delimiter for output.
-t : Applied for creating a table by determining the number of columns.
-R : Used to right-align text in a specific column.
-T : Allows the system to truncate text wherever necessary so that the column width can be adjusted to ensure that the column doesn’t become too wide.
-O : Allows the user to define the order in which columns have to be displayed.
-L : Inserts empty lines after each row.
 
varshagumber28
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
ps command in Linux with Examples
How to get the default blue colour of matplotlib.pyplot.scatter?

The default color of a scatter point is blue. To get the default blue color of matplotlib scatter point, we can annotate them using annotate() method.
Create a figure and a set of subplots using subplots() method.
Plot a scatter point at (-1, 1) location.
Add some label for that point.
Plot a scatter point at (-0.9, 1) location.
Add some label for that point.
Plot a scatter point at (1.9, 1) location.
Add some label for that point.
Scale the x and y axes using xlim and ylim method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.scatter(-1, 1)
ax.annotate("default color", xy=(-0.9, 1))
ax.scatter(1, 1, c='#1f77b4')
ax.annotate("using hex", xy=(1.1, 1))
ax.set_xlim(-2, 3)
ax.set_ylim(-1, 2)
plt.show()
Remove item from a nested array by indices in JavaScript

Suppose, we have a nested array of objects like this −
const arr = [
   { value: 'some value' },
   {
      array: [
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               { value: 'some value' },
            ],
         },
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               {
                  array: [
                     { value: 'delete me' },
                     { value: 'some value' },
                  ]
               },
            ],
         },
      ],
   }
];
We are required to write a JavaScript function that takes in one such array as the first argument and an array of indices as the second argument.
Our function should delete the value property at all the indices specified by the array (second argument).
The code for this will be −
const arr = [
   { value: 'some value' },
   {
      array: [
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               { value: 'some value' },
            ],
         },
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               {
                  array: [
                     { value: 'delete me' },
                     { value: 'some value' },
                  ]
               },
            ],
         },
      ],
   }
];
const keys = [1, 3, 1, 0];
const getKeys = (arr, keys) => {
   const recursiveFind = (arr, level) => {
      const res = [];
      arr.forEach((el, ind) => {
         if (keys[level] !== ind) {
            return res.push(el);
         };
         if (level + 1 !== keys.length && el.array) {
            res.push({ array: recursiveFind(el.array, level + 1) });
         };
      });
      return res;
   };
   return recursiveFind(arr, 0);
};
console.log(JSON.stringify(getKeys(arr, keys), undefined, 4));
And the output in the console will be −
[
   {
      "value": "some value"
   },
   {
      "array": [
         {
            "value": "some value"
         },
         {
            "array": [
               {
                  "value": "some value"
               },
               {
                  "value": "some value"
               }
            ]
         },
         {
            "value": "some value"
         },
         {
            "array": [
               {
                  "value": "some value"
               },
               {
                  "array": [
                     {
                        "value": "some value"
                     }
                  ]
               }
            ]
         }
      ]
   }
]
Machine Learning - Correlation Matrix Plot

Correlation is an indication about the changes between two variables. In our previous chapters, we have discussed Pearson’s Correlation coefficients and the importance of Correlation too. We can plot correlation matrix to show which variable is having a high or low correlation in respect to another variable.
In the following example, Python script will generate and plot correlation matrix for the Pima Indian Diabetes dataset. It can be generated with the help of corr() function on Pandas DataFrame and plotted with the help of pyplot.
from matplotlib import pyplot
from pandas import read_csv
import numpy
Path = r"C:\pima-indians-diabetes.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(Path, names = names)
correlations = data.corr()
fig = pyplot.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlations, vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = numpy.arange(0,9,1)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(names)
ax.set_yticklabels(names)
pyplot.show()
From the above output of correlation matrix, we can see that it is symmetrical i.e. the bottom left is same as the top right. It is also observed that each variable is positively correlated with each other.

    168 Lectures 
     13.5 hours 

 Er. Himanshu Vasishta

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions

    91 Lectures 
     10 hours 

 Abhilash Nelson

    54 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     4 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
TypeScript - Strings

The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods.
var var_name = new String(string);

A list of the methods available in String object along with their description is given below −
Returns a reference to the String function that created the object.
Returns the length of the string.
The prototype property allows you to add properties and methods to an object.
A list of the methods available in String object along with their description is given below −
Returns the character at the specified index.
Returns a number indicating the Unicode value of the character at the given index.
Combines the text of two strings and returns a new string.
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
match()
Used to match a regular expression against a string.
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and a specified string.
Extracts a section of a string and returns a new string.
Splits a String object into an array of strings by separating the string into substrings.
Returns the characters in a string beginning at the specified location through the specified number of characters.
Returns the characters in a string between two indexes into the string.
The characters within a string are converted to lower case while respecting the current locale.
The characters within a string are converted to upper case while respecting the current locale.
Returns the calling string value converted to lower case.
Returns a string representing the specified object.
Returns the calling string value converted to uppercase.
Returns the primitive value of the specified object.

    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page