code-rag-bench/online-tutorials huggingface dataset:
Python - Filter Rows Based on Column Values with query function in Pandas?

To filter rows based on column values, we can use the query() function. In the function, set the condition through which you want to filter records. At first, import the required library −
import pandas as pd
Following is our data with Team Records −
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]
Create a DataFrame from above and add columns as well −
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

Use query() to filter records with “Rank” equal to 5 −
dataFrame.query("Rank == 5"))
Following is the complete code −
import pandas as pd

# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]

# Creating a DataFrame and add columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print"DataFrame...\n",dataFrame

# using query to filter rows
print"\nFetch Team with Rank 5..\n",dataFrame.query("Rank == 5")
This will produce the following output −
DataFrame...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50
5    Bangladesh      6       40

Fetch Team with Rank 5..
        Country   Rank   Points
4  South Africa      5       50
Let us see another example. Here, we have a different condition to filter rows −
import pandas as pd

# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]

# Creating a DataFrame and add columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print"DataFrame...\n",dataFrame

# using query to filter rows
print"\nFetch Team with points above 70 and Rank less than 3..\n"
print(dataFrame.query("Points > 70 and Rank <3"))
This will produce the following output −
DataFrame...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50
5    Bangladesh      6       40

Fetch Team with points above 70 and Rank less than 3..

     Country   Rank   Points
0      India      1      100
1  Australia      2       85
JDBC - CallableStatement Object Example

Following is the example, which makes use of the CallableStatement along with the following getEmpName() MySQL stored procedure −
Make sure you have created this stored procedure in your EMP Database. You can use MySQL Query Browser to get it done.
DELIMITER $$

DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName` 
   (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
   SELECT first INTO EMP_FIRST
   FROM Employees
   WHERE ID = EMP_ID;
END $$

DELIMITER ;
This sample code has been written based on the environment and database setup done in the previous chapters.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExample {
   static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "{call getEmpName (?, ?)}";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         CallableStatement stmt = conn.prepareCall(QUERY);
      ) {		      
         // Bind values into the parameters.
         stmt.setInt(1, 102);  // This would set ID
         // Because second parameter is OUT so register it
         stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
         //Use execute method to run stored procedure.
         System.out.println("Executing stored procedure..." );
         stmt.execute();
         //Retrieve employee name with getXXX method
         String empName = stmt.getString(2);
         System.out.println("Emp Name with ID: 102 is " + empName);
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Executing stored procedure...
Emp Name with ID: 102 is Zaid
C:\>


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
HTML - <li>Tag

The HTML <li> tag is used for specifying a list item in ordered, unordered, directory, and menu lists.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML li Tag</title>
   </head>

   <body>
      <ul>
         <li>ol - ordered list</li>
         <li>ul - unordered list</li>
         <li>dir - directory list</li>
         <li>menu - menu list</li>
      </ul>
   </body>

</html>
This will produce the following result −
ol - ordered list
ul - unordered list
dir - directory list
menu - menu list
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <li> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from 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.
Any class can be a parent class, so the syntax is the same as creating any 
other class:
Create a class named Person, with
firstname and lastname properties, 
and a printname method:
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child 
class:
Create a class named Student, which will inherit the properties 
and methods from 
the Person class:
Note: Use the pass 
  keyword when you do not want to add any other properties or methods to the 
  class.
Now the Student class has the same properties and methods as the Person 
class.
Use the Student class to create an object, 
and then execute the printname method:
So far we have created a child class that inherits the properties and methods 
from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Add the __init__() function to the
Student class:
When you add the __init__() function, the child class will no longer inherit 
the parent's __init__() function.
Note: The child's __init__() 
  function overrides the inheritance of the parent's 
  __init__() function.
To keep the inheritance of the parent's __init__() 
function, add a call to the 
parent's __init__() function:
Now we have successfully added the __init__() function, and kept the 
inheritance of the parent class, and we are ready to add functionality in the
__init__() function.
Python also has a super() function that 
will make the child class inherit all the methods and properties from its 
parent:
By using the super() function, you do not 
have to use the name of the parent element, it will automatically inherit the 
methods and properties from its parent.
Add a property called graduationyear to the
Student class:
In the example below, the year 2019 should be a variable, and passed into the 
Student class when creating student objects.
To do so, add another parameter in the __init__() function:
Add a year parameter, and pass the correct 
year when creating objects:
Add a method called welcome to the
Student class:
If you add a method in the child class with the same name as a function in 
the parent class, the inheritance of the parent method will be overridden.
What is the correct syntax to create a class named Student that will inherit properties and methods from a class named Person?
class :

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Unable to locate an element using xpath error in selenium-java

We may encounter the error - unable to locate element while working with Selenium webdriver. This leads to NoSuchElementException. This type of exception is thrown when there is no element on the page which matches with the locator value.
If error is encountered, we can fix it by the following ways −
Check if there is any syntax error in our xpath expression.
Check if there is any syntax error in our xpath expression.
Add additional expected wait conditions for the element.
Add additional expected wait conditions for the element.
Use an alternative xpath expression.
Use an alternative xpath expression.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class XpathError{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
      m.click();
      //explicit wait condition - visibilityOfElementLocated
      w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
      System.out.println("Page title: " + driver.getTitle());
      driver.quit();
   }
}
Creating 3D animation using matplotlib

To create a 3D animation using matplotlib, we can take the following steps −
Import the required packages. For 3D animation, you need to import Axes3D from mpl_toolkits.mplot3d and matplotlib.animation.
Set the figure size and adjust the padding between and around the subplots.
Create t, x, y and data points using numpy.
Create a new figure or activate an existing figure.
Get the instance of 3D axes.
Turn off the axes.
Plot the lines with data.
Create an animation by repeatedly calling a function *animate*.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D

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

def animate(num, data, line):
   colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2',   '#7f7f7f', '#bcbd22', '#17becf']
   line.set_color(colors[num % len(colors)])
   line.set_alpha(0.7)
   line.set_data(data[0:2, :num])
   line.set_3d_properties(data[2, :num])
   return line

t = np.arange(0, 20, 0.2)
x = np.cos(t) - 1
y = 1 / 2 * (np.cos(2 * t) - 1)
data = np.array([x, y, t])
N = len(t)
fig = plt.figure()
ax = Axes3D(fig)
ax.axis('off')

line, = plt.plot(data[0], data[1], data[2], lw=7, c='red')
line_ani = animation.FuncAnimation(fig, animate, frames=N, fargs=(data, line), interval=50, blit=False)

plt.show()
It will produce the following output
C# | Check if a thread belongs to managed thread pool or not - GeeksforGeeks

01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsThreadPoolThread to check if the thread belongs to the managed thread pool or not.
Syntax:
public bool IsThreadPoolThread { get; }
Return Value: This property returns true if the given thread belongs to the managed thread pool. Otherwise, return false. The return type of this property is System.Boolean.
Below programs illustrate the use of IsThreadPoolThread property:
Example 1:
// C# program to illustrate the use // of IsThreadPoolThread  propertyusing System;using System.Threading;  class GFG {      // Main Method    static public void Main()    {        Thread T;          // Get the reference of main Thread        // Using CurrentThread property        T = Thread.CurrentThread;          // Check if the main thread belongs to        // the managed thread pool or not        // Using IsThreadPoolThread  property        Console.WriteLine("Is main thread belongs to Thread"+                      " pool? : {0} ", T.IsThreadPoolThread);    }}
Output:
Is main thread belongs to Thread pool? : False 
Example 2:
// C# program to illustrate the use//  of IsThreadPoolThread  propertyusing System;using System.Threading;  class GFG {      // Main method    public static void Main()    {          // Creating and initializing threads        Thread TR1 = new Thread(new ThreadStart(job));        ThreadPool.QueueUserWorkItem(new WaitCallback(job1));        TR1.Start();    }      // Static methods    public static void job()    {        Console.WriteLine("Is thread 1 belongs to thread pool: {0}",                           Thread.CurrentThread.IsThreadPoolThread);    }      public static void job1(object stateInfo)    {        Console.WriteLine("Is thread 2 belongs to thread pool: {0}",                           Thread.CurrentThread.IsThreadPoolThread);    }}
Output:
Is thread 1 belongs to thread pool: False
Is thread 2 belongs to thread pool: True

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isthreadpoolthread?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
How to Create a Tolerance Chart in Excel?

01 May, 2021
A tolerance chart shows how a particular data item compares to the maximum and minimum permissible values. In this article, we’ll analyze the average results of the students of a class using a tolerance chart.
Tolerance Chart
Follow the below steps to create a Tolerance chart in Excel:
Step 1: The first step is to make your data table. This table must have three main attributes, Minimum, Maximum, and Range. Here, the range is the difference between the Maximum and the Minimum values. You can use this formula and apply it to all corresponding cells. Take a look at the following image for better clarity.
Step 2: Next, select the entire table and click on Insert. 
Note: The menus may look different for different versions of Excel, but the basic principles remain the same.
Step 3: Find Stacked Area Chart under the Charts sub-section, and click on it. You may delete the legend on the right-hand side if you want.
Stacked Area Chart
Step 4: Now, from the table, select all the values from the ‘min’ row. Then click Ctrl + C, to copy. Now, click on the chart and hit Ctrl + V, to paste. This will result in an additional layer being added to the stacked chart as shown below:
Step 5: Now, select the colored charts that correspond to Min (the top-most layer), Max, and Result and make the following conversions. Note – All others remain the same.
Max --> Line Chart
Min --> Line Chart
Result --> Line Chart with Markers
Right-click on the Layer you want to change and click on ‘Change Series Chart Type‘
The following screen will appear where you can select from the available Line Charts on the left.
Select Line from the left pane and choose the corresponding Line Chart mentioned above.
Do, this for all items and the final result would look something like this.
Step 6: Now, select the bottom-most layer, i.e., the min layer, and double-click on it. Then, select No Fill from the Fill section on the left.
Step 7: Next, right-click on the bottom axis and select Format Axis. Navigate to the bottom and select “On tick Marks”.
Your Tolerance Chart is ready!
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Introduction to Excel Spreadsheet
How to make a 3 Axis Graph using Excel?
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to copy a table from one MySQL database to another?

The following is the syntax to copy a table from one database to another.
INSERT INTO yourDestinationDatabaseName.yourTableName SELECT * from yourSourceDatabaseName.yourtableName;

Let us see an example.
The CREATE command is used to create a table in the database ‘business’. We are creating a new table here.
mysql> use business;
Database changed
mysql> create table OriginalTable
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.46 sec)
Creating a new table in the database ‘test’.
mysql> use test;
Database changed
mysql> create table OriginalTable
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.47 sec
Records are inserted with the help of INSERT command in the first table.
mysql> use business;
Database changed
mysql> insert into OriginalTable values(1),(2),(3),(4);
Query OK, 4 rows affected (0.18 sec)
Records: 4  Duplicates: 0  Warnings: 0
To display all the records.
mysql> select *from OriginalTable;
Here is the output.
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)

To copy the above table from database “business” into another database “test”.
mysql>  INSERT INTO test.OriginalTable SELECT * from business.OriginalTable;
Query OK, 4 rows affected (0.20 sec)
Records: 4  Duplicates: 0  Warnings: 0
To check if the table has been copied.
mysql> use test;
Database changed
mysql> select *from OriginalTable;
The following output shows that the table “OriginalTable” have been copied successfully into the second database.
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)
Lodash _.memoize() Method

16 Sep, 2020
The _.memoize() method is used to memorize a given function by caching the result computed by the function. If resolver is issued, the cache key for store the result is determined based on the arguments given to the memoized method. By default, the first argument provided to the memoized function is used as the map cache key.
Syntax:
_.memoize(func, [resolver])

Parameters: This method accepts two parameters as mentioned above and described below:
func: This parameter holds the function to have its output memoized.
resolver: It is the function to resolve the cache key.
Return Value: This method returns the new memoized function.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.  
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Use of _.memoize() method  var sum = _.memoize(function (n) {     return n < 1 ? n : n + sum(n - 1); });   // Sum of first 6 natural number  console.log(sum(6));
Output:
21

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    var object = { 'cpp': 5, 'java': 8 };  // Use of _.memoize() method  var values = _.memoize(_.values);  // value of object console.log(values(object));   // Modify the result cache.values.cache.set(object, ['html', 'css']);console.log(values(object));
Output:
[5, 8]
['html', 'css']

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2010 | Question 65

28 Jun, 2021
If 137 + 276 = 435 how much is 731 + 672?(A) 534(B) 1403(C) 1623(D) 1513Answer: (C)Explanation: If we try adding the numbers directly (i.e. considering decimal)
 
  1 
  137
 +276 
  ---  
    3

Since 7+6=13 and the given answer 435 has 5 in the one’s place therefore the numbers are in base 8; Because 13 will correspond to 15 (7+8) in base 8 system. As shown:
Now converting 731 and 672 in decimal
7×8^2 + 3×8^1 + 1×8^0 = 4736×8^2 + 7×8^1 + 2×8^0 = 442
Adding 473 + 442 = 915
Converting 915 into base 8 = 1623
This explanation has been contributed by Kriti Kushwaha.
More questions at: number-representation
Quiz of this Question
jayanth_mkv
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a session only cookies with JavaScript?

To create a session only cookie, you need to set the expiration date of the cookie to be some years ahead. You need to set the expire attribute −
current time + 5 years
The expire attribute shows the date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Note − Do not consider removing the expire value to create a session only cookie. This won’t work. Set the expire attribute to the future date.
SQL | Difference between functions and stored procedures in PL/SQL

06 Jun, 2022
Prerequisite: 
Procedures in PL/SQL
Functions in PL/SQL.
Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 
1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and returns the result of the function. Example: 
SP ->
create or replace procedure GEEKS(x int) 
is
y int;
begin
.....

UDF->
FUNCTION GEEKS(x int)  
/*return statement so we must return value in function */  
RETURN int             
IS  
  y int;  
BEGIN 
.....
2. SP can have input/output parameters but UDF only has input parameters. Example: 
 SP ->
 CREATE OR REPLACE PROCEDURE Factorial(x IN NUMBER, result OUT NUMBER)
 is
 begin
 ....

UDF ->
FUNCTION Factorial(x IN NUMBER) /* only input parameter */ 
return  NUMBER
is
result NUMBER;
begin
.....
3. We can call UDF from SP but cannot call SP from a function. Example: 
Calling UDF cal() inside SP square() but reverse is not possible.

set serveroutput on;
declare
a int;
c int;

function cal(temp  int)
return int
as 
ans int;
begin
ans:=temp* temp;
return ans;
end;

procedure square(x in int, ans out int) 
is
begin
dbms_output.put_line('calling function in procedure');
ans:= cal(x);
end;

begin
a:=6;
square(a, c);
dbms_output.put_line('the answer is '|| c);
end;

OUTPUT: 
calling function in the procedure
the answer is 36
4. We cannot use SP in SQL statements like SELECT, INSERT, UPDATE, DELETE, MERGE, etc. but we can use them with UDF.
5. SP is not allowed to be used in SELECT statements, but UDF can be used.
6. SP cannot be used anywhere in the WHERE/HAVING/SELECT part of SQL queries, but UDF can be used.
7. The execution plan can be re-used in SP but in UDF it will be compiled every time.
8. We can use try-catch exception handling in SP but we cannot do that in UDF.
9. We can use transactions in SP but it is not possible in UDF.
10. We can consider UDF as an expression but it is not possible in SP.
11. SP cannot be used in the join clause but it is possible in UDF as a resultset.
12. SP can have both table variables and temporary tables but UDF can have only table variables as it does not permit the use of temporary tables.
13. Advantages of using UDF– 
Enables faster execution
Modular Programming
Can reduce network traffic (data)
      Advantages of using SP–
Improved security measures
Client/server traffic is reduced.
Programming abstraction and efficient code reuse
Pre-compiled Execution 
itskawal2000
annieahujaweb2020
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.cumsum()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.cumsum() is used to find the cumulative sum value over any axis. Each cell is populated with the cumulative sum of the values seen so far.
Syntax: DataFrame.cumsum(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cumsum : Series
Example #1: Use cumsum() function to find the cumulative sum of the values along the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                   "D":[5, 4, 2, 8]})  # Print the dataframedf
Output :
Now find the cumulative sum of the values over the index axis
# To find the cumulative sumdf.cumsum(axis = 0)
Output :
 
Example #2: Use cumsum() function to find the cumulative sum of the values seen so far along the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                   "D":[5, 4, 2, 8]})  # To find the cumulative sum along column axisdf.cumsum(axis = 1)
Output :
 
Example #3: Use cumsum() function to find the cumulative sum of the values seen so far along the index axis in a data frame with NaN value present in dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4],                   "B":[None, 2, 4, 3],                   "C":[4, 3, 8, 5],                   "D":[5, 4, 2, None]})  # To find the cumulative sumdf.cumsum(axis = 0, skipna = True)
Output :
The output is a dataframe with cells containing the cumulative sum of the values seen so far along the index axis. Any Nan value in the dataframe is skipped.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How do you use regular expressions in Cucumber?

We can use regular expressions in Cucumber for selecting a collection of
similar statements in the feature file.
feature file
Feature: Exam Syllabus
Scenario Outline: Summer and Winter Exam Schedule
Given Exam time table in summer season
Given Mathematics and Physics Syllabus
Given Exam time table in winter season
The step Definition file has @Given("^Exam time table in ([^\"]*) season$") which maps two Given statements in a Feature file with the help of regular expression.
@Given ("^Exam time table in ([^\"]*) season$")
public void timeTable(String season){
   if (season.equals("winter")){
      System.out.println("The winter syllabus");
   }else{
      System.out.println("The summer syllabus");
   }
}
@Given ("^Mathematics and Physics Syllabus$")
public void syllabusList(){
   System.out.println("Mathematics and Physics syllabus is");
}
Buy chocolates and save N rupees | Practice | GeeksforGeeks

Geek wants to buy chocolates. The shop only has two types of chocolates. One costs 3 rupees and the other costs 7 rupees. Geek has 100 rupees. Is it possible for him to save exactly N rupees after visiting the shop ?

Example 1:
Input: N = 99
Output: 0
Explaination: Geek needs to save 99 rupees. 
That means he can only spend 1 rupee. But 
no chocolate is available for 1 rupee. Therefore 
there is no way for him to save N rupees. 

Eaxmple 2:
Input: N = 97
Output: 1
Explaination: Geek can buy one chocolate 
for 3 rupees and save 97 rupees.

Your Task:
You do not need to read input or print anything. Your task is to complete the function isPossible() which takes N as input parameter and returns 1 if Geek can save N rupees else returns 0.

Expected Time Compexity: O(1)
Expected Auxiliary Space: O(1)

Constraints:
0 ≤ N ≤ 100
+1
shekfider
This comment was deleted.
0
adiraju uttej3 years ago
adiraju uttej
Java solution:-
https://ide.geeksforgeeks.o...
0
Shubham Singh4 years ago
Shubham Singh
gfg needs to do something our time are wasted due to wrong test cases.output gives 0 when i take it as custom input but when i submit it says wrong answerfor input 89.
my code is
#include<iostream>using namespace std;int main() {int test;cin>>test;while(test--){    int n,flag=0;    cin>>n;    int i,j;    for(i=0;i<=100;i=i+7)    {        for(j=0;j<=100;j+=3)        {            if(((100-(i+j)==n)&&(i!=0 || j!=0))            {                cout<<"1"<<endl; flag="1;" break;="" }="" }="" }="" if(flag="=0)" cout<<"0"<<endl;="" }="" return="" 0;="" }="">
0
Raj Sahu4 years ago
Raj Sahu
https://code.hackerearth.co...
this code is giving answer for 90 to be 1, but the g4g ide is not!
can somebody help me with this?
0
Pranav Bharadwaj4 years ago
Pranav Bharadwaj
It is showing correct output for input 1 as 1, should the output be 0?*Sorry wrong question. Ignore
0
sonali dongre4 years ago
sonali dongre
https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... TYzRvvL
why this is showing wrong output for input 89 but while compiling it is giving right output
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Advanced Excel Logical - IFS Function

The IFS function checks whether one or more conditions are met and returns a value that corresponds to the first TRUE condition. This Function was added in Excel 2016.
IFS (logical_test1, value_if_true1, [logical_test2, value_if_true2], [logical_test3, value_if_true3]...) 

As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments.
As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments.
To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met.
To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met.
If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical "You've entered too few arguments for this function" error message.
If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical "You've entered too few arguments for this function" error message.
If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error.
If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error.
If no TRUE conditions are found, IFS returns #N/A! error.
If no TRUE conditions are found, IFS returns #N/A! error.
Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Prevent scientific notation in matplotlib.pyplot

To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.
Pass two lists to draw a line using plot() method.
Pass two lists to draw a line using plot() method.
Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation.
Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation.
To show the figure, use plt.show() method.
To show the figure, use plt.show() method.
from matplotlib import pyplot as plt
plt.plot([1, 2, 3, 4, 5], [11, 12, 13, 14, 15])
plt.ticklabel_format(style='plain')    # to prevent scientific notation.
plt.show()
Create a Cycle Graph using Networkx in Python - GeeksforGeeks

03 Jan, 2021
A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified.
Number of nodes in a Cycle Graph(Cn) are equal to N.
Number of edges in a Cycle Graph(Cn) are equal to N.
Every node is connected to 2 edges hence degree of each node is 2.
It is a Hamiltonian Graph.
It is a Connected Graph.
Even after removal of one edge it remains connected as it is cyclic.
We can simply obtain cycle graph by joining the initial an final node of a path graph.
We will use the networkx module for realizing a Cycle graph. This module in python is used for visualizing and analyzing different kind of graphs for most of which the generators are predefined in this library.
It comes with an inbuilt function networkx.cycle_graph() and can be illustrated using the networkx.draw() method.
draw()-This function is used to draw the required graph using networkx module.
Syntax:
networkx.draw(G, node_size, node_color)
Parameters:
G: It refers to the Cycle graph object it is passed so that draw method knows exactly which graph is to be printed.
node_size: It refers to the size of nodes.
node_color: It refers to color of the nodes.
cycle_graph()- This function is used to create a cycle graph, it gives all the required information for creating one.
Syntax:
networkx.cycle_graph(n)
Parameters:
n: This parameter is used to specify the number of nodes in the cycle graph.
Returns:
This method returns Cn (Cycle graph with n nodes). Therefore it is used to initialize the graph object G.
Import module
Create cycle graph object using cycle_graph() constructor
Use nx.draw() function
Display plot
Program:
Python3
# import required moduleimport networkx  # create objectG = networkx.cycle_graph(8)  # illustrate graphnetworkx.draw(G, node_size=150, node_color='green')
OUTPUT:
Output
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Path in a Directed Acyclic Graph
Best First Search (Informed Search)
Graph Coloring | Set 2 (Greedy Algorithm)
Maximum Bipartite Matching
Graph Coloring | Set 1 (Introduction and Applications)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
C++ Library - <exception>

It is a standard exception class. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type by reference.
Following is the declaration for std::exception.
class exception;
In below example for std::exception.
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
 
std::atomic_flag lock = ATOMIC_FLAG_INIT;
 
void f(int n) {
   for (int cnt = 0; cnt < 100; ++cnt) {
      while (lock.test_and_set(std::memory_order_acquire))
         ;
      std::cout << "Output from thread " << n << '\n';
      lock.clear(std::memory_order_release);
   }
}
 
int main() {
   std::vector<std::thread> v;
   for (int n = 0; n < 10; ++n) {
      v.emplace_back(f, n);
   }
   for (auto& t : v) {
      t.join();
   }
}
 Print
 Add Notes
 Bookmark this page
Basic System Controls with Terminal in Linux - GeeksforGeeks

16 Jul, 2020
Sometimes some of the basic services of the system stop working or starts malfunctioning. And it becomes really difficult to solve the problem through Graphical User Interface so here is the list of Terminal Command to solve the problem and to control the basic services manually.
Installing the required packages
To control the basic system services, install the basic required tools. For Debian based systems use the following command to install the required tools.
sudo apt-get install Bluetooth bluez bluez-tools rfkill
Check whether the Bluetooth device is blocked or not using the following command.
sudo rfkill list
It will display the status of the Bluetooth device.
Unblocking the blocked service
If the service is blocked execute the following command to unblock the services. To unblock Bluetooth enter the following command.
sudo rfkill unblock bluetooth
To unblock wifi enter the following command.
sudo rfkill unblock wifi
Starting Bluetooth service
To start the Bluetooth services enter the following command.
sudo service bluetooth start
Stopping Bluetooth service
To stop the Bluetooth services enter the following command.
sudo service bluetooth stop
Executing the above command will output the following results.
Starting Wi-Fi service
To start wifi services enter the following command.
nmcli radio wifi on
Stopping Wi-Fi service
To stop wifi services enter the following command.
nmcli radio wifi off
Executing the above command will output the following results.
Enter the following command to lock the screen.
gnome-screensaver-command -l
Executing the above command will output the following results.
Shutting down system
To shut down, the system instantly enters the following command.
shutdown 0
Shutting down at specific time
To shut down the system at 13:30 enters the following command.
shutdown -h 13:30
Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results.
Rebooting system
To reboot the system instantly, enter the following command.
shutdown -r now
Rebooting at specific time
To reboot the system at 13:30 enter the following command.
shutdown -r 13:30
Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results.
linux
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
'crontab' in Linux with Examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
ps command in Linux with Examples
Java program to print the factorial of the given number

Factorial of a positive integer n is the product of all values from n to 1. For example, the factorial of 3 is (3 * 2 * 1 = 6). 
1. Take integer variable A
2. Assign a value to the variable
3. From value, A up to 1 multiply each digit and store
4. The final stored value is factorial of A
import java.util.Scanner;
   public class Factorial {
      public static void main(String args[]){
         int i, factorial=1, number;
         System.out.println("Enter the number to which you need to find the factorial:");
         Scanner sc = new Scanner(System.in);
         number = sc.nextInt();

         for(i = 1; i<=number; i++) {
            factorial = factorial * i;
         }
         System.out.println("Factorial of the given number is:: "+factorial);
      }
   }
Enter the number to which you need to find the factorial:
25
Factorial of the given number is:: 2076180480
How to change the permission of a directory using Python?

On a platform with the chmod command available, you could call the chmod command like this:
>>> import subprocess
>>> subprocess.call(['chmod', '-R', '+w', 'my_folder'])
If you want to use the os module, you'll have to recursively write it:
Using os:
import os
def change_permissions_recursive(path, mode):
    for root, dirs, files in os.walk(path, topdown=False):
        for dir in [os.path.join(root,d) for d in dirs]:
            os.chmod(dir, mode)
    for file in [os.path.join(root, f) for f in files]:
            os.chmod(file, mode)
change_permissions_recursive('my_folder', 0o777)
 This will change the permissions of my_folder, all its files and subfolders to 0o777.
Fetch all the ids of MongoDB documents?

To fetch all the ids, simply use find() in MongoDB. Let us create a collection with documents −
> db.demo169.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36975e9e4f06af551997d7")
}
> db.demo169.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697629e4f06af551997d8")
}
> db.demo169.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697679e4f06af551997d9")
}
Display all documents from a collection with the help of find() method −
> db.demo169.find();
This will produce the following output −
{ "_id" : ObjectId("5e36975e9e4f06af551997d7"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e3697629e4f06af551997d8"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e3697679e4f06af551997d9"), "StudentName" : "David" }
Following is the query to get document ids of all the MongoDB documents in a collection −
> var iterator=db.demo169.find({},{"StudentName":0});
Display all documents from a collection with the help of find() method −
> iterator;
This will produce the following output −
{ "_id" : ObjectId("5e36975e9e4f06af551997d7") }
{ "_id" : ObjectId("5e3697629e4f06af551997d8") }
{ "_id" : ObjectId("5e3697679e4f06af551997d9") }
Check if any anagram of a string is palindrome or not in Python

Suppose we have a string s. We have to check whether an anagram of that string is forming a palindrome or not.
So, if the input is like s = "aarcrec", then the output will be True one anagram of this string is "racecar" which is palindrome.
To solve this, we will follow these steps −
freq := a map to store all characters and their frequencies
odd_count := 0
for each f in list of all values of freq, doif f is odd, thenodd_count := odd_count + 1
if f is odd, thenodd_count := odd_count + 1
odd_count := odd_count + 1
if odd_count > 1, thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
 Live Demo
from collections import defaultdict
def solve(s):
   freq = defaultdict(int)
   for char in s:
      freq[char] += 1
   odd_count = 0
   for f in freq.values():
      if f % 2 == 1:
         odd_count += 1
   if odd_count > 1:
      return False
   return True
s = "aarcrec"
print(solve(s))
"aarcrec"
True
Connect to MySQL using PyMySQL in Python - GeeksforGeeks

05 Sep, 2020
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database.
This package contains a pure-Python MySQL client library, based on PEP 249.
Requirements :
MySQL Server – one of the following :
MySQL >= 5.5
MariaDB >= 5.5
Installation :
This module does not come built-in with Python. You have to install it externally. To install this type the below command in the terminal.
pip install PyMySQL

The proper way to get an instance of this class is to call connect() method. This method establishes a connection to the MySQL database and accepts several arguments:
Parameters :
host – Host where the database server is located
user – Username to log in as
password – Password to use.
database – Database to use, None to not use a particular one.
port – MySQL port to use, default is usually OK. (default: 3306)
Example 1: Let’s connect to the MySQL server. 
Python3
import pymysql  def mysqlconnect():    # To connect MySQL database    conn = pymysql.connect(        host='localhost',        user='root',         password = "pass",        db='College',        )          cur = conn.cursor()    cur.execute("select @@version")    output = cur.fetchall()    print(output)          # To close the connection    conn.close()  # Driver Codeif __name__ == "__main__" :    mysqlconnect()
Output :
(('5.7.30-0ubuntu0.18.04.1',),)

Example 2: Let’s try to access a table from the database
Table used:
Python3
import pymysql  def mysqlconnect():    # To connect MySQL database    conn = pymysql.connect(        host='localhost',        user='root',         password = "pass",        db='College',        )          cur = conn.cursor()          # Select query    cur.execute("select * from STUDENT")    output = cur.fetchall()          for i in output:        print(i)          # To close the connection    conn.close()  # Driver Codeif __name__ == "__main__" :    mysqlconnect()
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
builtin command in Linux with examples - GeeksforGeeks

15 May, 2019
builtin command is used to run a shell builtin, passing it arguments(args), and also to get the exit status. The main use of this command is to define a shell function having the same name as the shell builtin by keeping the functionality of the builtin within the function.
Syntax:
builtin [shell-builtin [arg ..]]
Example: Here, we are creating a function to replace the ‘cd’ command. When you will use cd() function it will change the directory to the desktop directly.
builtin –help Command: It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux