code-rag-bench/online-tutorials huggingface dataset:
How to get the number of dimensions of a matrix using NumPy in Python? - GeeksforGeeks

03 Mar, 2021
In this article, we will discuss how to get the number of dimensions of a matrix using NumPy. It can be found using the ndim parameter of the ndarray() method.
Syntax: no_of_dimensions = numpy.ndarray.ndim
Approach:
Create an n-dimensional matrix using numpy package.
Use ndim attribute available with numpy array as numpy_array_name.ndim to get the number of dimensions.
Alternatively, we can use shape attribute to get the size of each dimension and then use len() function for the number of dimensions.
Use numpy.array() function to convert a list to numpy array and use one of the above two ways to get the number of dimensions.
Example 1: 
Python3
import numpy as np    x = np.arange(12).reshape((3, 4))    print(x.ndim)
Output:
2
Example 2:
Python3
import numpy as np    # create numpy arrays# 1-d numpy array_1darr = np.arange(4)        # 2-d numpy array_2darr = np.arange(15).reshape((5, 3))       # 3-d numpy array_3darr = np.arange(18).reshape((3, 2, 3))    # printing the type of value obtained using # attribute 'ndim'print("Type of value obtained: ", type(_1darr.ndim))  # printing the dimensions of each numpy arrayprint("Dimensions in _1darr are: ", _1darr.ndim)print("Dimensions in _2darr are: ", _2darr.ndim)print("Dimensions in _3darr are: ", _3darr.ndim)  # numpy_arr.shape is the number of elements in# each dimension numpy_arr.shape returns a tuple# len() of the returned tuple is also gives number# of dimensionsprint("Dimensions in _3darr are: ", len(_3darr.shape))  # Use numpy.array() function to convert a list to# numpy array__1darr = np.array([5, 4, 1, 3, 2])__2darr = np.array([[5, 4],[1,2], [4,5]])print("Dimensions in __1darr are: ", __1darr.ndim)print("Dimensions in __2darr are: ", __2darr.ndim)
Output:
Type of value obtained:  <class 'int'>
Dimensions in _1darr are:  1
Dimensions in _2darr are:  2
Dimensions in _3darr are:  3
Dimensions in _3darr are:  3
Dimensions in __1darr are:  1
Dimensions in __2darr are:  2
Picked
Python numpy-ndarray
Python-numpy
Technical Scripter 2020
Python
Technical Scripter
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()
FileSystem isOpen() method in Java with Examples - GeeksforGeeks

03 Dec, 2019
The isOpen() method of a FileSystem class is used to return true if file system is open. This method is very helpful to know filesystem is open or not. File systems created by the default provider are always open.
Syntax:
public abstract boolean isOpen()

Parameters: This method accepts nothing.
Return value: This method returns true if, and only if, this file system is open.
Below programs illustrate the isOpen() method:Program 1:
// Java program to demonstrate// FileSystem.isOpen() method  import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {      public static void main(String[] args)    {          // create the object of Path        Path path            = Paths.get(                "C:\\Movies\\document.txt");          // get FileSystem object        FileSystem fs = path.getFileSystem();          // apply isOpen() methods        boolean answer = fs.isOpen();          // print        System.out.println("isOpen: " + answer);    }}
Output:
Program 2:
// Java program to demonstrate// FileSystem.isOpen() method  import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {      public static void main(String[] args)    {          // create the object of Path        Path path            = Paths.get(                "E:// Tutorials// file.txt");          // get FileSystem object        FileSystem fs = path.getFileSystem();          // apply isOpen() methods        boolean answer = fs.isOpen();          // print        System.out.println(fs + " is Open: " + answer);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/FileSystem.html#isOpen()
Java-FileSystem
Java-Functions
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Data Structures | Binary Trees | Question 15 - GeeksforGeeks

