code-rag-bench/online-tutorials huggingface dataset:
Plot a 3D Contour in MATLAB

21 Apr, 2021
Contour plots are used to show 3D surfaces by plotting z- slides on a 2D surface. A contour plot is also called a line plot. In contour, we have 3 variables x, y, z. The x, y variables are used to give the values for z, ( z=f(x, y)). The x and y variables are usually in a grid called meshgrid.
There are various contour plots in MATLAB like contour, contourf, contour3, contourc, countourslice, clabel, and fcontour. In this article, we will see how to plot 3D contour in MATLAB. To plot 3D contour we will use countour3() to plot different types of 3D modules. 
Syntax:
contour3(X,Y,Z): Specifies the x and y coordinates for the values in Z.
contour3(Z): Creates a 3-D contour plot containing the isolines of matrix Z, where Z contains height values on the x-y plane.
contour3(___,levels): Specify levels as a scalar value n to display the contour lines at n automatically chosen levels (heights).
contour3(___,LineSpec): Specifies the style and color of the contour line.
Step-wise Approach:
Enter the inputs for x and y in meshgrid function.
Matlab
% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5);
Pass the value for z using x and y in an equation.
Matlab
% give any equation for z variablez = x.^2 + y.^2 ;  % disp is used to display the % value for zdisp(z);
Use contour3 to plot 3d contour and to label the axis use label() method.
Matlab
% to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contourlinescontour3(z,25);  % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');
Below is the complete program:
Matlab
% code for 3D plot% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5);  % give any equation for z variablez = x.^2 + y.^2 ;disp(z);  % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used % to display the height for the contour% linescontour3(z,25);  % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');
Output:
Example 1:
Here is another example similar to the previous one.
Matlab
% code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5);  % give any equation for z variablez = x.^2 - y.^2 ;disp(z);  % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to% display the height for the contourlinescontour3(z,25);  % to label x ,y , z axis and titlexlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');
Output:
Example 2:
MATLAB program to generate a 3D Contour:
Matlab
% code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-7 : 0.1 : 7);  % give any equation for z variablez = sin(x)+ cos(y) ;disp(z);  % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contour% linescontour3(z,25);  % to label x ,y and z axisxlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');
Output:
MATLAB-graphs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Turn on or off bulb using JavaScript

19 Feb, 2019
Write a JavaScript code that turns ON and OFF the Light Bulb.Syntax:
img src = URl
     or
img src = image_name.jpg

Here the src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.There are two states of the bulb is used which are specified below-Initial state of bulb (OFF STATE):
After clicking on bulb (ON STATE):
JavaScript code to illustrate this topic:
<html>  <body>    <!-- onclick event is generated        and it calls turnOnOff function -->    <!-- OFFbulb.jpg is the turn off bulb image --><img id="Image" onclick="turnOnOff()" src="https://media.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg">      <p>Click on the bulb to turn it ON and OFF</p>      <script>     // implementation of turnOnOff function -->     function turnOnOff()      // taking image in image variable     var image = document.getElementById('Image');       //Match the image name     //whether it is ONbulb or OFFbulb     //change image to OFFbulb.jpg if     //it match with ONbulb otherwise     //change it to ONbulb.jpg -->     if (image.src.match("ONbulb"))         image.src = "https://media.geeksforgeeks.org/                     wp-content/uploads/OFFbulb.jpg";     else         image.src = "https://media.geeksforgeeks.org/                      wp-content/uploads/ONbulb.jpg";    }    </script></body>  </html>
Output:Before clicking on the bulb-After clicking on the bulb-
javascript-basics
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashtable containsKey() Method in Java

28 Jun, 2018
The java.util.Hashtable.containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table.
Syntax:
Hash_table.containsKey(key_element)
Parameters: The method takes just one parameter key_element which refers to the key whose presence is supposed to be checked inside a Hashtable.
Return Value: The method returns boolean true if the key is present in the Hashtable otherwise it returns false.
Below programs are used to illustrate the working of java.util.Hashtable.containsKey() Method:Program 1:
// Java code to illustrate the containsKey() methodimport java.util.*;  public class Hash_Table_Demo {    public static void main(String[] args)    {          // Creating an empty Hashtable        Hashtable<Integer, String> hash_table =         new Hashtable<Integer, String>();          // Putting values into the table        hash_table.put(10, "Geeks");        hash_table.put(15, "4");        hash_table.put(20, "Geeks");        hash_table.put(25, "Welcomes");        hash_table.put(30, "You");          // Displaying the Hashtable        System.out.println("Initial Table is: " + hash_table);          // Checking for the key_element '20'        System.out.println("Is the key '20' present? " +         hash_table.containsKey(20));          // Checking for the key_element '5'        System.out.println("Is the key '5' present? " +         hash_table.containsKey(5));    }}
Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Is the key '20' present? true
Is the key '5' present? false

