code-rag-bench/online-tutorials huggingface dataset:
Accessing protected members in a C++ derived class

A class in C++ has public, private and protected sections which contain the corresponding class members. Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.
A program that demonstrates accessing protected data members in a derived class in C++ is given as follows −
 Live Demo
#include <iostream>
using namespace std;
class Base {
   protected :
   int num = 7;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of num is: " << num;
   }
};
int main() {
   Derived obj;
   obj.func();
   return 0;
}
The output of the above program is as follows.
The value of num is: 7
Now, let us understand the above program.
In the class Base, the data member is num which is protected. The class Derived inherits the class Base. The function func() prints the value of num. The code snippet for this is given as follows.
class Base {
   protected :
   int num = 7;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of num is: " <<< num;
   }
};
In the function main(), the object obj of class Derived is created. Then the function func() is called. The code snippet for this is given as follows.
int main() {
   Derived obj;
   obj.func();
   return 0;
}
What is Bitwise NOT Operator (~) in JavaScript?

It is a unary operator and operates by reversing all the bits in the operand.
You can try to run the following code to learn how to work with Bitwise NOT Operator(~) −
<html>
   <body>
      <script>
         var b = 3;   // Bit presentation 11

         document.write("(~b) => ");
         result = (~b);
         document.write(result);
      </script>
   </body>
</html>
Which one is better to insert NULL or empty string in MySQL?

In innoDB, NULL occupies less space as compared to empty string. Also, the NULL length is
null while length of the empty string is 0.
To understand this, a table is created with the help of create command which is given as
follows −
mysql> CREATE table DemoEmptyAndNULL
-> (
-> Message varchar(100)
-> );
Query OK, 0 rows affected (0.49 sec)
After creating the table successfully, an empty record is inserted into the table with the help of
insert command which is as follows −
mysql> INSERT into DemoEmptyAndNULL values(' ');
Query OK, 1 row affected (0.17 sec)
After inserting the record, we can display all the records with the help of the select command
which is as follows −
mysql> SELECT * from DemoEmptyAndNULL;

After executing the above query, following output is obtained −
+---------+
| Message |
+---------+
|         |
+---------+
1 row in set (0.00 sec)
The syntax to check the length of an empty string with the help of a built in function count is as
follow −
select count(column_name) from yourTableName;

The above syntax is used to get the length of an empty string which is given as follows −
mysql> select count(message) from DemoEmptyAndNULL;
After executing the above query, the following is the output −
+----------------+
| count(message) |
+----------------+
| 1              |
+----------------+
1 row in set (0.06 sec)
From the above output it is clear that the length of the empty string is 1.
Now we will check the length of NULL. First, the record that was inserted into the table is
deleted using delete command as follows −
mysql> delete from DemoEmptyAndNULL where message=' ';
Query OK, 1 row affected (0.19 sec)
The following query is used to check that there is no record in the table right now
mysql> SELECT * from DemoEmptyAndNULL;
Empty set (0.00 sec)
Now, the record with null value is inserted into the table as follows −
mysql> INSERT into DemoEmptyAndNULL values();
Query OK, 1 row affected (0.18 sec)
The record is displayed using the select command and the output obtained is as follows −
+---------+
| Message |
+---------+
| NULL    |
+---------+
1 row in set (0.00 sec)
Now, there is only one record with null value in the table. To find its length following query is
used −
mysql> select count(message) from DemoEmptyAndNULL;

The following is the output of the above query −
+----------------+
| count(message) |
+----------------+
| 0              |
+----------------+
1 row in set (0.00 sec)
The above output means that count is 0 for null value.
Let us check the MySQL version.
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.06 sec)
So it is better to use empty string for database as allowing NULL value forces the system to do
extra work and does not give the data that you are looking for. However, NULL does not throw
any exception when the count() function is executed.
Python program to print even numbers in a list

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a list iterable, we need to print all the even numbers in the list.
Here we will be discussing three approaches for the given problem statement.
list1 = [11,23,45,23,64,22,11,24]
# iteration
for num in list1:
   # check
   if num % 2 == 0:
      print(num, end = " ")
