code-rag-bench/online-tutorials huggingface dataset:
Difference between Method Overriding and Method Hiding in C#

19 Mar, 2019
Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called Method Overriding.In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
Example:
// C# program to illustrate the // Method overriding conceptusing System;  // Base classclass My_Parent {      // virtual method    public virtual void display()    {        Console.WriteLine("My new parent class.. !");    }}  // Derived classclass My_Child : My_Parent {      // Here display method is overridden    public override void display()    {        Console.WriteLine("My new child class.. !");    }}  class GFG {      // Main Method    public static void Main()    {          My_Parent obj;          // Creating object of the base class        obj = new My_Parent();          // Invoking method of the base class        obj.display();          // Creating object of the derived class        obj = new My_Child();          // Invoking method of derived class        obj.display();    }}
Output:
My new parent class.. !
My new child class.. !

In Method Hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.
Example:
// C# program to illustrate the// concept of method hidingusing System;  // Base Classpublic class My_Parent {      public void show()    {        Console.WriteLine("This is my parent class.");    }}  // Derived Classpublic class My_Child : My_Parent {      // Hide the method of base class    // Using new keyword    public new void show() {          Console.WriteLine("This is my child class.");    }}  public class GFG {      // Main method    static public void Main()    {          // Creating the object of         // the derived class        My_Child obj = new My_Child();          // Access the method of derived class        obj.show();    }}
Output:
This is my child class.
CSharp-Inheritance
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.onscreenclick() function in Python

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to bind fun to a mouse-click event on canvas.
Syntax :
turtle.onscreenclick(fun, btn=1, add=None)

Parameters:
                                                                                                                                       
Below is the implementation of the above method with an example :
Python3
# import packagesimport turtleimport random  # global colorscol = ['red', 'yellow', 'green', 'blue',       'white', 'black', 'orange', 'pink']  # method to call on screen click    def fxn(x, y):    global col    ind = random.randint(0, 7)          # set screen color randomly    sc.bgcolor(col[ind])  # set screensc = turtle.Screen()sc.setup(400, 300)  # call method on screen clickturtle.onscreenclick(fxn)
Output :
Here we can find that whenever the user clicks (yellow-colored dot on  arrow) on screen it changes the background color of the turtle graphics window randomly.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Filter float strings from String list

29 Nov, 2019
Sometimes, while working with Python list, we can have a problem in which we need to separate the float values from valid strings. But problem arises when float values are in form of strings. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + Exception HandlingThe combination of above functionalities can be used to perform this task. In this, we loop through each element and try to convert each string into float value, if it’s a success, means it’s a float, else it raises a ValueError and we can get desired string.
# Python3 code to demonstrate working of# Filter float strings from String list# using loop + Exception Handling  # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']  # printing original list print("The original list : " + str(test_list))  # Filter float strings from String list# using loop + Exception Handlingres = []for ele in test_list:    try:        float(ele)    except ValueError:        res.append(ele)  # printing resultprint("String list after filtering floats : " + str(res))
The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

 
Method #2 : Using regex + list comprehensionThe combination of above functionalities can perform this task. In this, we perform the task of filtering using regex created and list comprehension is used to iterate over the list and apply the filter.
# Python3 code to demonstrate working of# Filter float strings from String list# using regex + list comprehensionimport re  # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']  # printing original list print("The original list : " + str(test_list))  # Filter float strings from String list# using regex + list comprehensiontemp = re.compile(r'\d+(?:\.\d*)')res = [ele for ele in test_list if not temp.match(ele)]  # printing resultprint("String list after filtering floats : " + str(res))
The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
id() function in Python

25 Nov, 2017
Introductionid() is an inbuilt function in Python.Syntax:
id(object)
As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are actually the memory address, here in Python it is the unique id. This function is generally used internally in Python.
Examples:
The output is the identity of the 
object passed. This is random but 
when running in the same program, 
it generates unique and same identity. 

