code-rag-bench/online-tutorials huggingface dataset:
How to create a Hero Image with CSS?

Following is the code to create a hero image with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body,
html {
   height: 100%;
   margin: 0;
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
*,
*::before,
*::after {
   box-sizing: border-box;
}
h1 {
   font-size: 60px;
   font-weight: bolder;
}
.heroContainer {
   background-image: linear-gradient( rgba(185, 255, 243, 0.5), rgba(31, 12, 117, 0.5) ),
   url("https://images.pexels.com/photos/670720/pexels-photo-670720.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");
   height: 50%;
   background-position: center;
   background-repeat: no-repeat;
   background-size: cover;
   position: relative;
}
.heroCaption {
   text-align: center;
   position: absolute;
   top: 20%;
   left: 45%;
   color: white;
}
.heroCaption button {
   border: none;
   outline: none;
   display: inline-block;
   padding: 20px;
   color: rgb(255, 255, 255);
   opacity: 0.8;
   font-size: 20px;
   background-color: rgb(47, 151, 21);
   text-align: center;
   cursor: pointer;
}
.heroCaption button:hover {
   opacity: 1;
}
</style>
</head>
<body>
<div class="heroContainer">
<div class="heroCaption">
<h1>I am Shawn</h1>
<h2>And I'm a Web Developer</h2>
<button>Contact Me</button>
</div>
</div>
</body>
</html>
The above code will produce the following output −
React Native - App

If you open the default app you can observe that the app.js file looks like
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
   render() {
      return (
         <View style = {styles.container}>
            <Text>Open up App.js to start working on your app!</Text>
            <Text>Changes you make will automatically reload.</Text>
            <Text>Shake your phone to open the developer menu.</Text>
         </View>
      );
   }
}

const styles = StyleSheet.create({
   container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
   },
});
To display a simple message saying “Welcome to Tutorialspoint” remove the CSS part and insert the message to be printed wrapped by the <text></text> tags inside <view></view> as shown below.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
   render() {
      return (
         <View>
            <Text>Welcome to Tutorialspoint</Text>
         </View>
      );
   }
}

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to use count with CASE condition in a MySQL query?