64 22 24
list1 = [11,23,45,23,64,22,11,24]
# lambda exp.
even_no = list(filter(lambda x: (x % 2 == 0), list1))
print("Even numbers in the list: ", even_no)
Even numbers : [64, 22, 24]
list1 = [11,23,45,23,64,22,11,24]
#list comprehension
even_nos = [num for num in list1 if num % 2 == 0]
print("Even numbers : ", even_nos)
Even numbers : [64, 22, 24]
In this article, we learned about the approach to print even numbers in the input list.
Preorder from Inorder and Postorder traversals in C++

In this problem, we are given the inorder and postorder traversal of a binary tree. Our task is to print the postorder traversal of the tree.
Let’s take an example to understand the problem
Input:inorder: 16 7 21 12 1 5 9
postorder: 16 21 7 1 9 5 12
Output: preorder: 12 7 16 21 5 1 9
Explanation: the binary tree is :
To solve this problem, a simple solution could be creating a tree using the given traversals and then finding the preorder traversal of the tree. But this method will be more complex for the system.
A more effective solution to solve the problem is using the stack data structure. Let’s see each node of the tree. The root of the tree is the last item in postorder traversal. Now we have to separate the left and right subtree of the binary tree. Since we know the root node of the tree. In the postorder traversal, all elements before the root node are of left subtree and after the root are of right subtree.
Like this, we will find all elements and store the nodes in the stack and the print elements of the stack which gives the preorder traversal.
The implementation of our solution in Java
 Live Demo
import java.util.Stack;
public class Main {
   static int postIndex;
   void preOrder(int[] in, int[] post, int inStrt, int inEnd, Stack<Integer> preorder) {
      if (inStrt > inEnd)
         return;
      int val = post[postIndex];
      int inIndex = searchValue(in, val);
      postIndex--;
      preOrder(in, post, inIndex + 1, inEnd, preorder);
      preOrder(in, post, inStrt, inIndex - 1, preorder);
      preorder.push(val);
   }
   void printPreOrderTraversal(int[] in, int[] post) {
      int len = in.length;
      postIndex = len - 1;
      Stack<Integer> preorder = new Stack<Integer>();
      preOrder(in, post, 0, len - 1, preorder);
      while (preorder.empty() == false)
      System.out.print(preorder.pop()+" ");
   }
   int searchValue(int[] in, int data){
      int i = 0;
      for (i = 0; i < in.length; i++)
         if (in[i] == data)
      return i;
      return i;
   }
   public static void main(String ars[]){
      int in[] = { 4, 10, 12, 15, 18, 22, 24, 25, 31, 35, 44, 50, 66, 70, 90 };
      int post[] = { 4, 12, 10, 18, 24, 22, 15, 31, 44, 35, 66, 90, 70, 50, 25 };
      Main tree = new Main();
      System.out.println("Preorder Traversal of the tree is: ");
      tree.printPreOrderTraversal(in, post);
   }
}
Preorder Traversal of the tree is:
25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
CHAR() Function in SQL - GeeksforGeeks

31 Aug, 2020
CHAR() :This function could be used to find the character based on the ASCII (American Standard Code for Information Interchange) code. CHAR() function do not support multiple integers as arguments.
Syntax :
SELECT CHAR(code);

Note –Parameter code is mandatory, code evaluates to an integer value from 0 to 255.
Example-1:
SELECT CHAR(65) AS Result;

Output :
Example-2:
SELECT CHAR(165) AS Result;

Output :
Example-3:
SELECT CHAR(67, 255) AS Result;

Output :The char function requires 1 argument(s). As shown in the above example, when multiple integers are provided, it gets an error.
Example-4:
SELECT CHAR(1000) AS Result;

Output :
Note –The above example results in NULL because the input is out of the range from 0 to 255.
Example-5:
SELECT 'Hello' + CHAR(10) + 'World' AS Result;

Output :
Note –In the above example, the CHAR(10) returns the new line, therefore, the second string is placed in the new line.
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
How to Select Data Between Two Dates and Times in SQL Server?
SQL vs NoSQL: Which one is better to use?
Advanced SQL Interview Questions
SQL | OFFSET-FETCH Clause
Insert multiple values into multiple tables using a single statement in SQL Server
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Comments
SQL | CREATE
Adding multiple constraints in a single table
Perl uc Function

This function returns an uppercased version of EXPR, or $_ if not specified. Check ucfirst() function which will return only first character in uppercase.
Following is the simple syntax for this function −
uc EXPR