28 Jun, 2021
In a complete k-ary tree, every internal node has exactly k children or no child. The number of leaves in such a tree with n internal nodes is:(A) nk(B) (n – 1) k+ 1(C) n( k – 1) + 1(D) n(k – 1)Answer: (C)Explanation: For an k-ary tree where each node has k children or no children, following relation holdsL = (k-1)*n + 1
Where L is the number of leaf nodes and n is the number of internal nodes.since its a complete k tree, so every internal node will have K childLet us see following for example
               o
        /      |      \
      o        o        o
    / | \    / | \    / | \
   o  o  o  o  o  o  o  o  o
                      

k = 3
Number of internal nodes n = 4
Number of leaf nodes = (k-1)*n  + 1
                     = (3-1)*4 + 1
                     = 9 
Quiz of this Question
mehreena741
Binary Trees Quiz
Data Structures
Data Structures-Binary Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
Data Structures | Linked List | Question 6
Data Structures | Graph | Question 9
FIFO vs LIFO approach in Programming
Introduction to Data Structures
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
Advantages of vector over array in C++
Program to create Custom Vector Class in C++
fill_n() function in C++ STL with examples - GeeksforGeeks

11 Oct, 2019
The fill_n() function in C++ STL is used to fill some default values in a container. The fill_n() function is used to fill values upto first n positions from a starting position. It accepts an iterator begin and the number of positions n as arguments and fills the first n position starting from the position pointed by begin with the given value.
Syntax:
void fill_n(iterator begin, int n, type value);

Parameters:
begin: The function will start filling values from the position pointed by the iterator begin.
n: This parameter denotes the number of positions to be filled starting from the position pointed by first parameter begin.
value: This parameter denotes the value to be filled by the function in the container.
Return Value: This function does not returns any value.
Below program illustrate the fill_n() function in C++ STL:
// C++ program to demonstrate working of fil_n()#include <bits/stdc++.h>using namespace std;  int main(){    vector<int> vect(8);      // calling fill to initialize first four values    // to 7    fill_n(vect.begin(), 4, 7);      for (int i = 0; i < vect.size(); i++)        cout << ' ' << vect[i];    cout << '\n';      // calling fill to initialize 3 elements from    // "begin()+3" with value 4    fill_n(vect.begin() + 3, 3, 4);      for (int i = 0; i < vect.size(); i++)        cout << ' ' << vect[i];    cout << '\n';      return 0;}
7 7 7 7 0 0 0 0
 7 7 7 4 4 4 0 0

Reference: http://www.cplusplus.com/reference/algorithm/fill_n/
CPP-Functions
C++
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++
std::string class in C++
Pair in C++ Standard Template Library (STL)
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++
Python | Ways to convert Boolean values to integer - GeeksforGeeks

10 Sep, 2021
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task.Method #1: Using int() method  
Python3
# Python code to demonstrate# to convert boolean value to integer # Initialising Valuesbool_val = True  # Printing initial Valuesprint("Initial value", bool_val)  # Converting boolean to integerbool_val = int(bool_val == True) # Printing resultprint("Resultant value", bool_val)        
Initial value True
Resultant value 1
 
  Method #2: Using Naive Approach  
Python3
# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = True  # Printing initial Valuesprint("Initial value", bool_val)  # Converting boolean to integerif bool_val:    bool_val = 1else:    bool_val = 0# Printing resultprint("Resultant value", bool_val)        
Initial value True
Resultant value 1
 
  Method #3: Using numpy In case where boolean list is present  
Python3
# Python code to demonstrate# to convert boolean# value to integer import numpy# Initialising Valuesbool_val = numpy.array([True, False])  # Printing initial Valuesprint("Initial values", bool_val)  # Converting boolean to integerbool_val = numpy.multiply(bool_val, 1)# Printing resultprint("Resultant values", str(bool_val))
Initial values [ True False]
Resultant values [1 0]
 
  Method #4: Using map() in case where boolean list is present  