Input : id(1025)
Output : 140365829447504
Output varies with different runs

Input : id("geek")
Output : 139793848214784

# This program shows various identitiesstr1 = "geek"print(id(str1))  str2 = "geek"print(id(str2))  # This will return Trueprint(id(str1) == id(str2))  # Use in Listslist1 = ["aakash", "priya", "abdul"]print(id(list1[0]))print(id(list1[2]))  # This returns falseprint(id(list1[0])==id(list1[2]))
Output:
140252505691448
140252505691448
True
140252505691840
140252505739928
False

Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java - String concat() Method

This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
Here is the syntax of this method −
public String concat(String s)

Here is the detail of parameters −
s − the String that is concatenated to the end of this String.
s − the String that is concatenated to the end of this String.
This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
public class Test {

   public static void main(String args[]) {
      String s = "Strings are immutable";
      s = s.concat(" all the time");
      System.out.println(s);
   }
}
This will produce the following result −
Strings are immutable all the time
Python – os.pardir() method with example

18 May, 2020
In Python, OS module provides various functions to interact with the operating system. This module comes under the Python standard utility module, so there is no need to install it manually.
os.pardir is a constant string used by the operating system to refer to the parent directory. This method is also available via os.path.pardir()
Note: os.pardir is ‘.. for UNIX based OS and ‘::‘ for Mac OS.
Syntax: os.pardir
Return type: a string that refers to the parent directory.
# Python program to demonstrate# os.pardir  import os  # prints .. by defaultprint(os.pardir)
Output:
..

 Example 2: Let’s print the parent of current working directory.
# Python program to demonstrate# os.pardir    import os    # current working directorypath = os.getcwd()print("Current Directory:", path)  # parent directoryparent = os.path.join(path, os.pardir)  # prints parent directoryprint("\nParent Directory:", os.path.abspath(parent))
Output:
Current Directory: /home/geeks/Desktop/gfg

Parent Directory: /home/geeks/Desktop

 Example 3: Getting the parent of specified path.
# Python program to demonstrate# os.pardir    import os    # pathpath = "your/path/for/parent/directory"print("Path:", path)  # parentparent = os.path.join(path, os.pardir)  # prints the relative file path # for the current directory (parent)print("\nParent:", os.path.relpath(parent))
Output:
Path: your/path/for/parent/directory

Parent: your/path/for/parent

nishkarsh146
Python directory-program
python-os-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
plotly.express.line_3d() function in Python