uc

This function returns String in uppercase.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$string = 'the cat sat on the mat.';
$u_string = uc($string);

print "First String |$string|\n";
print "Second String |$u_string|\n";
When above code is executed, it produces the following result −
First String |the cat sat on the mat.|
Second String |THE CAT SAT ON THE MAT.|


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to change a color bar in Plotly in Python - GeeksforGeeks

28 Nov, 2021
In this article, we will learn how to change a color bar in Plotly Python. 
Syntax:
We can change the color by using the color scale.
fig = go.Figure(data=go.Scatter(
    y=np.random.randn(500),
    mode='markers',
    marker=dict(
        size=8,
        
        # set color equal to a variable
        color=np.random.randn(500),
        
        # one of plotly colorscales
        colorscale='hot',
        
        # enable color scale
        showscale=True
    )
))
Example 1:
Python3
# import the modulesimport plotly.graph_objects as goimport numpy as np  # create figure# from the data using numpy random methodfig = go.Figure(data=go.Scatter(    y=np.random.randn(500),    mode='markers',    marker=dict(        size=8,                # set color equal to a variable        color=np.random.randn(500),                  # one of plotly colorscales        colorscale='hot',                  # enable color scale        showscale=True    )))  # display figurefig.show()
Output:
Example 2:
Set color to hot_r
Python3
import plotly.graph_objects as goimport numpy as np  fig = go.Figure(data=go.Line(    y = np.random.randn(500),    mode='markers',    marker=dict(        size=8,        color=np.random.randn(500), #set color equal to a variable        colorscale='hot_r', # one of plotly colorscales        showscale=True  # enable color scale    )))  fig.show()
Output:
Example 3:
Set color to turbo_r
Python3
import plotly.graph_objects as goimport numpy as np  fig = go.Figure(data=go.Scatter(    y=np.random.randn(500),    mode='markers',    marker=dict(        size=8,                # set color equal to a variable        color=np.random.randn(550),                  # one of plotly colorscales        colorscale='turbo_r',                  # enable color scale        showscale=True    )))# displayfig.show()
Output:
Python-Plotly
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 Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Number of 1 Bits in Python

Suppose we have an unsigned number n. We have to find the number of 1s in a binary representation of this number. This is also known as Hamming Weight. So if the number is like 000000101101, then the result will be 4.
To solve this, we will use these steps −
Take the number and convert it into a binary string
set count = 0
for each character e in a binary stringif the character is ‘1’, then increase count by 1
if the character is ‘1’, then increase count by 1
return count
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def hammingWeight(self, n):
      """
      :type n: int
      :rtype: int
      """
      n = str(bin(n))
      print(n)
      one_count = 0
      for i in n:
         if i == "1":
            one_count+=1
      return one_count
num = "000000101101"
ob1 = Solution()
print(ob1.hammingWeight(num))
num = "000000101101"
4
Python | Animation in Kivy

06 Feb, 2020
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
 Kivy Tutorial – Learn Kivy with Examples.
Animation and AnimationTransition are used to animate Widget properties. You must specify at least a property name and target value. To use Animation, follow these steps:
Setup an Animation object
Use the Animation object on a Widget
To use animation you must have to import:from kivy.animation import Animation
Basic Approaches: 

1) import kivy
2) import kivyApp
3) import Button
4) import Animation
5) set kivy version (optional)
6) Create the App class
7) Define animation
8) Add animations
9) Run the App
Implementation of the Approach:
# Widget animation in kivy    # import kivy module import kivy     # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require("1.9.1")     # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App   # To work with Animation you must have to import itfrom kivy.animation import Animation  # The Button is a Label with associated# actions that are triggered when the button# is pressed (or released after a click/touch). from kivy.uix.button import Button  # Create the App classclass TestApp(App):     # Defining the function in which animations are added         def animate(self, instance):        # create an animation object. This object could be stored        # and reused each call or reused across different widgets.        # += is a sequential step, while &= is in parallel        animation = Animation(pos =(100, 100), t ='out_bounce')        animation += Animation(pos =(200, 100), t ='out_bounce')        animation &= Animation(size =(500, 500))        animation += Animation(size =(100, 50))          # apply the animation on the button, passed in the "instance" argument        # Notice that default 'click' animation (changing the button        # color while the mouse is down) is unchanged.        animation.start(instance)      def build(self):        # create a button, and  attach animate()         # method as a on_press handler        button = Button(size_hint =(None, None), text ='plop',                        on_press = self.animate)        return button  # run the Appif __name__ == '__main__':    TestApp().run()
Output:
When the Button as shown in the image when you click on it it shows the different animation.
ManasChhabra2
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exploring Correlation in Python