Python3
# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = [True, False]  # Printing initial Valuesprint("Initial value", bool_val)  # Converting boolean to integerbool_val = list(map(int, bool_val)) # Printing resultprint("Resultant value", str(bool_val))
Initial value [True, False]
Resultant value [1, 0]
 
sagartomar9927
anikakapoor
Python
Python Programs
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
Python program to convert a list to string
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?
Reverse a string in Julia - reverse() Method - GeeksforGeeks

26 Mar, 2020
The reverse() is an inbuilt function in julia which is used to return the reverse of the specified string.
Syntax:reverse(s::AbstractString)
Parameters:
a::AbstractString: Specified string
Returns: It returns the reverse of the specified string.
Example 1:
# Julia program to illustrate # the use of String reverse() method  # Getting the reverse of the specified stringprintln(reverse("GFG"))println(reverse("gfg"))println(reverse("Geeks"))println(reverse("GeeksforGeeks"))
Output:
GFG
gfg
skeeG
skeeGrofskeeG

Example 2:
# Julia program to illustrate # the use of String reverse() method  # Getting the reverse of the specified stringprintln(reverse("123"))println(reverse("5"))println(reverse("@#"))println(reverse("^&*"))
Output:
321
5
#@
*&^

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Creating array with repeated elements in Julia - repeat() Method
Manipulating matrices in Julia
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
\hfil - Tex Command

\hfil - Used to set horizontal alignment in matrices and arrays.
{ \hfil }
\hfil command is used to set horizontal alignment in matrices and arrays.

\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}

xxxxxxxxxxxxxxxxxxababab



\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}

xxxxxxxxxxxxxxxxxxababab


\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to redirect website after certain amount of time without JavaScript?

To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after.
Through this, you can automatically redirect your visitors to a new homepage. Set the content attribute to 0, if you want it to load immediately.
The following is an example of redirecting current page to another page after 2 seconds.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Redirection</title>
      <meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />
   </head>
   <body>
      <p>This page will redirect in 2 seconds.</p>
   </body>
</html>
numpy.linalg.solve()

The numpy.linalg.solve() function gives the solution of linear equations in the matrix form.
Considering the following linear equations −
x + y + z = 6
2y + 5z = -4
2x + 5y - z = 27
They can be represented in the matrix form as −
If these three matrices are called A, X and B, the equation becomes −
A*X = B  

Or

X = A-1B 


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Python - Create a Time Series Plot using Line Plot with Seaborn

To create a Time Series Plot, use the lineplot(). At first, import the required libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame with one of the columns as date i.e. “Date_of_Purchase” −
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]
})
Pot Time Series using lineplot() −
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)

Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# creating DataFrame
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]
})

# time series plot
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)
plt.show()
This will produce the following output −
Dart - main() Function - GeeksforGeeks

17 Feb, 2021
The main() function is a predefined method in Dart. It is the most important and mandatory part of any Dart Program. Any Dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user-defined statements, and user-defined functions. 
Syntax of main() function:
void main()
{
    //main() function body 
}
The main function can be further structured to variable declaration, function declaration, and executable statements. The main function returns void. Also, optional parameters List<String> may be used as arguments to the function. These arguments may be used in case we need to control our program from outside. 
Example 1:
The following example is a basic example of how the main function is the entry point of a Dart program.
Dart
main(){    print("Main is the entry point!");}
Output:
Example 2:
The following example shows how we can pass arguments inside the main() function.
Dart
main(List<String> arguments){     //printing the arguments along with length     print(arguments.length);     print(arguments);}
We run the app using the following code(if main.dart is the name of the saved file):
 dart main.dart Argument1 Argument2
Output:
Picked
Technical Scripter 2020
Dart
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Flutter - BorderRadius Widget
Format Dates in Flutter
Flutter - Positioned Widget
Flutter - Dialogs
Bootstrap .tooltip("toggle") method

Use the tooltip(“toggle”) method in Bootstrap to togle the tooltip.
The tooltip generates on clicking the button shown below −
<button type="button" class="btn btn-info">
  Toggle Tooltip
</button>
Toggle the tooltip on button click like the following code snippet −
$(".btn-info").click(function(){
  $("[data-toggle='tooltip']").tooltip('toggle');
});
You can try to run the following code to implement the tooltip(“toggle”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h3>Demo</h3>
    <a href="#" data-toggle="tooltip" title="Tooltip is visible!">Tooltip will be visible here</a>
    <div>
     <button type="button" class="btn btn-primary">Show Tooltip</button>
     <button type="button" class="btn btn-default">Hide Tooltip</button>
     <button type="button" class="btn btn-info">Toggle Tooltip</button>
    </div>  
  </div>

<script>
  $(document).ready(function(){
    $(".btn-primary").click(function(){
      $("[data-toggle='tooltip']").tooltip('show');
    });
  $(".btn-default").click(function(){
    $("[data-toggle='tooltip']").tooltip('hide');
  });
  $(".btn-info").click(function(){
    $("[data-toggle='tooltip']").tooltip('toggle');
  });
});
</script>

</body>
</html>
Java program to calculate the power of a number

Read the base and exponent values from the user. Multiply the base number by itself and multiply the resultant with base (again) repeat this n times where n is the exponent value.
2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)
import java.util.Scanner;
public class PowerOfNumber {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the base number ::");
      int base = sc.nextInt();
      int temp = base;
      System.out.println("Enter the exponent number ::");
      int exp = sc.nextInt();

      for (int i=1; i<exp; i++){
         temp = temp*temp;
      }
      System.out.println("Result of "+base+" power "+exp+" is "+temp);
   }
}
Enter the base number ::
12
Enter the exponent number ::
2
Result of 12 power 2 is 144
Can we assign a reference to a variable in Python?

Concept of variable in Python is different from C/C++. In C/C++, variable is a named location in memory. Even if value of one is assigned to another, it creates a copy in another location.
int x=5;
int y=x;
For example in C++, the & operator returns address of the declared variable.
cout<x<<&x<<y<<&y;
This will print different address of x and y even though both contain same value. You can create an alias to it by storing the address in a reference variable
int x=5;
int &y=x;
y=10;
cout<<x<<y;
This shows both variables having 10. Here, y is a reference to x. Hence they can be interchangeably used.
However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function.
>>> x=5
>>> y=x
>>> id(x), id(y)
(1486402752, 1486402752)
It therefore is clear that in Python, we can not create reference to a variable.
CoffeeScript Tutorial

CoffeeScript is a light weight language which transcompiles into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.
This tutorial has been prepared for beginners to help them understand the basic functionality of CoffeeScript to build dynamic webpages and web applications.
For this tutorial, it is assumed that the readers have a prior knowledge of HTML coding and JavaScript. It would help if the reader has some prior exposure to object-oriented programming concepts and a general idea on creating online applications.
For most of the examples given in this tutorial, you will find Try it option, so just make use of this option to transcompile your CoffeeScript programs to JavaScript programs on the spot and enjoy your learning.
Try the following example using the Try it option available at the top right corner of the below sample code box −
console.log "Hello Welcome to Tutorials point"


 Print
 Add Notes
 Bookmark this page
isdigit() function in C/C++ with Examples

19 Jan, 2021
The isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it’s a digit else it returns 0. For example, it returns a non-zero value for ‘0’ to ‘9’ and zero for others.
The isdigit() is declared inside ctype.h header file.
It is used to check whether the entered character is a numeric character[0 – 9] or not.
It takes a single argument in the form of an integer and returns the value of type int.
Even though isdigit() takes an integer as an argument, the character is passed to the function. Internally, the character is converted to its ASCII value for the check.
Header File:
#include <ctype.h>
Syntax:
std::isdigit(int arg)
Parameter: The template std::isdigit() accepts a single parameter of integer type.
Return type: This function returns an integer value on the basis of the argument passed to it, if the argument is a numeric character then it returns a non-zero value(true value), otherwise it returns zero(false value).
Below is the program to illustrate the same:
C
// C program to demonstrate isdigit()#include <ctype.h>#include <stdio.h>  // Driver Codeint main(){    // Taking input    char ch = '6';      // Check if the given input    // is numeric or not    if (isdigit(ch))        printf("\nEntered character is"               " numeric character");    else        printf("\nEntered character is not"               " a numeric character");    return 0;}
// C++ program to demonstrate isdigit()#include <ctype.h>#include <iostream>using namespace std;
// Driver Codeint main(){// Taking inputchar ch = ‘6’;
// Check if the given input// is numeric or notif (isdigit(ch))cout << "\nEntered character is"<< " numeric character";elsecout << "\nEntered character is not"" a numeric character";return 0;}
Entered character is numeric character

C Basics
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Groovy - padRight()

Pad the String with the spaces appended to the right. This method has 2 different variants.
String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right.
String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right.
Syntax
String padRight(Number numberOfCharacters)

Parameters
numberOfCharacters − The number of characters to pad the string with.
Return Value − The new value of the string with the padded characters.
String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right.
String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right.
Syntax
String padRight(Number numberOfCharacters, String padding)

Parameters
numberOfCharacters − The number of characters to pad the string with.
numberOfCharacters − The number of characters to pad the string with.
Padding − The character to apply for the padding.
Padding − The character to apply for the padding.
Return Value − The new value of the string with the padded characters
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      String a = "Hello World"; 
		
      println(a.padRight(14)); 
      println(a.padRight(16)); 
      println(a.padRight(16,'*')); 
      println(a.padRight(14,'*')); 
   } 
}
When we run the above program, we will get the following result −
PostgreSQL – Export PostgreSQL Table to CSV file

28 Feb, 2021
In this article will discuss we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine.
Use the below syntax to copy a PostgreSQL table from the server itself:
Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER;
Note: If you have permission to perform a read/write operation on the server-side then use this command.
Example:
First, let’s create a table with columns id, first_name, last_name, and email to the database:
CREATE TABLE students(
   id SERIAL PRIMARY KEY,
   first_name VARCHAR,
   last_name VARCHAR,
   email VARCHAR UNIQUE
);
Let’s insert some data into our students table:
INSERT INTO students(first_name, last_name, email)
VALUES('Virender', 'Sehwag', 'virender.sehwag@gfg.com'),
    ('Hardik', 'Pandiya', 'hardik.Pandiya@gfg.com'),
    ('Shreyas', 'Iyer', 'shreyas.iyer@gfg.com'),
    ('Rishabh', 'Pant', 'rishabh.pant@gfg.com');
Now check the data in the table:
SELECT * FROM students;
Output:
Now export the above table as a CSV file.
COPY students TO '/tmp/student1.csv' CSV HEADER;
Note: Make sure that the path that you specify should have read/write permission.
If everything works fine then it should look like this:
The CSV file would look like below:
We can also specify columns that we want to export or write a query for the data.
COPY (SELECT first_name FROM students) TO '/tmp/student.csv' CSV HEADER;
Output:
The CSV file would look like below:
CSV File
Use the below syntax for client-side export of CSV file:
Syntax: \copy Table_Name to 'Path/filename.csv' CSV HEADER
If you do not have permission to perform a read/write operation on the server-side and want to copy the table to the client-side machine then use this command.
Let’s use the students table here also.
Execute the below command to export the table to a CSV file.
\copy students to '/tmp/students.csv' CSV HEADER
Output:
The CSV file would look like below:
You can give a query to select data here also.
Picked
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT DISTINCT clause
How to convert String to Float in PHP ?