17 Jul, 2020
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use.
This function is used to create a 3D line plot and can be used with pandas dataframes. Each row of dataframe is represented by a symbol mark in 3D space in the line plot.
Syntax: plotly.express.line_3d(data_frame=None, x=None, y=None, z=None, color=None, line_dash=None, text=None, line_group=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame: DataFrame or array-like or dict needs to be passed for column names.
x, y, z: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis in cartesian coordinates respectively.
color: This parameters assign color to marks.
line_dash: This parameter is used to assign dash-patterns to lines.
line_group: This parameter is used to group rows of data_frame into lines.
hover_name:  Values from this column or array_like appear in bold in the hover tooltip.
hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip.
Example 1:
Python3
import plotly.express as px  df = px.data.tips()  plot = px.line_3d(df, x = 'time',                      y = 'day',                     z = 'sex')plot.show()
Output:
Example 2:
Python3
import plotly.express as px  df = px.data.tips()  plot = px.line_3d(df, x = 'time',                   y = 'day',                  z = 'sex',                  color = 'time')plot.show()
Output:
Example 3:
Python3
# Python program to demonstrate scatter# plot  import plotly.express as px  df = px.data.tips()  plot = px.line_3d(df, x = 'day',                      y = 'total_bill',                      z = 'sex',                      color = 'time',                     line_group = 'sex')plot.show()
Output:
Python Plotly express-class
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check that a string is parse-able to a double in java?

The parseDouble() method of the java.lang.Double class accepts a String value, parses it, and returns the double value of the given String.
If you pass a null value to this method, it throws a NullPointerException and if this method is not able to parse the given string into a double value you, it throws a NumberFormatException.
Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.
 Live Demo
import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = Double.parseDouble(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}
Enter a string value:
2245g
Given String is not parsable to double
Similarly, the valueOf() method of the Double class (also) accepts a String value as a parameter, trims the excess spaces and returns the double value represented by the string. If the value given is not parsable to double this method throws a NumberFormatException.
 Live Demo
import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = Double.valueOf(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}
Enter a string value:
2245g
Given String is not parsable to double
One of the constructor of the Double class accepts a String as a parameter and constructs an (Double) object that wraps the given value. If the string passed to this constructor is not parsable to Double a NumberFormatException will be thrown.
 Live Demo
import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = new Double(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}
Enter a string value:
2245g
Given String is not parsable to double
Compare two arrays and get those values that did not match JavaScript

We have two arrays of literals that contain some common values, our job is to write a function
that returns an array with all those elements from both arrays that are not common.
For example −
// if the two arrays are:
const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
// then the output should be:
const output = ['cat', 'zebra', 'tiger']
// because these three are the only elements that are not common to both
arrays
Let’s write the code for this −
We will spread the two arrays and filter the resulting array to obtain an array that contains no
common elements like this −
const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
const removeCommon = (first, second) => {
   const spreaded = [...first, ...second];
   return spreaded.filter(el => {
      return !(first.includes(el) && second.includes(el));
   })
};
console.log(removeCommon(first, second));
The output in the console will be −
[ 'cat', 'zebra', 'tiger' ]
Remove Axis Labels using ggplot2 in R - GeeksforGeeks

06 Jun, 2021

In this article, we are going to see how to remove axis labels of the ggplot2 plot in the R programming language.
We will use theme() function from ggplot2 package. In this approach to remove the ggplot2 plot labels, the user first has to import and load the ggplot2 package in the R console, which is a prerequisite for this approach, then the user has to call the theme() function which is the function of the ggplot2 package and further needs to pass the element_blank() as its parameters, which will be helping to remove the ggplot2 plots labels as blank in R programming language.
theme() function: Use of this function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look.
In this example, we will be showing that how the plot looks without removing its labels.
R
 

 
 










library("ggplot2")    
gfg_data <- data.frame(x = c(1,2,3,4,5), 
                       y = c(5,4,3,2,1)) 
gfg_plot <- ggplot(gfg_data, aes(x,y)) +   
  geom_point() 
gfg_plot






Output:
Example 1: In this example, we will be removing the label of the ggplot2  scatter plot of five data point using the theme() function of the ggplot2 package in the R programming language.
R
 

 
 










library("ggplot2")    
gfg_data<-data.frame(x = c(1,2,3,4,5), 
                     y = c(5,4,3,2,1)) 
gfg_plot <- ggplot(gfg_data, aes(x,y)) +   
  geom_point() 
gfg_plot + 
  theme(axis.text.x = element_blank(), 
        axis.ticks.x = element_blank(), 
        axis.text.y = element_blank(), 
        axis.ticks.y = element_blank())






Output:
Example 2: In this example, we will be removing the labels of the ggplot2 bar plot using the theme() function from the ggplot2 package in the R programming language.
R
 

 
 










library("ggplot2")    
gfg_data<-data.frame(x = c(1,2,3,4,5), 
                     y = c(5,4,3,2,1)) 
p<-ggplot(data=gfg_data, aes(x, y)) + 
  geom_bar(stat="identity") 
p+ 
  theme(axis.text.x = element_blank(), 
        axis.ticks.x = element_blank(), 
        axis.text.y = element_blank(), 
        axis.ticks.y = element_blank()) 






Output:

Picked


R-ggplot


R Language

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
LocalDateTime getHour() method in Java with Examples - GeeksforGeeks

29 Nov, 2018
The getHour() method of an LocalDateTime class is used to return the hour-of-day field. This method returns an integer value ranging from 0 to 23, i.e. the Hours of a day.
Syntax:
public int getHour()

Parameter: This method does not accept any parameter.
Returns: This method returns an integer value which represents the hour-of-day and it ranges from 0 to 23.
Below programs illustrate the LocalDateTime.getHour() method:
Program 1:
// Java program to demonstrate// LocalDateTime.getHour() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDateTime Object        LocalDateTime local            = LocalDateTime.parse("2018-12-03T12:39:10");          // get HourOfDay        int hourOfDay = local.getHour();          // print result        System.out.println("HourOfDay: "                           + hourOfDay);    }}
HourOfDay: 12

Program 2:
// Java program to demonstrate// LocalDateTime.getHour() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDateTime Object        LocalDateTime local            = LocalDateTime.parse("2019-01-28T22:29:10");          // get HourOfDay        int hourOfDay = local.getHour();          // print result        System.out.println("HourOfDay: "                           + hourOfDay);    }}
HourOfDay: 22

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/LocalDateTime.html#getHour–
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Overriding in Java
Singleton Class in Java
Collections in Java
Multithreading in Java
Program to check if a matrix is symmetric in C++

In linear algebra a matrix M[][] is said to be a symmetric matrix if and only if transpose of the matrix is equal to the matrix itself. A transpose of a matrix is when we flip the matrix over its diagonal, which resultant switches its row and columns indices of the matrix.
Below the example of Symmetric matrix −
[147456769]⇒[147456769]
The above matrix is the symmetric matrix we took the matrix on the left and transpose it and the result is same is equal to the matrix itself.
Input: arr1[][n] = { { 1, 2, 3 },
   { 2, 2, 4 },
   { 3, 4, 1 } };
Output: its a symmetric matrix
Input: arr1[][n] = { { 1, 7, 3 },
   { 2, 9, 5 },
   { 4, 6, 8 } };
Output: its not a symmetric matrix 
We can just follow these steps −
1. Take a matrix and store its transpose in other matrix.
2. Check the resultant matrix is same as the input matrix.
Start
Step 1 -> define macro as #define n 10
Step 2 -> declare function to find transporse of a matrix
   void transpose(int arr1[][n], int arr2[][n], int a)
      Loop For int i = 0 and i < a and i++
         Loop For int j = 0 and j < a and j++
            Set arr2[i][j] = arr1[j][i]
         End
   End
Step 3 -> declare function to check symmetric or not
   bool check(int arr1[][n], int a)
   declare variable as int arr2[a][n]
   Call transpose(arr1, arr2, a)
   Loop For int i = 0 and i < a and i++
      Loop For int j = 0 and j < a and j++
         IF (arr1[i][j] != arr2[i][j])
            return false
         End
      End
   End
   Return true
Step 4 -> In main()
   Declare variable as int arr1[][n] = { { 1, 2, 3 },
      { 2, 2, 4 },
      { 3, 4, 1 } }
   IF (check(arr1, 3))
      Print its a symmetric matrix
   Else
      Print its not a symmetric matrix
Stop
#include <iostream>
#define n 10
using namespace std;
//find transporse of a matrix
void transpose(int arr1[][n], int arr2[][n], int a){
   for (int i = 0; i < a; i++)
      for (int j = 0; j < a; j++)
         arr2[i][j] = arr1[j][i];
}
//check symmetric or not
bool check(int arr1[][n], int a){
   int arr2[a][n];
   transpose(arr1, arr2, a);
   for (int i = 0; i < a; i++)
      for (int j = 0; j < a; j++)
         if (arr1[i][j] != arr2[i][j])
            return false;
   return true;
}
int main(){
   int arr1[][n] = { { 1, 2, 3 },
      { 2, 2, 4 },
      { 3, 4, 1 } };
   if (check(arr1, 3))
      cout << "its a symmetric matrix";
   else
      cout << "its not a symmetric matrix";
   return 0;
}
its a symmetric matrix
Foundation - Vertical Dropdown Menus

The menu can be displayed vertically by including the class .vertical to the top level menu. The sub menus are automatically aligned vertically.
The following example demonstrates the use of Vertical dropdown menu in Foundation −
<!DOCTYPE html>
<html>
   <head>
      <title>Foundation Template</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">

      <!-- Compressed CSS -->
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">

      <!-- Compressed JavaScript -->
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
   </head>

   <body>
      <h2>Example of Dropdown menu</h2>
      <ul class = "vertical dropdown menu" data-dropdown-menu>
         <li><a href = "#">Home</a>
            <ul class = "menu">
               <li><a href = "#">Home 1</a></li>
               <li><a href = "#">Home 2</a>
                  <ul class = "menu">
                     <li><a href = "#">Home2 1</a></li>
                     <li><a href = "#">Home2 2</a></li>
                  </ul>
               </li>
            </ul>
         </li>
         <li><a href = "#">About</a></li>
         <li><a href = "#">Service</a></li>
         <li><a href = "#">Contact</a></li>
      </ul>

      <script>
         $(document).ready(function() {
            $(document).foundation();
         })
      </script>
   </body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code dropdown_vertical.html file.
Save the above given html code dropdown_vertical.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
Home

Home 1
Home 2

Home2 1
Home2 2




Home 1
Home 2

Home2 1
Home2 2


Home2 1
Home2 2
About
Service
Contact

    117 Lectures 
     5.5 hours 

 Shakthi Swaroop

    61 Lectures 
     1.5 hours 

 Hans Weemaes

    17 Lectures 
     4 hours 

 Stephen Kahuria

    8 Lectures 
     50 mins

 Zenva

    28 Lectures 
     2 hours 

 Sandra L

    16 Lectures 
     2.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
Python | Pandas Series.shift()

30 Oct, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.shift() function shift index by desired number of periods with an optional time freq. When freq is not passed, shift the index without realigning the data.
Syntax: Series.shift(periods=1, freq=None, axis=0, fill_value=None)
Parameter :periods : Number of periods to shift. Can be positive or negative.freq : Offset to use from the tseries module or time rule (e.g. ‘EOM’)axis : Shift direction.fill_value : The scalar value to use for newly introduced missing values
Returns : Copy of input object, shifted.
Example #1: Use Series.shift() function to shift the data of the given Series object by 2 periods.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.shift() function to shift the data in the given series object by 2 periods.
# shift by 2 periodssr.shift(periods = 2)
Output :
As we can see in the output, the Series.shift() function has successfully shifted the data over the index. Notice the data corresponding to the last two indexes has been dropped.
Example #2: Use Series.shift() function to shift the data of the given Series object by -2 periods.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.shift() function to shift the data in the given series object by -2 periods.
# shift by -2 periodssr.shift(periods = -2)
Output :
As we can see in the output, the Series.shift() function has successfully shifted the data over the index. Notice the data of the first two indexes has been dropped.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Solve the Linear Equation of Multiple Variable

01 Oct, 2020
Prerequisite: Sympy.solve()
In this article, we will discuss how to solve a linear equation having more than one variable. For example, suppose we have two variables in the equations. Equations are as follows:
x+y =1
x-y =1
When we solve this equation we get x=1, y=0 as one of the solutions. In Python, we use Eq() method to create an equation from the expression.  
Syntax : Eq(expression,RHS value)
For example, if we have expression as x+y = 1. It can be written as Eq(x+y,1)
Construct the equations using Eq() method. To solve the equations pass them as a parameter to the solve() function.
Example : 
Python3
# importing library sympyfrom sympy import symbols, Eq, solve  # defining symbols used in equations# or unknown variablesx, y = symbols('x,y')  # defining equationseq1 = Eq((x+y), 1)print("Equation 1:")print(eq1)eq2 = Eq((x-y), 1)print("Equation 2")print(eq2)  # solving the equationprint("Values of 2 unknown variable are as follows:")  print(solve((eq1, eq2), (x, y)))
Output:
Equation 1:
Eq(x + y, 1)
Equation 2
Eq(x - y, 1)
Values of 2 unknown variable are as follows:
{x: 1, y: 0} 

Construct the following equations using Eq() and solve then to find the unknown variables.
x +y+z =1
x+y+2z=1
Example:  
Python3
# importing library sympyfrom sympy import symbols, Eq, solve  # defining symbols used in equations# or unknown variablesx, y, z = symbols('x,y,z')  # defining equationseq1 = Eq((x+y+z), 1)print("Equation 1:")print(eq1)  eq2 = Eq((x-y+2*z), 1)print("Equation 2")print(eq2)  eq3 = Eq((2*x-y+2*z), 1)print("Equation 3")  # solving the equation and printing the # value of unknown variablesprint("Values of 3 unknown variable are as follows:")print(solve((eq1, eq2, eq3), (x, y, z)))
Output:
Equation 1:
Eq(x + y + z, 1)
Equation 2
Eq(x - y + 2*z, 1)
Equation 3
Values of 3 unknown variable are as follows:
{x: 0, y: 1/3, z: 2/3}
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Convert nested Python dictionary to object

25 Aug, 2020
Let us see how to convert a given nested dictionary into an object
Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method.
# importing the moduleimport json   # declaringa a classclass obj:          # constructor    def __init__(self, dict1):        self.__dict__.update(dict1)   def dict2obj(dict1):          # using json.loads method and passing json.dumps    # method and custom object hook as arguments    return json.loads(json.dumps(dict1), object_hook=obj)     # initializing the dictionary  dictionary = {'A': 1, 'B': {'C': 2},              'D': ['E', {'F': 3}],'G':4}   # calling the function dict2obj and# passing the dictionary as argumentobj1 = dict2obj(dictionary)   # accessing the dictionary as an objectprint (obj1.A)print(obj1.B.C)print(obj1.D[0])print(obj1.D[1].F)print(obj1.G)
1
2
E
3
4

Method 2 : Using the isinstance() method
. We can solve this particular problem by using the isinstance() method which is used to check whether an object is an instance of a particular class or not.
def dict2obj(d):          # checking whether object d is a    # instance of class list    if isinstance(d, list):           d = [dict2obj(x) for x in d]       # if d is not a instance of dict then    # directly object is returned    if not isinstance(d, dict):           return d       # declaring a class    class C:        pass       # constructor of the class passed to obj    obj = C()       for k in d:        obj.__dict__[k] = dict2obj(d[k])       return obj  # initializing the dictionary  dictionary = {'A': 1, 'B': {'C': 2},              'D': ['E', {'F': 3}],'G':4}  # calling the function dict2obj and# passing the dictionary as argument obj2 = dict2obj(dictionary)  # accessing the dictionary as an object print(obj2.A)print(obj2.B.C)print(obj2.D[0])print(obj2.D[1].F)print(obj2.G)
1
2
E
3
4

Akanksha_Rai
python-dict
Python
python-dict
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
Introduction To PYTHON
Python OOPs Concepts
Python | os.path.join() method
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 | Consecutive Maximum Occurrence in list

27 Aug, 2019
Sometimes, while working with Python lists or in competitive programming setup, we can come across a subproblem in which we need to get an element which has the maximum consecutive occurrence. The knowledge of solution of it can be of great help and can be employed whenever required. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using groupby() + max() + lambdaThis task can be solved using combination of above functions. In this, we group each occurrence of numbers using groupby() and get the max of it using max(). The lambda function provide utility logic to perform this task.
# Python3 code to demonstrate working of# Consecutive Maximum Occurrence in list# using groupby() + max() + lambdafrom itertools import groupby  # initializing listtest_list = [1, 1, 1, 2, 2, 4, 2, 2, 5, 5, 5, 5]  # printing original listprint("The original list is : " + str(test_list))  # Consecutive Maximum Occurrence in list# using groupby() + max() + lambdatemp = groupby(test_list)res = max(temp, key = lambda sub: len(list(sub[1])))  # printing result print("Maximum Consecutive Occurring number is : " + str(res[0]))
The original list is : [1, 1, 1, 2, 2, 4, 2, 2, 5, 5, 5, 5]
Maximum Consecutive Occurring number is : 5

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python – API.add_list_members() in Tweepy

10 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The add_list_members() method of the API class in Tweepy module is used to add multiple members to a specified list.
Syntax : API.add_list_members(parameters)
Parameters :
list_id : ID of the list.
slug : slug of the list.
user_id : ID of the user to be added to the list.
screen_name : screen name of the user to be added to the list.
owner_id : ID of the owner of the list.
owner_screen_name : screen name of the owner of the list.
Returns : an object of class List
Example 1 : Adding a single member to the list using the add_list_members() method.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the listlist_id =   # screen name of the user to be addedscreen_name = "geeksforgeeks"  print("Number of members before add_list_member() is used : " +      str(api.get_list(list_id = list_id).member_count))  # adding the user to the listapi.add_list_members(list_id = list_id, screen_name = screen_name)  print("Number of members after add_list_member() is used : " +      str(api.get_list(list_id = list_id).member_count))
Output :
Number of members after add_list_members() is used : 0
Number of members after add_list_members() is used : 1

Example 2 : Adding multiple members to the list using the add_list_members() method.
# the ID of the non-existent listlist_id =   # add the following users to the listusers = ["geeksforgeeks", "PracticeGfG",         "GeeksQuiz", "hackerrank"]  print("Number of members before add_list_member() is used : " +      str(api.get_list(list_id = list_id).member_count))  # adding the users to the listapi.add_list_members(list_id = list_id, screen_name = users)  print("Number of members after add_list_member() is used : " +      str(api.get_list(list_id = list_id).member_count))
Output :
Number of members before add_list_members() is used : 0
Number of members after add_list_members() is used : 4

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | onkeypress Attribute

12 Aug, 2021
This attribute fires when a user presses a key on the Keyboard. This event attribute can not be used for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers.Supported Tags: All HTML elements, EXCEPT:
<base>
<bdo>
<br>
<head>
<html>
<iframe>
<meta>
<param>
<script>
<style>
<title>
Syntax:  
<element onkeypress="script">
Attribute: The onkeydown attribute works for all keys in all browsers. The script will be run when onkeypress attribute call.Note: The order of events that is related to the onkeypress events:  
onkeydown
onkeypress
onkeyup
Example:  
html
<!DOCTYPE html><html>    <head>        <title>onkeypress attribute</title>        <style>            body {                text-align:center;            }               h1 {                color:green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>onkeypress attribute</h2>        <input type="text" onkeypress="GeeksForGeeks()">        <script>            function GeeksForGeeks() {                alert("Welcome to GeeksForGeeks!");            }        </script>    </body></html>                   
Output: Before click in the text box:  
After click on the text box:  
Supported Browsers: The browser supported by onkeypress event attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Apple Safari
 
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
cmd | Rem command

16 Oct, 2020
Rem (abbreviation of remark) is a command (internal) found inside the Windows Command Processor Command Prompt, that allows for inclusion of comments inside batch programs. Comments are supported by most Programming languages usually via special syntax that is associated to them. Ex. Python using pound sign/hashtag ( # ) to denote a inline comment. Rem command is for inline comments, therefore the comment would only be valid till the end of the current line (or first occurrence of CRLF) Though multiline comments can be created using multiple Rem command on separate lines. In this article we will take a look at the Rem command, and would get to know about various uses for it.
Description of the Command :
Records comments (remarks) in a batch file or CONFIG.SYS.

REM [comment] 
*The above output can be obtained by executing rem /? command in the commandline
Using the Command :Comments are generally used to add more intel to the code. It helps in providing an insight to what the creator of the code, was thinking while writing it. It is also useful for providing some pointers or addendum related to the code. Comments overall help in reducing the complexity of the code, by being a sort of human-readable form of code. They also help to guide readers, who are unaware of the language. For Example, let’s take a look at the following code snippet:
@echo off

echo %~f0
echo %~t0


To someone who has never seen the aforementioned syntax, the code may be quite cryptic at first. But if comments are added to the code:
REM Used to disable echo of command entry and current working directory
@echo off

REM Displaying the full path (absolute Path) of the this file
echo %~f0

REM Displaying the timestamp of creation of this file
echo %~t0


The code becomes clear on its functionality, and one can easily guide through its workings.
Creating Inline Comments :Inline comments can be created by using the REM command at the beginning of the line and then typing in the comment.
For example,
REM This code will display hello world
echo hello world!

Inline comments could also be added to the end of the line (preceded by some code) by using the & REM construct.
For example,
echo Hello World! & REM This code will display hello world

Creating Multiline Comments :Multiline comments can be created by using multiple rem commands, that span several lines.
For example,
REM This code will tell the current time
REM The resolution of the time will be until milliseconds
REM The time will be based on the current timezone
echo | time

Note –Comment creation exists through various other means as well. Ex. There exists other types of ~comments which allows for comments in between a statement. But they are not the documented way of commenting code, and exists due to workaround of other commands/syntaxes. Also, those are outside the scope of this article.
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unsigned specifier (%u) in C with Examples

10 Dec, 2021
Pre-requisite: Format specifiers in C
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, %u, etc.This article focuses on discussing the format specifier %u. 
Introduction
This unsigned Integer format specifier. This is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in memory. An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables.
Syntax:
printf(“%u”, variable_name);
or
printf(“%u”, value);
Below is the C program to implement the format specifier %u:
C
// C program to implement// the format specifier#include <stdio.h>  // Driver codeint main(){    // Print value 20 using %u    printf("%u\n", 20);    return 0;}
Output:
20
Explanation:
The positive integer value can be easily printed using “%u” format specifier.
Case 1: Print char value using %u
Below is the C program to demonstrate the concept:
C
// C program to demonstrate// the concept#include <stdio.h>  // Driver codeint main(){    // ASCII value of a character    // is = 97    char c = 'a';      // Printing the variable c value    printf("%u", c);    return 0;}
Output:
97
Explanation:
In the above program, variable c is assigned the character ‘a’. In the printf statement when %u is used to print the value of the char c, then the ASCII value of ‘a’ is printed.
Case 2: Print float value using %u
C
// C program to demonstrate// the concept#include <stdio.h>  // Driver codeint main(){    float f = 2.35;      // Printing the variable f value    printf("%u", f);    return 0;}
Output:
prog.c: In function ‘main’:prog.c:11:10: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘double’ [-Wformat=]printf(“%u”, f);         ^
Case 3: Print negative integer value using %u
C
// C program to demonstrate// the above concept#include <stdio.h>  // Driver codeint main(){    // The -20 value is converted    // into it's positive equivalent    // by %u    printf("%u", -20);}
Output:
4294967276
C Programs
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Comments

Comments can be used to explain C# code, and to make it more readable. It can also be used to 
prevent execution when testing alternative code.
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line 
is ignored by C# (will not be executed).
This example uses a single-line comment before a line of code:
// This is a comment
Console.WriteLine("Hello World!");


Try it Yourself »

This example uses a single-line comment at the end of a line of code:
Console.WriteLine("Hello World!");  // This is a comment


Try it Yourself »

Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by C#.
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
Console.WriteLine("Hello World!"); 


Try it Yourself »

It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.
Insert the missing parts to create two types of comments.
 This is a single-line comment
 This is a multi-line comment 

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.