Use CASE WHEN for this in MySQL and set CASE condition inside the COUNT() method to count. Let us first create a table −
mysql> create table DemoTable1374
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Score int
   -> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1374(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1374(Name,Score) values('David',78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Bob',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1374(Name,Score) values('Mike',75);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Carol',45);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1374(Name,Score) values('Adam',89);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1374;
This will produce the following output −
+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
|  1 | Chris |    45 |
|  2 | David |    78 |
|  3 | Bob   |    45 |
|  4 | Mike  |    75 |
|  5 | Carol |    45 |
|  6 | Adam  |    89 |
+----+-------+-------+
6 rows in set (0.00 sec)
Following is the query for CASE WHEN to set condition and count −
mysql> select count( case when Score=45 then 1 else NULL end) as  SpecificCondition from DemoTable1374;
This will produce the following output −
+-------------------+
| SpecificCondition |
+-------------------+
|                 3 |
+-------------------+
1 row in set (0.00 sec)
Python VLC MediaPlayer – Taking Screenshot - GeeksforGeeks

18 Aug, 2020
In this article we will see how we can take screen shot of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. A screenshot, also known as ss, sc, screen capture, or screen grab, is a digital image that shows the contents of a computer display. A common screenshot is created by the operating system or software running on the device. A screenshot or screen capture may also be created by taking a photo of the screen.
In order to do this we will use video_take_snapshot method with the MediaPlayer object
Syntax : media_player.video_take_snapshot(n, location, width, height)
Argument : It takes video output number, folder location and width and height of screenshot as argument
Return : It returns 0 on success, -1 if the video was not found
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time    # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("death_note.mkv")  # setting media to the media playermedia_player.set_media(media)  # setting video scalemedia_player.video_set_scale(0.6)  # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)  # taking screen shotmedia_player.video_take_snapshot(0, "F://test", 400, 300)
Output :
Below is the folder location
Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("1mp4.mkv")  # setting media to the media playermedia_player.set_media(media)    # setting video scalemedia_player.video_set_scale(0.6)  # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)    # taking screen shotmedia_player.video_take_snapshot(0, "F://test", 400, 300)
Output :
Below is the folder location
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
OpenCV - Rotation

You can perform rotation operation on an image using the warpAffine() method of the imgproc class. Following is the syntax of this method −
Imgproc.warpAffine(src, dst, rotationMatrix, size);

This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
rotationMatrix −  A Mat object representing the rotation matrix.
rotationMatrix −  A Mat object representing the rotation matrix.
size −  A variable of the type integer representing the size of the output image.
size −  A variable of the type integer representing the size of the output image.
The following program demonstrates how to rotate an image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Rotation {
   public static void main(String args[]) {
      // Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap24/transform_input.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Creating a Point object
      Point point = new Point(300, 200)

      // Creating the transformation matrix M
      Mat rotationMatrix = Imgproc.getRotationMatrix2D(point, 30, 1);

      // Creating the object of the class Size
      Size size = new Size(src.cols(), src.cols());

      // Rotating the given image
      Imgproc.warpAffine(src, dst, rotationMatrix, size);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap24/rotate_output.jpg", dst);

      System.out.println("Image Processed");
   }
}
Assume that following is the input image transform_input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
Flipping an Image in Python

Suppose we have a binary matrix A, this is the representation of an image, we want to flip the image horizontally, after that invert it, and finally return the resulting image. To flip the image horizontally each row of the image will be reversed. And to invert the image each 0 will be replaced by 1, and each 1 will be replaced by 0.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
result:= a new list
for each row i in A, doReverse:= reverse row ifor j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1insert Reverse at the end of result
Reverse:= reverse row i
for j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1
if Reverse[j] is same as 1, thenReverse[j]:= 0
Reverse[j]:= 0
otherwise,Reverse[j]:= 1
Reverse[j]:= 1
insert Reverse at the end of result
return result
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def flipAndInvertImage(self, A):
      result=[]
      for i in A:
         Reverse=i[::-1]
         for j in range(len(Reverse)):
            if Reverse[j]==1:
               Reverse[j]=0
            else:
               Reverse[j]=1
               result.append(Reverse)
      return result
ob = Solution()
print(ob.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
[[1,1,0],[1,0,1],[0,0,0]]
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
Validate Date in MySQL using a custom function

Let us create a custom function to validate date in MySQL −
mysql> set global log_bin_trust_function_creators=1;
Query OK, 0 rows affected (0.03 sec)
mysql> delimiter //
mysql> create function isValidDate(actualDate varchar(255)) returns int
   -> begin
   -> declare flag int;
   -> if (select length(date(actualDate)) IS NOT NULL ) then
   -> set flag = 1;
   -> else
   -> set flag = 0;
   -> end if;
   -> return flag;
   -> end
   -> //
Query OK, 0 rows affected (0.11 sec)
mysql> delimiter ;
Case 1 −
When parameter is null value i.e. the date to be checked isn’t an actual date. Call the function using SELECT statement −
mysql> select isValidDate(NULL);
This will produce the following output i.e. not a date −
+-------------------+
| isValidDate(NULL) |
+-------------------+
| 0                 |
+-------------------+
1 row in set (0.05 sec)
Case 2 −
When parameter is an actual date value. Call the function using SELECT statement −
mysql> select isValidDate('2019-10-21');
This will produce the following output i.e. 1, an actual date −
+---------------------------+
| isValidDate('2019-10-21') |
+---------------------------+
| 1                         |
+---------------------------+
1 row in set (0.00 sec)
Do you think Python Dictionary is really Mutable?

Yes, Python Dictionary is mutable. Changing references to keys doesn't lead to the creation of new dictionaries. Rather it updates the current dictionary in place. 
a = {'foo': 1, 'bar': 12}
b = a
b['foo'] = 20

print(a)
print(b)
This will give the output −
{'foo': 20, 'bar': 12}
{'foo': 20, 'bar': 12}
Difference between Inline and Macro in C++ - GeeksforGeeks

28 Jun, 2020
1. Inline :An inline function is a normal function that is defined by the inline keyword. An inline function is a short function that is expanded by the compiler. And its arguments are evaluated only once. An inline functions are the short length functions that are automatically made the inline functions without using the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{ 
 // inline function code
}

Example of an Inline function:
#include <iostream>using namespace std;  // Inline functioninline int Maximum(int a, int b){    return (a > b) ? a : b;}  // Main function for the programint main(){    cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;    cout << "Max (20, 0): " << Maximum(20, 0) << endl;      return 0;}
Output:
Max (100, 1000): 1000
Max (20, 0): 20 
2. Macro :It is also called preprocessors directive. The macros are defined by the #define keyword. Before the program compilation, the preprocessor examines the program whenever the preprocessor detects the macros then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition 
Example of Macro:
#include <iostream>using namespace std;  // macro with parameter#define MAXIMUM(a, b) (a > b) ? a : b  // Main function for the programint main(){    cout << "Max (100, 1000):";    int k = MAXIMUM(100, 1000);    cout << k << endl;      cout << "Max (20, 0):";    int k1 = MAXIMUM(20, 0);    cout << k1;      return 0;}
Output:
Max (100, 1000):1000
Max (20, 0):20 
Difference between Inline and Macro in C++ :
pp_pankaj
ashushrma378
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Timer in C#

The namespace used to set a timer is System. Timers. The Timer class generates an event after a set interval, with an option to generate recurring events.
Firstly, create a timer object for 5 seconds interval −
timer = new System.Timers.Timer(5000);
Set elapsed event for the timer. This occurs when the interval elapses −
timer.Elapsed += OnTimedEvent;
Now start the timer.
timer.Enabled = true;
using System;
using System.Timers;

public class Demo {
   private static Timer timer;

   public static void Main() {
      timer = new System.Timers.Timer();
      timer.Interval = 5000;

      timer.Elapsed += OnTimedEvent;
      timer.AutoReset = true;
      timer.Enabled = true;

      Console.WriteLine("Press the Enter key to exit anytime... ");
      Console.ReadLine();
   }

   private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      Console.WriteLine("Raised: {0}", e.SignalTime);
   }
}
What does abstract modifier in Java do?

An abstract keyword is used to declare methods abstract methods and abstract classes. Once a method is declared abstract we should not specify body for those.
public abstract class Sample{
   public abstract demo(){
   }
}
Sample.java:2: error: invalid method declaration; return type required
   public abstract demo(){
                   ^
1 error

And once a class is declared abstract it cannot be instantiated.
public abstract class Sample{
   public abstract void demo();
   public static void main(String args[]){
      new Sample();
   }
}
C:\Sample>javac Sample.java
Sample.java:4: error: Sample is abstract; cannot be instantiated
   new Sample();
   ^
1 error
How to display animated gif images in Android?

This example demonstrates how do I display animated gif images 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.
Add the following dependency in build.gradle: Module: app
implementation 'com.github.bumptech.glide:glide:4.9.0'
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"
   android:padding="4dp"
   tools:context=".MainActivity">
   <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/imageView"/>
   <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:onClick="ShowGif"
      android:textAlignment="center"
   android:text="SHOW GIF"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void ShowGif(View view) {
      ImageView imageView = findViewById(R.id.imageView);
      Glide.with(this).load(R.drawable.tenor).into(imageView);
   }
}
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 the 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.
Updating Strings in Python

You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −
 Live Demo
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result −
Updated String :- Hello Python
How to use pip to install python modules in easy way?

If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:
On Linux or macOS:
pip install -U pip setuptools
On Windows:
python -m pip install -U pip setuptools
If you’re using a Python install on Linux that’s managed by the system package manager (e.g "yum", "apt-get" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/
Otherwise:
Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip.
Now you can use pip to install python packages. For example, To install the latest version of "SomeProject":
$ pip install 'SomeProject'
To install a specific version:
$ pip install 'SomeProject==1.4'
To install greater than or equal to one version and less than another:
$ pip install 'SomeProject>=1,<2'
Get the longest and shortest string in an array JavaScript

We have an array of string literals like this −
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
We are required to write a function that returns the longest and the shortest word from this array. We will use Array.prototype.reduce() method to keep track of the longest and shortest word in the array through a complete iteration.
The code for this will be −
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
const findWords = (arr) => {
   return arr.reduce((acc, val) => {
      const { length: len } = val;
      if(len > acc['longest']['length']){
         acc['longest'] = val;
      }else if(len < acc['shortest']['length']){
         acc['shortest'] = val;
      };
      return acc;
   }, {
      longest: arr[0],
      shortest: arr[0]
   });
};
console.log(findWords(arr));
The output in the console will be −
{ longest: 'sentence.', shortest: 'a' }
Extract csv file specific columns to list in Python

To extract csv file for specific columns to list in Python, we can use Pandas read_csv() method.
Make a list of columns that have to be extracted.
Make a list of columns that have to be extracted.
Use read_csv() method to extract the csv file into data frame.
Use read_csv() method to extract the csv file into data frame.
Print the exracted data.
Print the exracted data.
Plot the data frame using plot() method.
Plot the data frame using plot() method.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:\n", df)
plt.plot(df.Name, df.Marks)
plt.show()
The csv file contains the following data −
When we execute the code, it will extract the data from the csv file and show the following plot −
How to convert a MySQL date to JavaScript date?

To convert a MySQL date to JavaScript, use Date.parse.
You can try to run the following code to convert MySQL date to JavaScript date −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         var MySQL_date = '2017-12-31 11:55:17';
         document.write("MySQL Date: "+MySQL_date);

         var jsDate = new Date(Date.parse(MySQL_date.replace(/[-]/g,'/')));
         document.write("<br>JavaScript Date: "+jsDate);
      </script>
   </body>
</html>
MySQL Date: 2017-12-31 11:55:17
JavaScript Date: Sun Dec 31 2017 11:55:17 GMT+0530 (India Standard Time)
MySQL Client Programs

There are 7 client programs, which are listed below −
mysql
mysql
mysqladmin
mysqladmin
mysqlcheck
mysqlcheck
mysqldump
mysqldump
mysqlimportmysqlpump
mysqlimportmysqlpump
mysqlshow
mysqlshow
mysqlslap
mysqlslap
Let us understand the MySQL client programs in brief −
The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format.
It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below −
shell> mysql db_name
The mysqladmin is a client that helps perform administrative operations. It can also be used to check the server's configuration and current status, to create and drop databases, and much more.
The mysqlcheck client performs table maintenance. It checks, repairs, optimizes, or analyses tables.
Every table is locked and hence unavailable to other sessions when it is being processed. But for check operations, the table is locked with a READ lock only.
The mysqldump client utility helps performs logical backups, thereby producing a set of SQL statements which can be executed to reproduce the original database object definitions and table data. It dumps one or more MySQL databases for backup or transfer to another SQL server.
The mysqldump command also generates output in CSV, other delimited text, or XML format. The utility mysqldump requires at least the SELECT privilege for dumped tables, SHOW VIEW for dumped views, TRIGGER for dumped triggers, LOCK TABLES if the --single-transaction option is not used, and PROCESS if --no-tablespaces option is not used.
The mysqlimport client comes with a command-line interface that helps with the LOAD DATA SQL statement. Most options to mysqlimport respond directly to clauses of LOAD DATA syntax
Let us understand the features of mysqlpump −
Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process.
Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process.
It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped
It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped
Dumping of user accounts as account-management statements (CREATE USER, GRANT)
instead of as inserts into the mysql system database
Dumping of user accounts as account-management statements (CREATE USER, GRANT)
instead of as inserts into the mysql system database
The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes. It provides a command-line interface for several SQL SHOW statements.
The mysqlslap utility is a diagnostic program that has designed to emulate client load for a MySQL server and report the timing of every stage. It works as though multiple clients are accessing the server.
PostgreSQL – DATE_TRUNC Function

01 Feb, 2021
In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision.
Syntax: date_trunc('datepart', field)

The datepart argument in the above syntax is used to truncate one of the field,below listed field type:
millennium
century
decade
year
quarter
month
week
day
hour
minute
second
milliseconds
microseconds
The field argument holds either a TIMESTAMP type value or an INTERVAL type value to truncate. It can also be an expression that returns one of the above mentioned type. The date_trunc function generally returns a TIMESTAMP type value or an INTERVAL type value.
Example 1:
The following statement truncates a TIMESTAMP value to hour date part:
SELECT DATE_TRUNC('hour', TIMESTAMP '2020-03-17 02:09:30');

Output:
Example 2:
The below query counts the number of rentals by staff per year from the rental table of the sample database, ie, dvdrental:
SELECT
    staff_id,
    date_trunc('year', rental_date) y,
    COUNT (rental_id) rental
FROM
    rental
GROUP BY
    staff_id, y
ORDER BY
    staff_id

Output:
PostgreSQL-Date-function
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove punctuation from string

30 Jun, 2021
Many times while working with Python strings, we have a problem in which we need to remove certain characters from strings. This can have application in data preprocessing in the Data Science domain and also in day-day programming. Let’s discuss certain ways in which we can perform this task. 
Method #1 : Using loop + punctuation string 
This is the brute way in which this task can be performed. In this, we check for the punctuations using a raw string which contain punctuations and then we construct string removing those punctuations. 
Python3
# Python3 code to demonstrate working of# Removing punctuations in string# Using loop + punctuation string # initializing stringtest_str = "Gfg, is best : for ! Geeks ;" # printing original stringprint("The original string is : " + test_str) # initializing punctuations stringpunc = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # Removing punctuations in string# Using loop + punctuation stringfor ele in test_str:    if ele in punc:        test_str = test_str.replace(ele, "") # printing resultprint("The string after punctuation filter : " + test_str)
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best  for  Geeks 
 
 Method #2 : Using regex 
The part of replacing with punctuation can also be performed using regex. In this, we replace all punctuation with an empty string using a certain regex. 
Python3
# Python3 code to demonstrate working of# Removing punctuations in string# Using regeximport re # initializing stringtest_str = "Gfg, is best : for ! Geeks ;" # printing original stringprint("The original string is : " + test_str) # Removing punctuations in string# Using regexres = re.sub(r'[^\w\s]', '', test_str) # printing resultprint("The string after punctuation filter : " + res)
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best  for  Geeks 
 
amiableabhishekkumar
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to count unique values inside a list

25 Jan, 2022
There are several methods for finding or counting unique items inside a list in Python. Here we’ll discuss 3 methods.
Method 1: 
The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start and check the items. If the item is not in the empty list(as it has taken empty) then we will add it to the empty list and increase the counter by 1. While traveling if the item is in the taken list(empty list) we will not count it. 
Example:  
Python3
# taking an input listinput_list = [1, 2, 2, 5, 8, 4, 4, 8] # taking an input listl1 = [] # taking an countercount = 0 # traversing the arrayfor item in input_list:    if item not in l1:        count += 1        l1.append(item) # printing the outputprint("No of unique items are:", count)
Output:
No of unique items are: 5
Method 2:
In this method, we will use a function name Counter. The module collections have this function. Using the Counter function we will create a dictionary. The keys of the dictionary will be the unique items and the values will be the number of that key present in the list.  We will create a list using the keys, the length of the list will be our answer.
Python3
# importing Counter modulefrom collections import Counter  input_list = [1, 2, 2, 5, 8, 4, 4, 8] # creating a list with the keysitems = Counter(input_list).keys()print("No of unique items in the list are:", len(items))
Output:
No of unique items in the list are: 5
If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable.
Method 3:
In this method, we will convert our list to set. As sets don’t contain any duplicate items then printing the length of the set will give us the total number of unique items.
Python3
input_list = [1, 2, 2, 5, 8, 4, 4, 8] # converting our list to setnew_set = set(input_list)print("No of unique items in the list are:", len(new_set))
Output:
No of unique items in the list are: 5
sagartomar9927
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add Matplotlib graph in Kivy ? - GeeksforGeeks

05 Apr, 2021
In this article, we will discuss how to add matplotlib graph in the kivy app.
Import matplotlib pyplot
Import numpy
Import FigureCanvas KivyAgg
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the Implementation.
Python3
# importing pyplot for graph plottingfrom matplotlib import pyplot as plt  # importing numpyimport numpy as npfrom kivy.garden.matplotlib import FigureCanvasKivyAgg  # importing kivyappfrom kivy.app import App  # importing kivy builderfrom kivy.lang import Builder    # this is the main class which will # render the whole applicationclass uiApp(App):      def build(self):        self.str = Builder.load_string("""   BoxLayout:    layout:layout          BoxLayout:              id:layout                                      """)          signal = [7, 89.6, 45.-56.34]          signal = np.array(signal)                  # this will plot the signal on graph        plt.plot(signal)                  # setting x label        plt.xlabel('Time(s)')                  # setting y label        plt.ylabel('signal (norm)')        plt.grid(True, color='lightgray')                  # adding plot to kivy boxlayout        self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf()))        return self.str    # running the applicationuiApp().run()
Output:
Note: When you run the below code this may throw the error given below
What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!
Python-kivy
Python
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 unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to find width and height of an image using Python? - GeeksforGeeks

13 Jan, 2021
In this article, we are going to discuss how to get the height and width of a particular image.
In order to find the height and width of an image, there are two approaches. The first approach is by using the PIL(Pillow) library and the second approach is by using the Open-CV library.
Approach 1:
PIL is the Python Imaging Library is an important module which is used for image processing. It supports many formats of images such as “jpeg”, “png”, “ppm”, “tiff”, “bmp”, “gif”.  It provides many image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. 
PIL.Image.open() is used to open the image and then .width and .height property of Image are used to get the height and width of the image. The same results can be obtained by using .size property.
To use pillow library run the following command:
pip install pillow
Image Used:
Image Used
Code:
Python
# import required modulefrom PIL import Image  # get imagefilepath = "geeksforgeeks.png"img = Image.open(filepath)  # get width and heightwidth = img.widthheight = img.height  # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Alternative:
An alternate way to get height and width is using .size property.
Example:
Image Used:
Image Used
Code:
Python
# import required modulefrom PIL import Image  # get imagefilepath = "geeksforgeeks.png"img = Image.open(filepath)  # get width and heightwidth,height = img.size  # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Approach 2:
OpenCV in python is a library which is used for computer vision, image processing and much more.  The imread(filepath) function is used to load an image from the file path specified. The .shape stores a tuple of height, width and no of channels for each pixel. The .shape[:2] will get the height and width of the image.
To install OpenCV run the following command:
pip install opencv-python
Code:
Python
# import required moduleimport cv2  # get imagefilepath = "geeksforgeeks.jpg"image = cv2.imread(filepath)#print(image.shape)  # get width and heightheight, width = image.shape[:2]  # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Picked
Python-OpenCV
Python-pil
Python
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Class template with multiple parameters - GeeksforGeeks

27 Jun, 2017
Prerequisite: Templates in C++
While creating templates, it is possible to specify more than one type. We can use more than one generic data type in a class template. They are declared as a comma-separated list within the template as below:Syntax:
template<class T1, class T2, ...>
class classname
{
      ...
      ...
};

// CPP program to illustrate// Class template with multiple parameters  #include<iostream>using namespace std;  // Class template with two parameterstemplate<class T1, class T2>class Test{        T1 a;        T2 b;    public:        Test(T1 x, T2 y)        {            a = x;            b = y;        }        void show()        {            cout << a << " and " << b << endl;        }};  // Main Functionint main(){    // instantiation with float and int type    Test <float, int> test1 (1.23, 123);          // instantiation with float and char type    Test <int, char> test2 (100, 'W');             test1.show();    test2.show();          return 0;}
Output:
1.23 and 123
100 and  W

Explanation of the code:
In the above program, the Test constructor has two arguments of generic type.
The type of arguments is mentioned inside angle brackets < > while creating objects.
When argument is more than one, they are separated by commas.
Following statementTest  test1 (1.23, 123);tells the compiler that the first argument is of type float and another one is int type.
Test  test1 (1.23, 123);
tells the compiler that the first argument is of type float and another one is int type.
During creation of objects, constructor is called and values are received by template arguments.
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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.
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Getting attributes of Objects in R Language - attributes() and attr() Function - GeeksforGeeks

23 Nov, 2021
attribute() function in R Programming Language is used to get all the attributes of data. This function is also used to set new attributes to data.
Syntax: attributes(x)
Parameters: 
x: object whose attributes to be accessed.
R
# R program to illustrate# attributes functioninfo = data.frame(iris) # Load info set that you want to work ondata(info) # Print first 6 rows of info set data                                           head(info)                                                # Apply attributes functionattributes(info)                                      
Output: 
Here in the above code, we have applied the attributes() function so we have shown all the data which is present in the info data frame. So by applying info all the attributes in the datasets will be shown.
R
# Set different column names# retain dataframe classattributes_list <- list(names = c('Sepal.Length' ,'Sepal.Width' ,                                  'Petal.Length', 'Petal.Width',                                  'Species'),                        class = "data.frame",                        row.names= c("NA","NA","NA","NA"))  # New attributes from list added to info databaseattributes(info) <- attributes_list attributes(info)
Output: 
$names
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
$class
'data.frame'
$row.names
'NA' 'NA' 'NA' 'NA'
Here in the above code, we have added the new attributes to the list info from Example 1, and then printed all the attributes including the new one.
attr() will return specific data, but this function needs precise information about the data.
Syntax: attr(x = data, which = “attribute_name”)
Parameters: 
x: object whose attributes to be accessed. 
which: string specifying the attribute to be accessed.
R
# R program to illustrate# attr() function # Load info set that you want to work ondata(info) # Apply attr() functionattr(x = info, which = "names")                     
Output: 
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
Here in the above code, we have specified a particular parameter name, so only the values in names will be returned. attr() will return specific data, but attr() functions need a precise information about the data.
ruhelaa48
surinderdawra388
kumar_satyam
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
5 Best Languages for Competitive Programming
7 Highest Paying Programming Languages For Freelancers in 2022
R - Matrices
R - Charts and Graphs
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
How To Remove facet_wrap Title Box in ggplot2 in R ? - GeeksforGeeks

11 Nov, 2021
Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When you have multiple variables, with faceting it can be plotted in a single plot into smaller plots.
We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box.
Syntax: 
plot + facet_wrap( ~facet-variable)
Where:
facet-variable: determines the variable around which plots have to be divided.
Let us first start with a regular plot, without making any changes so that the difference is apparent.
Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~clarity to divide the plot into facets according to their clarity.
Example: Basic plot
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse)  # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) +  # geom_boxplot() function is used to draw ridgeline plot  geom_boxplot()+  # facet_wrap() function divides the plot in facets # according to category of clarity  facet_wrap(~clarity)
Output:
We can customize various aspects of a ggplot2 using the theme() function. To remove the facet_wrap() title box, we need to use “strip.background” argument inside the theme() layer with argument ‘element_blank()’.
Syntax: 
plot + theme( strip.background = element_blank() )
Example: Removing the facet wrap box.
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse)  # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) +  # geom_boxplot() function is used to draw ridgeline plot  geom_boxplot()+  # facet_wrap() function divides the plot in facets according# to category of clarity  facet_wrap(~clarity)+# strip.background parameter of theme# function is used to remove the facet wrap box# element_blank() makes the box background blanktheme(strip.background = element_blank())
Output:
surinderdawra388
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
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 import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?