30 Apr, 2021
Strings in PHP can be converted to float very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert a string into a number in PHP, some of them are discussed below:
Methods:
Using floatval() function.
Using Typecasting.
Using number_format() function.
Method 1: Using floatval() function.
Note: The floatval() function can be used to convert the string into float values .
Syntax:
$floatvar = floatval($stringvar)
Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.
Example:
PHP
<?php    // Number in string format  $stringvar = "1000.314";    // converts string into float  $floatvar =  floatval($stringvar);    // prints the value of above variable as a float  echo "Converted float = ".$floatvar;  ?>
Output:
Converted float = 1000.314
Method 2: Using Typecasting.
Note:  Typecasting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We convert String into Float.
Syntax:
$floatvar = (float)$stringvar
Example:
PHP
<?php  // Number in string format$stringvar = "1000.314";  // converts string into float$floatvar =  (float)$stringvar;  // prints the value of above variable as a floatecho "Converted float = ".$floatvar;  ?>
Output:
Converted float = 1000.314
Method 3: Using number_format() function.
Note: The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.
Syntax:
string number_format( $number, $decimals, $decimalpoint, $sep )
Return Value: It returns a formatted number in case of success, otherwise it gives E_WARNING if it fails.
Example:
PHP
<?php  // Number in string format$stringvar = "1000.3145635";  // converts  string into float with 6 decimals$floatvar =  number_format($stringvar, 6);  // prints the value of above variable as a stringecho "Converted float = ".$floatvar;  ?>
Output:
Converted float = 1000.314564
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to validate input field in the HTML Form ?

13 Jan, 2022
In this article, we will see how to validate form input fields using HTML. To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
Syntax:
<input required>
Approach: In the below example, we will create a form with <label> and <input> tags and add required attribute with input tag to validate the input field using HTML.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        How to validate input field in HTML Form?    </title></head>  <body>    <center>        <h1 style="color: green;">            GeeksforGeeks        </h1>          <h3>            How to validate input field in HTML Form?        </h3>          <form action="#">            <label for="fname">First Name:</label>            <input type="text" name="fname" id="fname" required>            <br><br>              <label for="lname">Last Name:</label>            <input type="text" name="lname" id="lname" required>            <br><br>              <label for="email">Email Id:</label>            <input type="email" name="email" id="email" required>            <br><br>              <input type="submit" value="Submit">        </form>    </center></body>  </html>
Output:
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Maximum value of int in C++

09 Dec, 2020
In this article, we will discuss the int data type in C++. It is used to store a 32-bit integer. 
Some properties of the int data type are:
Being a signed data type, it can store positive values as well as negative values.
Takes a size of 32 bits where 1 bit is used to store the sign of the integer.
A maximum integer value that can be stored in an int data type is typically 2, 147, 483, 647, around 231 – 1, but is compiler dependent.
The maximum value that can be stored in int is stored as a constant in <climits> header file whose value can be used as INT_MAX.
A minimum integer value that can be stored in an int data type is typically -2, 147, 483, 648, around -231, but is compiler dependent.
In case of overflow or underflow of data type, the value is wrapped around. For example, if -2, 147, 483, 648 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 2, 147, 483, 647. Similarly, in the case of overflow, the value will round back to -2, 147, 483, 648.
Below is the program to get the highest value that can be stored in int in C++:
C++
// C++ program to obtain the maximum// value that can be store in int#include <climits>#include <iostream>using namespace std;  // Driver Codeint main(){    // From the constant of climits    // header file    int valueFromLimits = INT_MAX;      cout << "Value from climits "         << "constant (maximum): ";    cout << valueFromLimits << "\n";      valueFromLimits = INT_MIN;    cout << "Value from climits "         << "constant(minimum): ";    cout << valueFromLimits << "\n";      // Using the wrap around property    // of data types      // Initialize two variables with    // value -1 as previous and another    // with 0 as present    int previous = -1;    int present = 0;      // Keep on increasing both values    // until the present increases to    // the max limit and wraps around    // to the negative value i.e., present    // becomes less than previous value    while (present > previous) {        previous++;        present++;    }      cout << "\nValue using the wrap "         << "around property:\n";      cout << "Maximum: " << previous << "\n";    cout << "Minimum: " << present << "\n";      return 0;}
Value from climits constant (maximum): 2147483647
Value from climits constant(minimum): -2147483648