19 Jan, 2019
This article aims to give a better understanding of a very important technique of multivariate exploration.
Correlation Matrix is basically a covariance matrix. Also known as the auto-covariance matrix, dispersion matrix, variance matrix, or variance-covariance matrix. It is a matrix in which i-j position defines the correlation between the ith and jth parameter of the given data-set.
When the data points follow a roughly straight-line trend, the variables are said to have an approximately linear relationship. In some cases, the data points fall close to a straight line, but more often there is quite a bit of variability of the points around the straight-line trend. A summary measure called the correlation describes the strength of the linear association. Correlation summarizes the strength and direction of the linear (straight-line) association between two quantitative variables. Denoted by r, it takes values between -1 and +1. A positive value for r indicates a positive association, and a negative value for r indicates a negative association.The closer r is to 1 the closer the data points fall to a straight line, thus, the linear association is stronger. The closer r is to 0, making the linear association weaker.
To get the link to House_price Data click here.
Loading Libraries
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom scipy.stats import norm
Loading Data
data = pd.read_csv("House Price.csv")data.shape
Output:
(1460, 81)
‘Sales Price’ Description
data['SalePrice'].describe()
Output:
count      1460.000000
mean     180921.195890
std       79442.502883
min       34900.000000
25%      129975.000000
50%      163000.000000
75%      214000.000000
max      755000.000000
Name: SalePrice, dtype: float64
Histogram
plt.figure(figsize = (9, 5))data['SalePrice'].plot(kind ="hist")
Output:
 
Code #1: Correlation Matrix
corrmat = data.corr()  f, ax = plt.subplots(figsize =(9, 8))sns.heatmap(corrmat, ax = ax, cmap ="YlGnBu", linewidths = 0.1)
Output:
Code #2: Grid Correlation Matrix
corrmat = data.corr()  cg = sns.clustermap(corrmat, cmap ="YlGnBu", linewidths = 0.1);plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation = 0)  cg
Output:
Code #3: Correlation for Saleprice
# saleprice correlation matrix# k : number of variables for heatmapk = 15   cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index  cm = np.corrcoef(data[cols].values.T)f, ax = plt.subplots(figsize =(12, 10))  sns.heatmap(cm, ax = ax, cmap ="YlGnBu",            linewidths = 0.1, yticklabels = cols.values,                               xticklabels = cols.values)
Output:
data-science
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Supervised and Unsupervised learning
Read JSON file using Python
Python map() function
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Java.util.Arraylist.indexOf() in Java

10 Oct, 2019
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
Syntax :
public int IndexOf(Object o)
obj : The element to search for.

// Java code to demonstrate the working of// indexOf in ArrayList  // for ArrayList functionsimport java.util.ArrayList;  public class IndexOfEx {  public static void main(String[] args) {         // creating an Empty Integer ArrayList  ArrayList<Integer> arr = new ArrayList<Integer>(5);    // using add() to initialize values  arr.add(1);  arr.add(2);  arr.add(3);  arr.add(4);    // printing initial value  System.out.print("The initial values in ArrayList are : ");  for (Integer value : arr) {  System.out.print(value);  System.out.print(" ");  }      // using indexOf() to find index of 3  int pos =arr.indexOf(3);      // prints 2  System.out.println("\nThe element 3 is at index : " + pos);  }    }   
Output:
The initial values in ArrayList are : 1 2 3 4 
The element 3 is at index : 2