Program 2:
// Java code to illustrate the containsKey() methodimport java.util.*;  public class Hash_Table_Demo {    public static void main(String[] args)    {          // Creating an empty Hashtable        Hashtable<String, Integer> hash_table=         new Hashtable<String, Integer>();          // Putting values into the table        hash_table.put("Geeks", 10);        hash_table.put("4", 15);        hash_table.put("Geeks", 20);        hash_table.put("Welcomes", 25);        hash_table.put("You", 30);          // Displaying the Hashtable        System.out.println("Initial Table is: " + hash_table);          // Checking for the key_element 'Welcomes'        System.out.println("Is the key 'Welcomes' present? " +         hash_table.containsKey("Welcomes"));          // Checking for the key_element 'World'        System.out.println("Is the key 'World' present? " +         hash_table.containsKey("World"));    }}
Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
Is the key 'Welcomes' present? true
Is the key 'World' present? false

Note: The same operation can be performed with any type of variation and combination of different data types.
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Removing Array Element and Re-Indexing in PHP

25 Jan, 2022
In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically.
Function Used:
unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] )array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array )
unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] )
void unset ( mixed $var [, mixed $... ] )
array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array )
array array_values ( array $array )
Example 1:
<?php $arr1 = array(      'geeks', // [0]    'for', // [1]    'geeks' // [2]  );  // remove item at index 1 which is 'for'unset($arr1[1]);   // Print modified arrayvar_dump($arr1);  // Re-index the array elements$arr2 = array_values($arr1);  // Print re-indexed arrayvar_dump($arr2);?>
array(2) {
  [0]=>
  string(5) "geeks"
  [2]=>
  string(5) "geeks"
}
array(2) {
  [0]=>
  string(5) "geeks"
  [2]=>
  string(5) "geeks"
}

We can also use array_splice() function which removes a portion of the array and replaces it with something else.Example 2:
<?php $arr1 = array(    'geeks', // [0]    'for', // [1]    'geeks' // [2]);  // remove item at index 1 which is 'for'array_splice($arr1, 1, 1);   // Print modified arrayvar_dump($arr1);?>
array(2) {
  [0]=>
  string(5) "geeks"
  [1]=>
  string(5) "geeks"
}

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
manakupadhyay
PHP-array
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Update Date Field in SQL Server

10 Oct, 2021
The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database.
So, we will create a database first:
Step 1: Create Database
Query:
CREATE DATABASE GFG
Step 2: Use Database
Query:
USE GFG
Step 3: Create a table
Create a table (TimeTable) in the database to store the data.
Query:
CREATE TABLE TimeTable(
 SubjectDate datetime NOT NULL ,
 SubjectName char (10)
)
Step 4: Insert the data into the database 
Query:
/* Data Inserted for a full week dates*/

INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('01/10/2021','DSA')
INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('02/10/2021','CD')
INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('03/10/2021','DBMS')
INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('04/10/2021','OS')
Step 5: Now change the data of DateTime
In the below query, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated. If we have not used the WHERE clause then the columns in all the rows will be updated. So the WHERE clause is used to choose the particular rows.
Query:
UPDATE TimeTable   
SET SubjectDate = '05/10/2021'   
WHERE SubjectName = 'DSA'   
Output:
As we can see subject date has been changed.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Implement Max Heap

A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in Binary Tree. Min Binary Heap is similar to MinHeap.
For max_heap:
Begin
   Declare function max_heap ()
      Declare j, t of the integer datatype.
      Initialize t = a[m].
      j = 2 * m;
      while (j <= n) do
         if (j < n && a[j+1] > a[j]) then
            j = j + 1
         if (t > a[j]) then
            break
         else if (t <= a[j]) then
            a[j / 2] = a[j]
            j = 2 * j
      a[j/2] = t
      return
End.
For build_maxheap:
Begin
   Declare function build_maxheap(int *a,int n).
      Declare k of the integer datatype.
      for(k = n/2; k >= 1; k--)
         Call function max_heap(a,k,n)
End.
#include <iostream>
using namespace std;
void max_heap(int *a, int m, int n) {
   int j, t;
   t = a[m];
   j = 2 * m;
   while (j <= n) {
      if (j < n && a[j+1] > a[j])
         j = j + 1;
      if (t > a[j])
         break;
      else if (t <= a[j]) {
         a[j / 2] = a[j];
         j = 2 * j;
      }
   }
   a[j/2] = t;
   return;
}
void build_maxheap(int *a,int n) {
   int k;
   for(k = n/2; k >= 1; k--) {
      max_heap(a,k,n);
   }
}
int main() {
   int n, i;
   cout<<"enter no of elements of array\n";
   cin>>n;
   int a[30];
   for (i = 1; i <= n; i++) {
      cout<<"enter elements"<<" "<<(i)<<endl;
      cin>>a[i];
   }
   build_maxheap(a,n);
   cout<<"Max Heap\n";
   for (i = 1; i <= n; i++) {
      cout<<a[i]<<endl;
   }
}
enter no of elements of array
5
enter elements 1
7
enter elements 2
6
enter elements 3
2
enter elements 4
1
enter elements 5
4
Max Heap
7
6
2
1
4
GATE | GATE-CS-2014-(Set-2) | Question 20 - GeeksforGeeks

28 Jun, 2021
Consider the function func shown below:
int func(int num){    int count = 0;    while (num)    {        count++;        num >>= 1;    }    return (count);}
The value returned by func(435)is __________.
(A) 8(B) 9(C) 10(D) 11Answer: (B)Explanation: The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit.
Another explanation:>> in right shift. In other words, it means divide by 2.If keep on dividing by 2, we get: 435, 217, 108, 54, 27, 13, 6, 3, 1.Therefore, the count is 9.Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How many types of inheritance are there in Python?

Inheritance is concept where one class accesses the methods and properties of another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
There are two types of inheritance in python −
Multiple Inheritance
Multilevel Inheritance
In multiple inheritance one child class can inherit multiple parent classes.
class Father:
   fathername = ""
   def father(self):
      print(self.fathername)

class Mother:
   mothername = ""
   def mother(self):
      print(self.mothername)

class Daughter(Father, Mother):
   def parent(self):
      print("Father :", self.fathername)
      print("Mother :", self.mothername)

s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()
Father : Srinivas
Mother : Anjali
In this type of inheritance, a class can inherit from a child class/derived class.
#Daughter class inherited from Father and Mother classes which derived from Family class.
class Family:
   def family(self):
      print("This is My family:")

class Father(Family):
   fathername = ""
   def father(self):
      print(self.fathername)

class Mother(Family):
   mothername = ""
   def mother(self):
      print(self.mothername)
   
class Daughter(Father, Mother):
   def parent(self):
      print("Father :", self.fathername)
      print("Mother :", self.mothername)

s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family()
s1.parent()
This is My family:
Father : Srinivas
Mother : Anjali
Connecting to a MySQL database with Java

Use below URL to connect MySQL database. The syntax is as follows −
String MySQLURL="jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false";
String databseUserName="yourUserName";
String databasePassword="yourPassword";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class ConnectToDatabase {
   public static void main(String[] args) {
      String MySQLURL = "jdbc:mysql://localhost:3306/web?useSSL=false";
      String databseUserName = "root";
      String databasePassword = "123456";
      Connection con = null;
      try {
         con = DriverManager.getConnection(MySQLURL, databseUserName, databasePassword);
         if (con != null) {
            System.out.println("Database connection is successful !!!!");
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
Database connection is successful !!!!
Here is the snapshot of the output −
Remove duplicates and map an array in JavaScript

Suppose, we have an array of objects like this −
const arr = [
   {id:123, value:"value1", name:"Name1"},
   {id:124, value:"value2", name:"Name1"},
   {id:125, value:"value3", name:"Name2"},
   {id:126, value:"value4", name:"Name2"}
];
Note that some of the "name" property in objects within the array are duplicate.
We are required to write a JavaScript function that takes in one such array of objects. The function should then construct a new array of strings that contains only unique "name" property value from the array.
Therefore, the output for the above input should look like this −
const output = ["Name1", "Name2"];
The code for this will be −
const arr = [
   {id:123, value:"value1", name:"Name1"},
   {id:124, value:"value2", name:"Name1"},
   {id:125, value:"value3", name:"Name2"},
   {id:126, value:"value4", name:"Name2"}
];
const pickNames = (arr = []) =>{
   const res = [];
   for (let i = arr.length; i−−;){
      if (res.indexOf(arr[i].name) < 0) {
         res.push(arr[i].name);
      };
   }
   return res;
};
console.log(pickNames(arr));
And the output in the console will be −
[ 'Name2', 'Name1' ]
Difference between Call by Value and Call by Reference - GeeksforGeeks

14 Aug, 2020
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.
Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
// C program to illustrate
// call by value

#include 

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass by Values
    swapx(a, b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Swap functions that swaps
// two values
void swapx(int x, int y)
{
    int t;

    t = x;
    x = y;
    y = t;

    printf("x=%d y=%d\n", x, y);
}


Output:
x=20 y=10
a=10 b=20

// C program to illustrate
// Call by Reference

#include 

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass reference
    swapx(&a, &b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Function to swap two variables
// by references
void swapx(int* x, int* y)
{
    int t;

    t = *x;
    *x = *y;
    *y = t;

    printf("x=%d y=%d\n", *x, *y);
}

Output:
x=20 y=10
a=20 b=10

Note : In C, we use pointers to achieve call by reference. In C++, we can either use pointers or references to for pass by reference. In Java, primitive types are passed as values and non-primitive types are always references.
C-Functions
CPP-Functions
Picked
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
PHP | fputcsv( ) Function - GeeksforGeeks

13 Jun, 2018
The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.
Syntax:
int fputcsv ( $file, $fields, $separator, $enclosure )

Parameters: The fputcsv() function in PHP accepts four parameters as explained below.
$file: It is a mandatory parameter which specifies the file.
$fields: It is a mandatory parameter which specifies which array to get data from.
$separator: It is an optional parameter which specifies the field separator. By default the fputcsv() function uses comma.
$enclosure: It is an optional parameter which specifies the field enclosure character. By default the fputcsv() function uses.
Return Value: This function returns the length of the written string on success or FALSE on failure.
Exceptions:
If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_char.
Enabling the auto_detect_line_endings run-time configuration option may help resolve the problem of PHP properly recognizing the line endings when reading files either on or created by a Macintosh computer.
Below programs illustrate the fputcsv() function:Program 1:
<?php// Sample data for formatting in CSV format$employees = array("Raj, Singh, Developer, Mumbai",                    "Sameer, Pandey, Tester, Bangalore",                    "Raghav, Chauhan, Manager, Delhi");  // opening the file "data.csv" for writing$myfile = fopen("gfg.csv", "w");  // formatting each row of data in CSV format // and outputting itforeach ($employees as $line){    fputcsv($myfile, explode(',',$line));}  // closing the filefclose($myfile); ?>
Output:
Raj, Singh, Developer, Mumbai
Sameer, Pandey, Tester, Bangalore
Raghav, Chauhan, Manager, Delhi

Program 2:
<?php// Sample data for formatting in CSV format$random_data = array(array("abc, efg, jhi, klm"),array("123, 456, 789"),array("11aa, 22bb, 33cc, 44dd"));  // opening the file "data.csv" for writing$myfile = fopen("gfg.csv", "w");  // formatting each row of data in CSV format // and outputting itforeach ($random_data as $line){    fputcsv($myfile, $line);}  // closing the filefclose($myfile);?>
Output:
abc, efg, jhi, klm
123, 456, 789
11aa, 22bb, 33cc, 44dd

Reference: http://php.net/manual/en/function.fputcsv.php
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 ?
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Apache Flink - Machine Learning

Apache Flink's Machine Learning library is called FlinkML. Since usage of machine learning has been increasing exponentially over the last 5 years, Flink community decided to add this machine learning APO also in its ecosystem. The list of contributors and algorithms are increasing in FlinkML. This API is not a part of binary distribution yet.
Here is an example of linear regression using FlinkML −
// LabeledVector is a feature vector with a label (class or real value)
val trainingData: DataSet[LabeledVector] = ...
val testingData: DataSet[Vector] = ...

// Alternatively, a Splitter is used to break up a DataSet into training and testing data.
val dataSet: DataSet[LabeledVector] = ...
val trainTestData: DataSet[TrainTestDataSet] = Splitter.trainTestSplit(dataSet)
val trainingData: DataSet[LabeledVector] = trainTestData.training
val testingData: DataSet[Vector] = trainTestData.testing.map(lv => lv.vector)
val mlr = MultipleLinearRegression()

.setStepsize(1.0)
.setIterations(100)
.setConvergenceThreshold(0.001)
mlr.fit(trainingData)

// The fitted model can now be used to make predictions
val predictions: DataSet[LabeledVector] = mlr.predict(testingData)
Inside flink-1.7.1/examples/batch/ path, you will find KMeans.jar file. Let us run this sample FlinkML example.
This example program is run using the default point and the centroid data set.
./bin/flink run examples/batch/KMeans.jar --output Print


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Check if dataframe contains infinity in Python - Pandas - GeeksforGeeks

26 Dec, 2020
Prerequisites: Pandas
There are various cases where a data frame can contain infinity as value. This article discusses how we can keep track of infinities in our data frame. 
Import module
Create a data frame, for this article, it is done using a dictionary. For including infinity in the data, import NumPy module, and use np.inf for positive infinity and -np.inf for negative infinity.
Use appropriate methods from the ones mentioned below as per your requirement.
Method 1: Use DataFrame.isinf() function to check whether the dataframe contains infinity or not. It returns boolean value. If it contains any infinity, it will return True. Else, it will return False. 
Syntax:
isinf(array [, out])
Using this method itself, we can derive a lot more information regarding the presence of infinity in our dataframe:
Checking for infinity as values
Counting the number of infinity values
Retrieve column name with infinity as value(s)
Retrieve row index/indices with infinity as value(s)
Example:
Python3
# Import required libraries  import pandas as pdimport numpy as np  # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14],         'Age': [23, 22, 24, 22, 25],        'Weight': [66, 72, np.inf, 68, -np.inf]}  df = pd.DataFrame(data)  display(df)  # checking for infinityprint()print("checking for infinity")  ds = df.isin([np.inf, -np.inf])print(ds)  # printing the count of infinity valuesprint()print("printing the count of infinity values")  count = np.isinf(df).values.sum()print("It contains " + str(count) + " infinite values")  # counting infinity in a particular column namec = np.isinf(df['Weight']).values.sum()print("It contains " + str(c) + " infinite values")  # printing column name where infinity is presentprint()print("printing column name where infinity is present")col_name = df.columns.to_series()[np.isinf(df).any()]print(col_name)  # printing row index with infinityprint()print("printing row index with infinity ")  r = df.index[np.isinf(df).any(1)]print(r)
Output:
Method 2: Use np.isfinite(dataframe_name) to check the presence of infinite value(s). It returns boolean value. It will return False for infinite values and it will return True for finite values.
Syntax:
isfinite(array [, out])
Example: 
Python3
# Import required libraries  import pandas as pdimport numpy as np  # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14], 'Age': [    23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]}  df = pd.DataFrame(data)  d = np.isfinite(df)  display(d)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a grouped bar plot in Matplotlib - GeeksforGeeks

17 Dec, 2020
In this article, we will learn how to Create a grouped bar plot in Matplotlib. Let’s discuss some concepts :
Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002.
A bar plot or bar graph may be a graph that represents the category of knowledge with rectangular bars with lengths and heights that’s proportional to the values which they represent. The bar plots are often plotted horizontally or vertically.
A bar chart is a great way to compare categorical data across one or two dimensions. More often than not, it’s more interesting to compare values across two dimensions and for that, a grouped bar chart is needed.
Approach:
Import Library (Matplotlib)Import / create data.Plot the bars in the grouped manner.
Import Library (Matplotlib)
Import / create data.
Plot the bars in the grouped manner.
Example 1: (Simple grouped bar plot)
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]width = 0.40  # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width)plt.bar(x+0.2, y2, width)
Output :
Example 2: (Grouped bar chart with more than 2 data)
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]y3 = [14, 23, 45, 25, 89]width = 0.2  # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width, color='cyan')plt.bar(x, y2, width, color='orange')plt.bar(x+0.2, y3, width, color='green')plt.xticks(x, ['Team A', 'Team B', 'Team C', 'Team D', 'Team E'])plt.xlabel("Teams")plt.ylabel("Scores")plt.legend(["Round 1", "Round 2", "Round 3"])plt.show()
Output :
Example 3: (Grouped Bar chart using dataframe plot)
Python3
# importing packageimport matplotlib.pyplot as pltimport pandas as pd  # create datadf = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6],                   ['D', 10, 29, 13, 19]],                  columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])# view dataprint(df)  # plot grouped bar chartdf.plot(x='Team',        kind='bar',        stacked=False,        title='Grouped Bar Graph with dataframe')
Output :
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
JQuery | parseHTML() method - GeeksforGeeks

27 Apr, 2020
This parseHTML() Method in jQuery is used to parses a string into an array of DOM nodes.
Syntax:
jQuery.parseHTML(data [, context ] [, keepScripts ])

Parameters: The parseXML() method accepts three parameter that is mentioned above and described below:
data: This parameter is the HTML string to be parsed.
context : This parameter is the document element to serve as the context in which the HTML fragment will be created.
keepScripts : This parameter is the boolean indicating whether to include scripts passed in the HTML string.
Example 1: In this example, the parseHTML() Method a string is parsed into an array of DOM nodes.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseHTML() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  </head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | parseHTML() method</h3>    <pre id="geek">    </pre>           <script>        var $geek = $( "#geek" ),          str = "A <b>computer science portal</b> for <b>geeks</b>",          html = jQuery.parseHTML( str ),          nodeNames = [];                   $geek.append( html );    </script></body></html>                                                                                
Output:
Example 2: In this example, the parseHTML() Method create an array of DOM nodes using an HTML string and insert it into a div.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseHTML() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  </head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | parseHTML() method</h3>    <div id="geek">    </div>           <script>        var $geek = $( "#geek" ),          str = "A <b>computer science portal</b> for <b>geeks</b>",          html = jQuery.parseHTML( str ),          nodeNames = [];                   $geek.append( html );                   $.each( html, function( i, el ) {          nodeNames[ i ] = "<li>" + el.nodeName + "</li>";        });                   $geek.append( "<h3>Node Names:</h3>" );        $( "<b></b>" )          .append( nodeNames.join( "" ) )          .appendTo( $geek );    </script></body></html>                            
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Tryit Editor v3.7

CSS Grid Item
Tryit: Using grid-area to name grid items
How to compare two columns in an R data frame for an exact match?

Sometimes analysis requires the user to check if values in two columns of an R data frame are exactly the same or not, this is helpful to analyze very large data frames if we suspect the comparative values in two columns. This can be easily done with the help of ifelse function.
Consider the below data frame −
 Live Demo
x1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE)
y1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE)
df1<-data.frame(x1,y1)
df1
     x1    y1
1 Spring Autumn
2 Winter Winter
3 Summer Summer
4 Autumn Autumn
5 Summer Autumn
6 Autumn Autumn
7 Summer Winter
8 Spring Spring
9 Summer Spring
10 Winter Winter
11 Autumn Summer
12 Autumn Summer
13 Spring Winter
14 Spring Winter
15 Spring Spring
16 Summer Autumn
17 Spring Winter
18 Winter Summer
19 Summer Spring
20 Spring Autumn
Determining whether each value in x1 and y1 are same or not −
ifelse(df1$x1==df1$y1,"Yes","No")
[1] "No" "Yes" "Yes" "Yes" "No" "Yes" "No" "Yes" "No" "Yes" "No" "No"
[13] "No" "No" "Yes" "No" "No" "No" "No" "No"
 Live Demo
x2<-sample(c("Male","Female"),20,replace=TRUE)
y2<-sample(c("Male","Female"),20,replace=TRUE)
df2<-data.frame(x2,y2)
df2
   x2       y2
1 Male    Female
2 Female  Male
3 Female  Female
4 Male    Male
5 Female  Female
6 Male    Female
7 Female  Female
8 Male    Male
9 Male    Female
10 Female Female
11 Female Female
12 Male   Female
13 Male   Male
14 Female Male
15 Male   Male
16 Female Female
17 Male   Male
18 Female Female
19 Male   Female
20 Male   Female
Determining whether each value in x2 and y2 are the same or not −
> ifelse(df2$x2==df2$y2,"Yes","No")
[1] "No" "No" "Yes" "Yes" "Yes" "No" "Yes" "Yes" "No" "Yes" "Yes" "No"
[13] "Yes" "No" "Yes" "Yes" "Yes" "Yes" "No" "No"
MySQL query to set current date in the datetime field for all the column values

Let us first create a table −
mysql> create table DemoTable821(AdmissionDate datetime);
Query OK, 0 rows affected (1.24 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable821 values('2019-01-21');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable821 values('2018-11-02');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable821 values('2016-12-31');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable821 values('2015-03-19');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable821;
This will produce the following output −
+---------------------+
| AdmissionDate       |
+---------------------+
| 2019-01-21 00:00:00 |
| 2018-11-02 00:00:00 |
| 2016-12-31 00:00:00 |
| 2015-03-19 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
Here is the query to set current date in the DateTime field −
mysql> update DemoTable821 set AdmissionDate=CURDATE();
Query OK, 4 rows affected (0.74 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable821;
This will produce the following output −
+---------------------+
| AdmissionDate       |
+---------------------+
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
| 2019-08-03 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
MS SQL Server - Drop Database

To remove your database from MS SQL Server, use drop database command. Following two methods can be used for this purpose.
Following is the basic syntax for removing database from MS SQL Server.
Drop database <your database name>

To remove database name ‘Testdb’, run the following query.
Drop database Testdb

Connect to SQL Server and right-click the database you want to remove. Click delete command and the following screen will appear.
Click OK to remove the database (in this example, the name is Testdb as shown in the above screen) from MS SQL Server.

    32 Lectures 
     2.5 hours 

 Pavan Lalwani

    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    102 Lectures 
     10 hours 

 Pavan Lalwani

    52 Lectures 
     4 hours 

 Pavan Lalwani

    239 Lectures 
     33 hours 

 Gowthami Swarna

    53 Lectures 
     5 hours 

 Akshay Magre
 Print
 Add Notes
 Bookmark this page
Getter and Setter in Python

For the purpose of data encapsulation, most object oriented languages use getters and setters method. This is because we want to hide the attributes of a object class from other classes so that no accidental modification of the data happens by methods in other classes.
As the name suggests, getters are the methods which help access the private attributes or get the value of the private attributes and setters are the methods which help change or set the value of private attributes.
Below we write code to create a class, initialize it and access it variables without creating any additional methods.
class year_graduated:
   def __init__(self, year=0):
      self._year = year

# Instantiating the class
grad_obj = year_graduated()
#Printing the object
print(grad_obj)
#Printing the object attribute
print(grad_obj.year)
Running the above code gives us the following result -
<__main__.year_graduated object at 0x00F2DD50>
0
While the first print statement gives us the details of the object created, the second print object gives us the default value of the private attribute.
In the below examples we will make a class, initialize is and then add a getter and setter method to each of them. Then access the variables in these methods by instantiating the class and using these getter and setter methods. So you can hide your logic inside the setter method.
 Live Demo
class year_graduated:
   def __init__(self, year=0):
      self._year = year

   # getter method
   def get_year(self):
      return self._year

# setter method
def set_year(self, a):
self._year = a

grad_obj = year_graduated()
# Before using setter
print(grad_obj.get_year())

# After using setter
grad_obj.set_year(2019)
print(grad_obj._year)
Running the above code gives us the following result:
0
2019
In the next example we see how to make the methods private so that the variables in it cannot be manipulated by external calling functions. They can only be manipulated by functions inside the class. They become private by prefixing them with two underscores.
 Live Demo
class year_graduated:
   def __init__(self, year=32):
      self._year = year

   # make the getter method
   def get_year(self):
      return self.__year

   # make the setter method
   def set_year(self, a):
      self.__year = a

grad_obj = year_graduated()
print(grad_obj._year)

# Before using setter
print(grad_obj.get_year())
#
# # After using setter
grad_obj.set_year(2019)
print(grad_obj._year)
Running the above code gives us the following result:
32
AttributeError: 'year_graduated' object has no attribute '_year_graduated__year'
No we can access the private attribute values by using the property method and without using the getter method.
 Live Demo
class year_graduated:
   def __init__(self, year=32):
      self._year = year

   @property
   def Aboutyear(self):
      return self.__year

   @Aboutyear.setter
   def Aboutyear(self, a):
      self.__year = a

grad_obj = year_graduated()
print(grad_obj._year)

grad_obj.year = 2018
print(grad_obj.year)
Running the above code gives us the following result:
32
2018
How to format number in JSP?

The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.
The <fmt:formatNumber> tag has the following attributes −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
   <head>
      <title>JSTL fmt:formatNumber Tag</title>
   </head>
   <body>
      <h3>Number Format:</h3>
      <c:set var = "balance" value = "120000.2309" />
      <p>Formatted Number (1): <fmt:formatNumber value = "${balance}" type = "currency"/></p>
      <p>Formatted Number (2): <fmt:formatNumber type = "number" maxIntegerDigits = "3" value = "${balance}" /></p>
      <p>Formatted Number (3): <fmt:formatNumber type = "number" maxFractionDigits = "3" value = "${balance}" /></p>
      <p>Formatted Number (4): <fmt:formatNumber type = "number" groupingUsed = "false" value = "${balance}" /></p>
   </body>
</html>
The above code will generate the following result −
Number Format:
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Create an italic text in HTML

The HTML <i> tag is used to display the content in italic.You can try to run the following code to create an italic text in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML i Tag</title>
   </head>
   <body>
      <p>We liked the movie <i>Avengers</i></p>
   </body>
</html>
Python + Selenium | How to locate elements in span class & not unique ID

We can locate elements in span class and not unique id with the help of the Selenium webdriver. We can identify an element having a class attribute with the help of the locator xpath, css or class name.
To locate elements with these locators we have to use the By.xpath, By.xpath or By.cssSelector method. Then pass the locator value as a parameter to this method.
Let us see the html code of a button having a span class and try to identify it.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
l = driver.find_element_by_id("textemail")
l.send_keys("abc@gmail.com")
#get value entered
s = l.get_attribute('value')
#identify element with span class
m = driver.find_element_by_xpath("//span[@class='input_group_button']")
#verify if element present
b = m.is_displayed()
if b:
   print("Element with span class available")
else:
   print("Element with span class not available")
#close browser
driver.close()
How to display HTML element with JavaScript?

Use the visibility property in JavaScript to show an element. You can try to run the following code to learn how to work with visibility property:
<!DOCTYPE html>
<html>
   <body>
      <p id="pid">Demo Text</p>
      <button type = "button" onclick = "displayHide()"> Hide </button>
      <button type = "button" onclick = "displayShow()"> Show </button>
      <script>
         function displayHide() {
            document.getElementById("pid").style.visibility = "hidden";
         }
         function displayShow() {
            document.getElementById("pid").style.visibility = "visible";
         }
      </script>
   </body>
</html>
How to add a margin to a tkinter window? - GeeksforGeeks

18 Nov, 2021
In this article, we will see how to add a margin to the Tkinter window. 
We will use the frame for adding the margin:
Syntax:
Frame(root, options)
Approach:
Importing the module.
Create the main window (container)
Use frame and frame.pack()
Apply the event Trigger on the widgets.
Without using frame method:
Python3
# importing the modulefrom tkinter import * # main containerroot = Tk() # container contentlabel = Label(root, text='GeeksForGeeks.org!',              width=45, height=10) label.pack() root.mainloop()
Output : 
Example 1: 
By using the frame method of this module. With frame() we have used pack() function to place the content and to create margin. 
window.pack(options)
Options are fill, expand or side.
Below is the implementation: 
Python3
# importing modulefrom tkinter import * # main containerroot = Tk() # frameframe = Frame(root, relief = 'sunken',              bd = 1, bg = 'white')frame.pack(fill = 'both', expand = True,           padx = 10, pady = 10) # container contentlabel = Label(frame, text = 'GeeksForGeeks.org!',              width = 45, height = 10, bg = "black",              fg = "white")label.pack() root.mainloop()
Output :  
Example 2: We can also the grid() method of the module to give margin to the container or window.
Syntax :  
window.grid(grid_options) 
Python3
# importing the modulefrom tkinter import * # container windowroot = Tk() # frameframe = Frame(root) # content of the frameframe.text = Text(root)frame.text.insert('1.0', 'Geeks for Geeks') # to add margin to the frameframe.text.grid(row = 0, column = 1,                padx = 20, pady = 20) # simple buttonframe.quitw = Button(root)frame.quitw["text"] = "Logout",frame.quitw["command"] = root.quitframe.quitw.grid(row = 1, column = 1) root.mainloop()
Output :  
 
simranarora5sos
kalrap615
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Exploring Brent Oil Prices Data using Python | by Sadrach Pierre, Ph.D. | Towards Data Science

In this post, we will perform some simple exploratory analysis on the Brent Oil Prices dataset. We start by importing the pandas library and reading the data into a pandas data frame:
import pandas as pddf = pd.read_csv("BrentOilPRices.csv")
We can also display the first five rows:
print(df.head())
Next, we can convert the ‘Date’ column into a datetime object and view the first five rows:
df['Date'] = pd.to_datetime(df['Date'])print(df.head())
We can also view the last five rows of data:
print(df.head())
We can see from the data that the prices are from 1987–2019. We can also see that there are 8,216 rows of data. Next, we can plot the prices vs. time using the ‘seaborn’ data visualization package:
import seaborn as snssns.set()plt.title('Brent Oil Prices')sns.lineplot(df['Date'], df['Price'])
We can also look at the distribution of prices:
In the next post we will build a simple regression model to predict future Brent Oil prices. The code from this post is available on GitHub. Thanks for reading. Good luck and happy machine learning!