Value using the wrap around property:
Maximum: 2147483647
Minimum: -2147483648

cpp-data-types
Data Type
C++
C++ Programs
Data Type
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | PIL Attributes

29 Jul, 2019
Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image.
Image used is:
Instances of the Image class have the following attributes:
PIL.Image.filename: The filename or path of the source file. Only images created with the factory function open have a filename attribute. If the input is a file-like object, the filename attribute is set to an empty string.
Syntax: PIL.Image.filename

Type: py:class: string

from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG")  im2 = im1.filenameprint(im2)
Output:
C:\Users\sadow984\Desktop\r1.PNG
 PIL.Image.format: The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
Syntax: PIL.Image.format

Type: string or None

from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG")  im2 = im1.formatprint(im2)
Output:
PNG
 PIL.Image.mode: Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See Modes for a full list.
Syntax: PIL.Image.mode

Type: string 

from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG")  im2 = im1.modeprint(im2)
Output:
P
 PIL.Image.size: Image size, in pixels. The size is given as a 2-tuple (width, height).
Syntax: PIL.Image.size

Type: (width, height) 

from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG")  im2 = im1.sizeprint(im2)
Output:
(225, 225)
nidhi_biet
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | Pandas dataframe.nunique()

22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.nunique() function return Series with number of distinct observations over requested axis. If we set the value of axis to be 0, then it finds the total number of unique observations over the index axis. If we set the value of axis to be 1, then it find the total number of unique observations over the column axis. It also provides the feature to exclude the NaN values from the count of unique numbers.
Syntax: DataFrame.nunique(axis=0, dropna=True)
Parameters :axis : {0 or ‘index’, 1 or ‘columns’}, default 0dropna : Don’t include NaN in the counts.
Returns : nunique : Series
Example #1: Use nunique() function to find the number of unique values over the column axis.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df = pd.DataFrame({"A":[14, 4, 5, 4, 1],                   "B":[5, 2, 54, 3, 2],                   "C":[20, 20, 7, 3, 8],                    "D":[14, 3, 6, 2, 6]})  # Print the dataframedf
Let’s use the dataframe.nunique() function to find the unique values across the column axis.
# find unique valuesdf.nunique(axis = 1)
Output :As we can see in the output, the function prints the total no. of unique values in each row. Example #2: Use nunique() function to find the number of unique values over the index axis in a dataframe. The dataframe contains NaN values.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df = pd.DataFrame({"A":["Sandy", "alex", "brook", "kelly", np.nan],                   "B":[np.nan, "olivia", "olivia", "", "amanda"],                    "C":[20 + 5j, 20 + 5j, 7, None, 8],                   "D":[14.8, 3, None, 6, 6]})  # apply the nunique() functiondf.nunique(axis = 0, dropna = True)
Output :The function is treating the empty string as a unique value in column 2.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to implement Gift Wrapping Algorithm in Two Dimensions

We shall develop a C++ program to implement Gift Wrapping Algorithm in two dimensions. The Gift Wrapping Algorithm is an algorithm for computing the convex hull of a given set of points.
Begin
   function convexHull() to find convex hull of a set of n points:
   There must be at least three points.
   Initialize the result.
   Find the leftmost point.
   Starting from leftmost point, keep moving counterclockwise
   until reach the start point again.
   Print the result.
End
 Live Demo