Practical Application : The index functions are mostly useful to determine last or first occurrence of events, for example last occurrence of 6 in a throw of a die, or 1st occurrence of any letter in a name etc.
One more example:
// Java code to demonstrate the application of// index functions in ArrayList  // for ArrayList functionsimport java.util.ArrayList;  public class AppliIndex {  public static void main(String[] args) {         // creating an Empty Integer ArrayList  ArrayList<Integer> arr = new ArrayList<Integer>(10);    // using add() to initialize dice values  arr.add(1);  arr.add(2);  arr.add(4);  arr.add(6);  arr.add(5);  arr.add(2);  arr.add(6);  arr.add(1);  arr.add(6);  arr.add(4);    // using IndexOf() to find first index of 6  int pos1 =arr.indexOf(6);      // using lastIndexOf() to find last index of 6  int pos2 =arr.lastIndexOf(6);      // to balance 0 based indexing  pos1 = pos1+1;  pos2 = pos2+1;      // printing first index of 6  System.out.println("The first occurrence of 6 is  : " + pos1);      // printing last index of 6  System.out.println("The last occurrence of 6 is  : " + pos2);      }    }   
Output:
The first occurrence of 6 is  : 4
The last occurrence of 6 is  : 9

This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java
place_info(), pack_info() and grid_info() methods in Tkinter

01 Aug, 2020
To get all the information about the options of the geometry management of a widget place_info(), pack_info() and grid_info() methods in tkinter are used accordingly.  
This method is used for getting information about geometry management of a widget like position and size of a window, either in absolute terms, or relative to another window. 
Syntax : widget.place_info() 
Parameter: None
Returns : Returns a dictionary of the info of the place options of the current widget  
Code 1:  
Python3
# Importing all functions/classes# from tkinter module from tkinter import *  # toplevel window root = Tk()   # setting window sizeroot.geometry("810x350")  # create a Label widget whose# place info is to be obtainedrect = Label(root,              text = "MY PLACE INFO IS SHOWN BELOW",              bg = "pink")  # place a widget in a specific # position in the parent widget.rect.place(rely = 0.1, relx = 0.2,           relwidth = 0.6,            relheight = 0.3)  # widget displaying place info of rectlabel = Label(root)  # place a widget in a specific# position in the parent widget.label.place(rely = 0.6)  # get a info of the placelabel['text'] = rect.place_info()   # start the GUIroot.mainloop() 
Output: 
 
This method is used for getting information about geometry management of a widget like expand, side, fill, padding values etc.
Syntax : widget.pack_info() 
Parameter: None
Returns : Returns a dictionary of the info of the pack options of the current widget  
Code 2:  
Python3
# Importing all functions/classes# from tkinter module from tkinter import *  # toplevel window root = Tk()   # create a Label widget whose # pack info is to be obtainedrect = Label(root,              text = "MY PACK INFO IS SHOWN BELOW",             bg = "pink")  # placing them in a specific position# in the parent widget.rect.pack(expand = True)  # create a Labellabel = Label(root)  label.pack()  label['text'] = rect.pack_info()   # start the GUI root.mainloop() 
Output: 
 
This method is used for getting information about geometry management of a widget like row number, column number ,rowsapn, columnspan, padding values etc.
Syntax : widget.grid_info() 
Parameter: None
Returns : Returns a dictionary of the info of the grid options of the current widget  
Code 3:  
Python3
# Importing all functions/classes # from tkinter module from tkinter import *  # toplevel window root = Tk()   # widget whose grid info is to be obtainedrect = Label(root,              text = "MY GRID INFO IS SHOWN BELOW",              bg = "pink")  # grid method is used for placing# the widgets at respective positions# in table like structure .rect.grid(stick = N)  # create a labellabel = Label(root)  label.grid()  label['text'] = rect.grid_info()   # start the GUIroot.mainloop() 
Output:  
 
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pandas Groupby and Computing Mean

26 Nov, 2020
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. 
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. It is helpful in the sense that we can :
Compute summary statistics for every group
Perform group-specific transformations
Do the filtration of data
The groupby() involves a combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.
Example 1:
Python3
# import required moduleimport pandas as pd  # create dataframedf = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'],                     'Max Speed': [380., 370., 24., 26.]})  # use groupby() to compute meandf.groupby(['Animal']).mean()
Output
Example 2:
Python3
# import required moduleimport pandas as pd  # assign listl = [[100, 200, 300], [10, None, 40], [20, 10, 30], [100, 200, 200]]  # create dataframedf = pd.DataFrame(l, columns=["a", "b", "c", ])  # use groupby() to generate meandf.groupby(by=["b"]).mean()
Output:
Example 3:
Python3
# import required moduleimport pandas as pd  # assign dataipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',  'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],              'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2],              'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016, 2017, 2016, 2014, 2015, 2017],              'Points': [876, 789, 863, 673, 741, 812, 756, 788, 694, 701, 804, 690]}  # create dataframedf = pd.DataFrame(ipl_data)  # use groupby() to generate meandf.groupby(['Team']).mean()
Output:
Python pandas-groupby
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2007 | Question 57

28 Jun, 2021
A single processor system has three resource types X, Y and Z, which are shared by three processes. There are 5 units of each resource type. Consider the following scenario, where the column alloc denotes the number of units of each resource type allocated to each process, and the column request denotes the number of units of each resource type requested by a process in order to complete execution. Which of these processes will finish LAST?
 
    alloc           request
    X Y Z            X Y Z
P0  1 2 1            1 0 3
P1  2 0 1            0 1 2
P2  2 2 1            1 2 0 
(A) P0(B) P!(C) P2(D) None of the above, since the system is in a deadlockAnswer: (C)Explanation: A single processor system has three resource types X, Y and Z, which are shared by three processes. There are 5 units of each resource type.
So, the resource instances which are left being unallocated = { unallocated resources= total resources-allocated resources }
now, from the request table, you can say that only request of P1 can be satisfied. So P1 can finish its execution first. Once P1 is done, it releases 2, 0 and 1 units of X, Y and Zrespectively which were allocated to P1.So, Now unallocated resource instance are = + =
Now Among P0 and P2, needs of P0 can only be satisfied. So P0 finishes its execution. Once P2 is done, It releases 2,2,and 1 units of X,Y and Z respectively which were allocated to P2.SO, Now unallocated resource instance are= + = . Finally, P2 finishes its execution. So, P2 is the process which finishes in end.
Option (C) is the correct answer.
See question 2 of https://www.geeksforgeeks.org/operating-systems-set-13/
Reference:https://www.geeksforgeeks.org/bankers-algorithm-in-operating-system-2/
This solution is contributed by Nitika BansalQuiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
codecs.decode() in Python

26 Mar, 2020
With the help of codecs.decode() method, we can decode the binary string into normal form by using codecs.decode() method.
Syntax : codecs.decode(b_string)
Return : Return the decoded string.
Example #1 :In this example we can see that by using codecs.decode() method, we are able to get the decoded string which can be in binary form by using this method.
# import codecsimport codecs  s = b'GeeksForGeeks'# Using codecs.decode() methodgfg = codecs.decode(s)  print(gfg)
Output :
GeeksForGeeks
Example #2 :
# import codecsimport codecs  s = b'I love python.'# Using codecs.decode() methodgfg = codecs.decode(s)  print(gfg)
Output :
I love python.
Python codecs-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | Get unique values from a list
Python | datetime.timedelta() function
Python Program for Odd-Even Sort / Brick Sort

28 Jun, 2021
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases.
In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements.
# Python Program to implement # Odd-Even / Brick Sort  def oddEvenSort(arr, n):    # Initially array is unsorted    isSorted = 0    while isSorted == 0:        isSorted = 1        temp = 0        for i in range(1, n-1, 2):            if arr[i] > arr[i+1]:                arr[i], arr[i+1] = arr[i+1], arr[i]                isSorted = 0                          for i in range(0, n-1, 2):            if arr[i] > arr[i+1]:                arr[i], arr[i+1] = arr[i+1], arr[i]                isSorted = 0          return    arr = [34, 2, 10, -9]n = len(arr)  oddEvenSort(arr, n);for i in range(0, n):    print(arr[i], end =" ")      # Code Contribute by Mohit Gupta_OMG <(0_o)>
Output :
-9 2 10 34 
Please refer complete article on Odd-Even Sort / Brick Sort for more details!
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python Program to check Armstrong Number
Python Program for simple interest
Python Program for Merge Sort
Appending a dictionary to a list in Python
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python | Remove spaces from a string
Reading an excel file using Python openpyxl module
Python | Indices of N largest elements in list - GeeksforGeeks