#include <iostream>
using namespace std;
#define INF 10000
struct P {
   int x;
   int y;
};
int orient(P a, P b, P c) {
   int v = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);
   if (v == 0)
      return 0; // colinear
      return (v >0) ? 1 : 2; // clock or counterclock wise
}
void convexHull(P points[], int m) {
   if (m < 3)//at least three points required
      return;
   int n[m];
   for (int i = 0; i < m; i++)
      n[i] = -1;
      int l = 0;//initialize result.
   for (int i = 1; i < m; i++)
      if (points[i].x < points[l].x)
         l = i; //find left most point
         int p = l, q;
   do {
      q = (p + 1) % m;
      for (int i = 0; i < m; i++)
         if (orient(points[p], points[i], points[q]) == 2)
            q = i;
            n[p] = q;
            p = q;
   } while (p != l);
   for (int i = 0; i < m; i++) {
      if (n[i] != -1)
         cout << "(" << points[i].x << ", " << points[i].y << ")\n";
   }
}
int main() {
   P points[] = {{0, 4}, {2, 1}, {2, 3}, {4, 1}, {3, 0}, {1, 1}, {7, 6}};
   cout << "The points in the convex hull are: ";
   int n = sizeof(points) / sizeof(points[0]);
   convexHull(points, n);
   return 0;
}
The points in the convex hull are: (0, 4)
(4, 1)
(3, 0)
(1, 1)
(7, 6)
Kubernetes - Namespace

Namespace provides an additional qualification to a resource name. This is helpful when multiple teams are using the same cluster and there is a potential of name collision. It can be as a virtual wall between multiple clusters.
Following are some of the important functionalities of a Namespace in Kubernetes −
Namespaces help pod-to-pod communication using the same namespace.
Namespaces help pod-to-pod communication using the same namespace.
Namespaces are virtual clusters that can sit on top of the same physical cluster.
Namespaces are virtual clusters that can sit on top of the same physical cluster.
They provide logical separation between the teams and their environments.
They provide logical separation between the teams and their environments.
The following command is used to create a namespace.
apiVersion: v1
kind: Namespce
metadata
   name: elk

The following command is used to control the namespace.
$ kubectl create –f namespace.yml ---------> 1
$ kubectl get namespace -----------------> 2
$ kubectl get namespace <Namespace name> ------->3
$ kubectl describe namespace <Namespace name> ---->4
$ kubectl delete namespace <Namespace name>

In the above code,
We are using the command to create a namespace.
This will list all the available namespace.
This will get a particular namespace whose name is specified in the command.
This will describe the complete details about the service.
This will delete a particular namespace present in the cluster.
Following is an example of a sample file for using namespace in service.
apiVersion: v1
kind: Service
metadata:
   name: elasticsearch
   namespace: elk
   labels:
      component: elasticsearch
spec:
   type: LoadBalancer
   selector:
      component: elasticsearch
   ports:
   - name: http
      port: 9200
      protocol: TCP
   - name: transport
      port: 9300
      protocol: TCP

In the above code, we are using the same namespace under service metadata with the name of elk.

    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
What is difference between a pointer and reference parameter in C++?

Pointer variables are used to store the address of variable.
Type *pointer;
Type *pointer;
Pointer=variable name;
When a parameter is declared as reference, it becomes an alternative name for an existing parameter.
Type &newname=existing name;
Type &pointer;
Pointer=variable name;
The main differences between pointers and reference parameters are −
References are used to refer an existing variable in another name whereas pointers are used to store address of variable.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable.
References cannot have a null value assigned but pointer can.
References cannot have a null value assigned but pointer can.
A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
A reference must be initialized on declaration while it is not necessary in case of pointer.
A reference must be initialized on declaration while it is not necessary in case of pointer.
A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack.
A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack.
C++ Inline Functions

C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline  specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
 
using namespace std;

inline int Max(int x, int y) {
   return (x > y)? x : y;
}

// Main function for the program
int main() {
   cout << "Max (20,10): " << Max(20,10) << endl;
   cout << "Max (0,200): " << Max(0,200) << endl;
   cout << "Max (100,1010): " << Max(100,1010) << endl;
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Change the background color of a button with CSS

To change the background color of a button, use the background-color property.
You can try to run the following code to change button’s background color
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .btn {
            background-color: yellow;
            color: black;
            text-align: center;
            font-size: 13px;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <button class = "btn">Result</button>
   </body>
</html>