28 Aug, 2019
Sometimes, while working with Python lists, we can have a problem in which we wish to find N largest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of N largest elements in list.
Method : Using sorted() + lambda + list slicingThis task can be performed using the combination of above functions. In this the sorted(), can be used to get the container in way which requires to get N largest elements at rear end and then the indices can be computed using list slicing.
# Python3 code to demonstrate working of# Indices of N largest elements in list# using sorted() + lambda + list slicing  # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19]  # printing original listprint("The original list is : " + str(test_list))  # initialize N N = 4  # Indices of N largest elements in list# using sorted() + lambda + list slicingres = sorted(range(len(test_list)), key = lambda sub: test_list[sub])[-N:]  # printing resultprint("Indices list of max N elements is : " + str(res))
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of max N elements is : [1, 4, 2, 6]

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

15 Feb, 2019
The value of 351 mod 5 is _________ .
Note: This was Numerical Type question.(A) 1(B) 2(C) 3(D) 4Answer: (B)Explanation: According to chinese remainder theorem:
= 351 mod 5 
= (33)17 mod 5 
= (27)17 mod 5
= {(22)8*21} mod 5
= {(4)8*(2)} mod 5
= {(-1)8*(2)} mod 5
= {(1*2)} mod 5
= {(2)} mod 5
= 2  
Note: You can solve it directly by using power and mod operations in given calculator.
So, option (B) is correct.Quiz of this Question
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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
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
Python - Add space between Numbers and Alphabets in String - GeeksforGeeks

02 Sep, 2020
Given a string consisting of numbers and Strings, add space between them.
Input : test_str = ‘ge3eks4geeks is1for10geeks’Output : ge 3 eks 4 geeks is 1 for 10 geeksExplanation : Numbers separated from Characters.
Input : test_str = ‘ge3eks4geeks’Output : ge 3 eks 4 geeksExplanation : Numbers separated from Characters by space.
Method #1 : Using regex + sub() + lambda
In this, we perform the task of finding alphabets by appropriate regex and then sub() is used to do replacements, lambda does the task of adding spaces in between.
Python3
# Python3 code to demonstrate working of # Add space between Numbers and Alphabets in String# using regex + sub() + lambdaimport re  # initializing stringtest_str = 'geeks4geeks is1for10geeks'  # printing original Stringprint("The original string is : " + str(test_str))  # using sub() to solve the problem, lambda used tp add spaces res = re.sub("[A-Za-z]+", lambda ele: " " + ele[0] + " ", test_str)  # printing result print("The space added string : " + str(res)) 
The original string is : geeks4geeks is1for10geeks
The space added string :  geeks 4 geeks   is 1 for 10 geeks 

Method #2 : Using regex + sub()
This is one of ways to solve. In this, we look for numerics rather than alphabets to perform task of segregation, similar approach by use numerics are search criteria to add spaces.
Python3
# Python3 code to demonstrate working of # Add space between Numbers and Alphabets in String# using regex + sub()import re  # initializing stringtest_str = 'geeks4geeks is1for10geeks'  # printing original Stringprint("The original string is : " + str(test_str))  # using sub() to solve the problem, lambda used tp add spaces res = re.sub('(\d+(\.\d+)?)', r' \1 ', test_str)  # printing result print("The space added string : " + str(res)) 
The original string is : geeks4geeks is1for10geeks
The space added string : geeks 4 geeks is 1 for 10 geeks

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

This method will get/set the minutes. It takes input from 0-59, if greater than the range
provided, then it will add to the hour.
moment().minute(Number);
moment().minute();
moment().minutes(Number);
moment().minutes();

var m = moment().minute(); // gets the current minute
var d = moment().minute(5); // sets the minute as shown below
 Print
 Add Notes
 Bookmark this page
Write Paragraph in Word Document

How to write a paragraph in a word document using Java.
Following is the program to write a paragraph in a word document using Java.
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class ParagraphInWord {
   public static void main(String[] args)throws Exception {
       
      //Blank Document
      XWPFDocument document = new XWPFDocument();

      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File
         ("C:/poiword/createparagraph.docx"));

      //create Paragraph
      XWPFParagraph paragraph = document.createParagraph();
      XWPFRun run = paragraph.createRun();
      run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming Languages.");

      document.write(out);
      out.close();
      System.out.println("createparagraph.docx written successfully");
   }
}
 Print
 Add Notes
 Bookmark this page
How to change MySQL error message language?

You can use lc_messages to change MySQL error message language. The syntax is as follows −
SET lc_messages = 'yourLanguage';
To understand the concept, let us create a table with some error and check the error message language.
Here, we have set the local message to French. Let us first create a table −
mysql> create table errorMessagelanguage
   -> (
   -> Error_MessageId int,
   -> Error_Message varchar(100),
   -> );
The error message is as follows −
ERROR 1064 (42000): Erreur de syntaxe près de ')' à la ligne 5
Now you can set the error message to be in English language. The query is as follows −
mysql> set lc_messages ='en_US';
Query OK, 0 rows affected (0.00 sec)
Now create a table with some error and check the error message language −
mysql> create table errorMessagelanguage
   -> (
   -> Error_MessageId int,
   -> Error_Message varchar(100),
   -> );
Here is the output −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5
Fade Out Right Animation Effect with CSS

To implement Fade Out Right Animation Effect on an image with CSS, you can try to run the following code −
Live Demo
<html>
   <head>
      <style>

         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }

         @-webkit-keyframes fadeOutRight {
            0% {
               opacity: 1;
               -webkit-transform: translateX(0);
            }
            100% {
               opacity: 0;
               -webkit-transform: translateX(20px);
            }
         }

         @keyframes fadeOutRight {
            0% {
               opacity: 1;
               transform: translateX(0);
            }
            100% {
               opacity: 0;
               transform: translateX(20px);
            }
         }

         .fadeOutRight {
            -webkit-animation-name: fadeOutRight;
            animation-name: fadeOutRight;
         }
         animation-name: fadeOutLeft;
     
   </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeOutRight"></div>
      <button onclick="myFunction()">Reload page</button>

      <script>
         function myFunction() {
            location.reload();
         }
      </script>
   </body>
</html>
Contour Plot using Matplotlib - Python - GeeksforGeeks

21 Apr, 2020
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables we want to plot then the response Z will be plotted as slices on the X-Y plane due to which contours are sometimes referred as Z-slices or iso-response.
Contour plots are widely used to visualize density, altitudes or heights of the mountain as well as in the meteorological department. Due to such wide usage matplotlib.pyplot provides a method contour to make it easy for us to draw contour plots.
The matplotlib.pyplot.contour() are usually useful when Z = f(X, Y) i.e Z changes as a function of input X and Y. A contourf() is also available which allows us to draw filled contours.
Syntax: matplotlib.pyplot.contour([X, Y, ] Z, [levels], **kwargs)
Parameters:X, Y: 2-D numpy arrays with same shape as Z or 1-D arrays such that len(X)==M and len(Y)==N (where M and N are rows and columns of Z)Z: The height values over which the contour is drawn. Shape is (M, N)levels: Determines the number and positions of the contour lines / regions.
Returns: QuadContourSet
Below examples illustrate the matplotlib.pyplot.contour() function in matplotlib.pyplot:
Example #1: Plotting of Contour using contour() which only plots contour lines.
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3)  # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y)  fig, ax = plt.subplots(1, 1)  Z = np.cos(X / 2) + np.sin(Y / 4)  # plots contour linesax.contour(X, Y, Z)  ax.set_title('Contour Plot')ax.set_xlabel('feature_x')ax.set_ylabel('feature_y')  plt.show()
Output:
Example #2: Plotting of contour using contourf() which plots filled contours.
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  feature_x = np.linspace(-5.0, 3.0, 70)feature_y = np.linspace(-5.0, 3.0, 70)  # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y)  fig, ax = plt.subplots(1, 1)  Z = X ** 2 + Y ** 2  # plots filled contour plotax.contourf(X, Y, Z)  ax.set_title('Filled Contour Plot')ax.set_xlabel('feature_x')ax.set_ylabel('feature_y')  plt.show()
Output:
Python-matplotlib
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
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
C++ Vector Library - empty() Function

The C++ function std::vector::empty() tests whether vector is empty or not. Vector of size zero is considered as empty vector.
Following is the declaration for std::vector::empty() function form std::vector header.
bool empty() const;

bool empty() const noexcept;

None
Returns true if vector is empty otherwise false.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::empty() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v;

   if (v.empty())
      cout << "Vector v1 is empty" << endl;

   v.push_back(1);
   v.push_back(2);
   v.push_back(3);

   if (!v.empty())
      cout << "Vector v1 is not empty" << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector v1 is empty
Vector v1 is not empty

 Print
 Add Notes
 Bookmark this page