code-rag-bench/online-tutorials huggingface dataset:
Multiple Statements in Python

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −
import sys; x = 'foo'; sys.stdout.write(x + '\n')
A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −
if expression :
   suite
elif expression :
   suite
else :
   suite
How to compare two lists in Python?

The list in python is a collection of similar items. We may at times need to compare data items in the two lists to perform certain operations. We will discuss certain methods to compare two lists in python.
The list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list. This means that the list [1,2,3] will be equal to the list [2,1,3] according to this method of comparison.
 Live Demo
def compareList(l1,l2):
   l1.sort()
   l2.sort()
   if(l1==l2):
      return "Equal"
   else:
      return "Non equal"
l1=[1,2,3]
l2=[2,1,3]
print("First comparison",compareList(l1,l2))
l3=[1,2,3]
l4=[1,2,4]
print("Second comparison",compareList(l3,l4))
First comparison Equal
Second comparison Non equal
This method tests for the equality of the lists by comparing frequency of each element in first list with the second list. This method also does not take into account the order of the elements of the list.
 Live Demo
import collections
def compareList(l1,l2):
   if(collections.Counter(l1)==collections.Counter(l2)):
      return "Equal"
   else:
      return "Non equal"
l1=[1,2,3]
l2=[2,1,3]
print("First comparison",compareList(l1,l2))
l3=[1,2,3]
l4=[1,2,4]
print("Second comparison",compareList(l3,l4))
First comparison Non equal
Second comparison Equal
This method first compares each element of the two lists and store those as summation of 1, which is then compared with the length of the other list. For this method, we have to first check if the lengths of both the lists are equal before performing this computation.
This method also checks for the order of the elements. This means that the list [1,2,3] is not equal to the list [2,1,3].
 Live Demo
def compareList(l1,l2):
   if(len(l1)==len(l2) and len(l1)==sum([1 for i,j in zip(l1,l2) if i==j])):
      return "Equal"
   else:
      return "Non equal"
l1=[1,2,3]
l2=[2,1,3]
print("First comparison",compareList(l1,l2))
l3=[1,2,3]
l4=[1,2,3]
print("Second comparison",compareList(l3,l4))
First comparison Non equal
Second comparison Equal
As in the above example, for the first comparison, the data items in both the lists are equal but the order of the elements is different. Therefore, the first comparison returns not equal.
This is a modification of the first method. In this method, the lists are compared without sorting and thus, this method takes into account the order of the data items in the lists.
 Live Demo
def compareList(l1,l2):
   if(l1==l2):
      return "Equal"
   else:
      return "Non equal"
l1=[1,2,3]
l2=[2,1,3]
print("First comparison",compareList(l1,l2))
l3=[1,2,3]
l4=[1,2,3]
print("Second comparison",compareList(l3,l4))
First comparison Non equal
Second comparison Equal
These are some of the methods to compare lists in python, both taking into account the order of the data items as well as without taking into account the order of data items.
How to get the child element of a parent using JavaScript?

Following is the code for getting the child element of a parent using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .child1,
   .child2,
   .child3 {
      display: none;
      margin: 10px;
      width: 70px;
      height: 70px;
   }
   .child1 {
      background-color: red;
   }
   .child2 {
      background-color: pink;
   }
   .child3 {
      background-color: blue;
   }
</style>
</head>
<body>
<h1>Get the child element of a parent using JavaScript</h1>
<div class="parent1">
<div class="child1">Child 1</div>
<div class="child2">Child 2</div>
<div class="child3">Child 3</div>
</div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the parent1 child elements</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let parentEle = document.querySelector(".parent1");
   BtnEle.addEventListener("click", (event) => {
      Array.from(parentEle.children).forEach((item) => {
         item.style.display = "inline-block";
      });
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Hierarchical data in Pandas - GeeksforGeeks

11 Dec, 2020
In pandas, we can arrange data within the data frame from the existing data frame. For example, we are having the same name with different features, instead of writing the name all time, we can write only once. We can create hierarchical data from the existing data frame using pandas.
Example:
See the student subject details. Here we can see name of student is always repeating.
With this, we need memory to store multiple name. We can reduce this by using data hierarchy.
Example:
Python3
# import pandas  module for data frameimport pandas as pd  # Create dataframe for student data in different collegessubjectsdata = {'Name': ['sravan', 'sravan', 'sravan', 'sravan',                          'sravan', 'sravan', 'sravan', 'sravan',                          'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi',                          'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi',                         'Rohith', 'Rohith', 'Rohith', 'Rohith',                         'Rohith', 'Rohith', 'Rohith', 'Rohith'],                                  'college': ['VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU',                            'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU',                            'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT',                            'VIT', 'VIT', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu',                             'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu',                            'IIT-Bhu'],                                  'subject': ['java', 'dbms', 'dms', 'coa', 'python', 'dld',                            'android', 'iot', 'java', 'dbms', 'dms', 'coa',                            'python', 'dld', 'android', 'iot', 'java',                            'dbms', 'dms', 'coa', 'python', 'dld', 'android',                            'iot']                }  # Convert into data framedf = pd.DataFrame(subjectsdata)  # print the data(student records)print(df)
Output:
Python3
# Set the hierarchical indexdf = df.set_index(['Name', 'college'], drop=False)  # print data framedf
Output:
The next step is to remove the name.
Python3
# setting indexdf = df.set_index(['Name', 'college'])  # print data framedf
Output:
Now get college as the index using swap level.
Python3
# Swap the levels in the indexdf.swaplevel('Name', 'college')
Output:
Now give a summary of the results
Python3
# Summarize the results by collegedf.sum(level='college')
Output:
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
jQuery | Keydown() with Examples - GeeksforGeeks

13 Feb, 2019
The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.Syntax:
$(selector).keydown(function) 

Here selector is the selected element.Parameter: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not.Return values: It returns whether any key is pressed or not or which key is pressed.jQuery code to show the working of keydown() Method:Code #1:Below code is used to check if a key is on its way down.
<title>Jquery | Keydown() </title>    $(document).keydown(function(event) {          alert('You pressed down a key');    });                  <h1>Try pressing any key from the keyboard </h1>     
Output:After pressing run button-
After pressing any key-
Code #2:Below code is used to check which specific key is pressed down from the keyboard and the event.keyCode and event.which will return a UNICODE value of the pressed key, Both are browser specific.
<title>Jquery | Keydown() </title>      $(document).keydown(function(event) {     var key = (event.keyCode ? event.keyCode : event.which);     if (key >= '65' && key = '96' && key = '48' && key = '112' && key <= '123')        alert('You pressed FUNCTION key - ' + (key - 111));     else if (key == '144')        alert('You pressed NUMLOCK key');     else if (key == '145')        alert('You pressed SCROLL LOCK key');     else        alert('You pressed SPECIAL CHARACTER key'); });   <br><br>      <h1>Try pressing any key from the keyboard </h1>                 
Output:After pressing run button-
After pressing any key-
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
Difference Between PUT and PATCH Request
JQuery | Set the value of an input text field
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change the background color after clicking the button in JavaScript ?
How to change selected value of a drop-down list using jQuery?
numpy.index() in Python

28 Nov, 2018
numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError.
Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in.
Returns : An integer array with the lowest index of found sub-string, raises ValueError if substring is not found.
Code #1:
# Python Program illustrating # numpy.char.index() method import numpy as np   arr = ['this is geeks for geek']  print ("arr : ", arr)  print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks'))
Output:
arr :  ['this is geeks for geek']

index of 'geeks' : [8]

 Code #2:
# Python Program illustrating # numpy.char.index() method import numpy as np   arr = ['this is geeks for geek']  print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 2))print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 10))print ("\nindex of 'geek' : ", np.char.index(arr, 'geek', start = 10))
Output:
index of 'geeks' : [8]
ValueError: substring not found
index of 'geek' : [18]

Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Converting an image to ASCII image in Python

In this article we we want to convert a given images into a text bases image also called ASCII image.
Below is the Python program which will take an input imagee and various functions to convert them into grayscale picture and then apply the ASCII characters to create different patterns insert the image. Finally the emails comes text based image this is a series of plane ASCII characters.
from PIL import Image
import os
ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
def resize_image(image, new_width=25):
   (input__width, input__height) = image.size
   aspect_ratio = input__height/float(input__width)
   changed_height = int(aspect_ratio * new_width)
   changed_image = image.resize((new_width, changed_height))
   return changed_image
def make_grey(image):
   return image.convert('L')
def pixel_to_ascii(image, range_width=25):
   pixels_in_image = list(image.getdata())
   pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in
   pixels_in_image]
   return "".join(pixels_to_chars)
def image_to_ascii(image, new_width=25):
   image = resize_image(image)
   image = make_grey(image)
   pixels_to_chars = pixel_to_ascii(image)
   len_pixels_to_chars = len(pixels_to_chars)
   image_ascii = [pixels_to_chars[index: index + new_width] for index in
   range(0, len_pixels_to_chars, new_width)]
   return "\n".join(image_ascii)
def convert_image(image_filepath):
   # image = None
   try:
      image = Image.open(image_filepath)
   except Exception as e:
      print("Unable to open image file          {image_filepath}.".format(image_filepath=image_filepath))
   print(e)
   return
   image_ascii = image_to_ascii(image)
   f = open(os.path.splitext(image_filepath)[0]+'.txt','w')
   f.write(image_ascii)
   f.close()
convert_image('D:\\button.jpg')
Running the above code gives us the following result −
Determine the type of an image in Python using imghdr

08 Feb, 2018
Suppose you are given an image type file and you need to determine the type of that file. In simple words, you need to get the extension of that image type file. This can be used in a project to verify whether the image you have requested for is actually an image and with which extension does it come.
imghdr module
Use following command for Installation:
npm install imghdr
Description:The imghdr module determines the type of image contained in a file or byte stream. The imghdr module defines the following function:
imghdr.what(filename[, h])
Tests the image data contained in the file named by filename, and returns a string describing the image type. If optional h is provided, the filename is ignored and h is assumed to contain the byte stream to test.
Note: The path of the file needs to be correct with its correct name. If the image file and the code file are in the same directory, you don’t need to specify the whole path. Just pass the name of the file as I did in the next example
The extensions that can be recognized in module are-‘rgb’, ‘gif’,’ pbm’,’ pgm’,’ ppm’,’ tiff’, ‘rast’, ‘xbm’, ‘jpeg’, ‘bmp’, ‘png’, ‘webp’, ‘exr’. In Python 3.5, extensions ‘exr’ and ‘webp’ are also added.
Example :
Input : picture.gif
Output : gif

Input: picture.jpeg
Output : jpeg

import imghdrx = imghdr.what("picture.gif") #path of image as parameter  print(x)
Output:
gif

This is a simple program but used to solve big problems in real life projects.
This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.amax() in Python

28 Apr, 2022
The numpy.amax() method returns the maximum of an array or maximum along the axis(if mentioned). Syntax:
numpy.amax(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>)
Parameters – 
arr : [array_like] input data
axis : [int or tuples of int] axis along which we want the max value. Otherwise, it will consider arr to be flattened.
out : [ndarray, optional] alternative output array in which to place the result
keepdims : [boolean, optional] if this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised.
Return – Maximum of array – arr[ndarray or scalar], scalar if axis is None; the result is an array of dimension a.ndim – 1, if axis is mentioned. Code – 
Python
# Python Program illustrating# numpy.amax() method import numpy as geek # 1D arrayarr = geek.arange(8)print("arr : ", arr)print("Max of arr : ", geek.amax(arr)) # 2D arrayarr = geek.arange(10).reshape(2, 5)print("\narr : ", arr) # Maximum of the flattened arrayprint("\nMax of arr, axis = None : ", geek.amax(arr)) # Maxima along the first axis# axis 0 means verticalprint("Max of arr, axis = 0 : ", geek.amax(arr, axis = 0)) # Maxima along the second axis# axis 1 means horizontalprint("Max of arr, axis = 1 : ", geek.amax(arr, axis = 1))  
Output – 
arr :  [0 1 2 3 4 5 6 7]
Max of arr :  7

arr :  [[0 1 2 3 4]
 [5 6 7 8 9]]

Max of arr, axis = None :  9
Max of arr, axis = 0 :  [5 6 7 8 9]
Max of arr, axis = 1 :  [4 9]
Reference – https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.amax.html 
Note – These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
surinderdawra388
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
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 to drop one or multiple columns in Pandas Dataframe
How to Scrape Web Data from Google using Python?

29 Dec, 2020
Prerequisites: Python Requests, Implementing Web Scraping in Python with BeautifulSoup
Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites.
In this article, we will scrape the weather update from google’s search result.
Modules Requisred
BeautifulSoup: This module is used for iterating, searching, and modifying the parse tree over the HTML or XML parser. To download it type the below command in the terminal.pip install beautifulsoup4
pip install beautifulsoup4
Requests: Requests library is one of the integral part of Python for making HTTP requests to a specified URL. To download it type the below command in the terminal.pip install requests
pip install requests
Below is the implementation.
import requestsfrom bs4 import BeautifulSoup   # Enter the City Namecity = input("Enter the City Name: ")search = "Weather in {}".format(city)  # URL url = f"https://www.google.com / search?&q ={search}"    # Sending HTTP requestreq = requests.get(url)  # Pulling HTTP data from internetsor = BeautifulSoup(req.text, "html.parser")   # Finding temperature in Celsiustemp = sor.find("div", class_='BNeawe').text  print(temp)
Output :
Python web-scraping-exercises
Python-requests
Web-scraping
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
Program to add two binary strings, and return also as binary string in C++

Suppose we have two binary strings a and b, we have to add these binary numbers and find their sum, also as a string.
So, if the input is like a = "10110", b = "10010", then the output will be "101000".
To solve this, we will follow these steps −
ret := empty string
na := size of a, nb := size of b
i := na - 1, j := nb - 1
carry := 0
while (i >= 0 or j >= 0), do:addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)sum := addA + addB + carrycarry := sum / 2sum := sum mod 2ret := ret concatenate sum(decrease i by 1)(decrease j by 1)
addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)
addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)
sum := addA + addB + carry
carry := sum / 2
sum := sum mod 2
ret := ret concatenate sum
(decrease i by 1)
(decrease j by 1)
if carry is non-zero, then:ret := ret concatenate carry
ret := ret concatenate carry
reverse the array ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string solve(string a, string b){
      string ret = "";
      int na = a.size();
      int nb = b.size();
      int i = na - 1;
      int j = nb - 1;
      int carry = 0;
      while(i >= 0 || j >= 0){
         int addA = i >= 0 ? a[i] - '0' : 0;
         int addB = j >= 0 ? b[j] - '0' : 0;
         int sum = addA + addB + carry;
         carry = sum / 2;
         sum %= 2;
         ret += to_string(sum);
         i--;
         j--;
      }
      if(carry)
         ret += to_string(carry); reverse(ret.begin(), ret.end());
         return ret;
   }
};
main(){
   string a = "10110", b = "10010"; Solution ob;
   cout << ob.solve(a, b);
}
"10110","10010"
101000
Vue.js Methods

10 Sep, 2021
A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.
Syntax:
methods : {
  // We can add our functions here
}
Syntax for single file components:
export default {
  methods: {
    // We can add our functions here
  }
}
In the following examples, we use Vue.js to show the working of methods.
Example 1:
HTML
<!DOCTYPE html><html> <head>     <script src=        "https://unpkg.com/vue">    </script></head> <body>     <div style="text-align: center;" id = "home">          <!-- Rendering data to DOM -->        <h1 style="color: seagreen;">{{title}}</h1>        <h2>Title : {{name}}</h2>        <h2>Topic : {{topic}}</h2>        <!-- Calling function in methods -->        <h2>{{show()}}</h2>     </div> </body><script type="text/javascript">     // Creating Vue Instance    var  vm = new Vue({         // Assigning id of DOM in parameter        el: '#home',        // Assigning values of parameter        data: {            title : "Geeks for Geeks",            name  : "Vue.js",            topic : "Instances"        },         // Creating methods        methods : {             // Creating function            show: function(){                return "Welcome to this tutorial on "                    + this.name + " - " + this.topic;            }        }    });</script>   </html>
  
Output:
 
Vue App
 
Example 2:
 
HTML
<!DOCTYPE html><html> <head>    <script src=        "https://unpkg.com/vue">    </script></head> <body>    <div style="text-align: center;" id = "home">         <!-- Rendering data to DOM -->        <h1 style="color: seagreen;">{{title}}</h1>        <h2>Title : {{name}}</h2>         <!-- Calling function in methods -->        <button @click="show()">Click me</button>        <h2 id="view"></h2>    </div></body> <script type="text/javascript">     // Creating Vue Instance    var  vm = new Vue({         // Assigning id of DOM in parameter        el: '#home',         // Assigning values of parameter        data: {            title : "Geeks for Geeks",            name  : "Vue.js | Methods",        },         // Creating methods        methods : {             // Creating function            show: function(){                    // Setting text in element                    document.getElementById("view")                      .innerHTML = "Hi, This is Vue"                     // Hiding text after 2 seconds                    setTimeout(() => {                        document.getElementById("view")                           .innerHTML = ""                    }, 2000);                }            }    });</script> </html>
  
Output:
 
Before clicking the button:  
Before click
After clicking the button:  
After click
 
anikakapoor
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rename column by index in Pandas

26 Dec, 2020
Prerequisites: Pandas
A column of a data frame can be changed using the position it is in known as its index. Just by the use of index a column can be renamed. This article discusses all such possible methods. 
Import required python library.
Create data
Provide index of the column to be renamed as argument to rename() function.
Pandas rename() method is used to rename any index, column or row.
Syntax: rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)
Parameters:
mapper, index and columns: Dictionary value, key refers to the old name and value refers to new name. Only one of these parameters can be used at once.
axis: int or string value, 0/’row’ for Rows and 1/’columns’ for Columns
copy: Copies underlying data if True.
inplace: Makes changes in original Data Frame if True.
level: Used to specify level in case data frame is having multiple level index.
Return Type: Data frame with new names
Given below are various implementation to achieve our required functionality:
Example 1: Switching both column names with each other using column index.
Python3
import pandas as pd  # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})  # Changing columns name with index numberdf.columns.values[0] = "b"df.columns.values[1] = "a"  # Displaydisplay(df)
Output:
Example 2: Using another method to rename the column with index.
Python3
import pandas as pd  # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})  # Changing columns name with index numbersu = df.rename(columns={df.columns[1]: 'new'})  # Displaydisplay(su)
Output:
Example 3: Renaming two/more columns in a single command using an index number.
Python3
import pandas as pd  # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [7, 8]})  # Changing columns name with index numbermapping = {df.columns[0]: 'new0', df.columns[1]: 'new1'}su = df.rename(columns=mapping)  # Displaydisplay(su)
Output:
Example 4: Renaming column name with an index number of the CSV file.
File in use: Data1.csv
Link: Click here
Python3
import pandas as pd  # reading a csv filedf1 = pd.read_csv("data1.csv")  # change 2nd column name with index numberdf1.columns.values[2] = "city"  # Display DataFramedisplay(df1)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Finding the smallest positive integer not present in an array in JavaScript

We are required to write a JavaScript function that takes in array of integers as the first and the only argument.
Our function should find and return that smallest positive integer which is not present in the array.
For example −
If the input array is −
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
Then the output should be −
const output = 5;
because 1, 2, 3, 4 are already present in the array and 5 is the smallest positive integer absent from the array.
Following is the code −
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
const findSmallestMissing = (arr = []) => {
   let count = 1;
   if(!arr?.length){
      return count;
   };
   while(arr.indexOf(count) !== -1){
      count++;
   };
   return count;
};
console.log(findSmallestMissing(arr));
Following is the console output −
5
What is the use of tilde operator (~) in R?

Tilde operator is used to define the relationship between dependent variable and independent variables in a statistical model formula. The variable on the left-hand side of tilde operator is the dependent variable and the variable(s) on the right-hand side of tilde operator is/are called the independent variable(s). So, tilde operator helps to define that dependent variable depends on the independent variable(s) that are on the right-hand side of tilde operator.
> Regression_Model <- lm(y~ x1 + x2 + x3)
Here, the object Regression_Model stores the formula for linear regression model created by using function lm and y is the dependent variable and x1, x2, and x3 are independent variables.
This model can be created by using a dot (.) if we want to include all the independent variables but for this purpose, we should have all the variables stored in a data frame.
> Regression_Data <- data.frame(x1, x2, x3, y)
> Regression_Model_New < - lm(y~ . , data = Regression_Data)
This will have the same output as the previous model, but we cannot use tilde with dot if we want to create a model with few variables.
Suppose you want to create a new model with x1 and x3 only then it can be done as follows −
> Regression_Model_New1 <- lm(y~ x1 + x3, data = Regression_Data)

But we cannot do it using dot with tilde as −
> Regression_Model_New2_Incorrect <- lm(y~ . + x3, data = Regression_Data)
https://www.tutorialspoint.com/how-to-write-text-and-output-it-as-a-text-file-using-r
PySpark dataframe add column based on other columns

23 Aug, 2021
In this article, we are going to see how to add columns based on another column to the Pyspark Dataframe.
Creating Dataframe for demonstration:
Here we are going to create a dataframe from a list of the given dataset.
Python3
# Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate()  # Create a spark dataframecolumns = ["Name", "Course_Name",           "Months",           "Course_Fees", "Discount",           "Start_Date", "Payment_Done"]data = [    ("Amit Pathak", "Python", 3, 10000, 1000,     "02-07-2021", True),    ("Shikhar Mishra", "Soft skills", 2,     8000, 800, "07-10-2021", False),    ("Shivani Suvarna", "Accounting", 6,     15000, 1500, "20-08-2021", True),    ("Pooja Jain", "Data Science", 12,     60000, 900, "02-12-2021", False),]  df = spark.createDataFrame(data).toDF(*columns)  # View the dataframedf.show()
Output:
It is used to change the value, convert the datatype of an existing column, create a new column, and many more.
Syntax: df.withColumn(colName, col)
Returns: A new :class:`DataFrame` by adding a column or replacing the existing column that has the same name. 
Python3
new_df = df.withColumn('After_discount',                       df.Course_Fees - df.Discount)new_df.show()
Output:
Here we will use SQL query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it.
Then after creating the table select the table by SQL clause which will take all the values as a string.
Python3
df.registerTempTable('table')newDF = spark.sql('select *, Course_Fees - Discount as Total from table')newDF.show()
Output:
In this method, we will define the user define a function that will take two parameters and return the total price. This function allows us to create a new function as per our requirements.
Now we define the data type of the UDF function and create the functions which will return the values which is the sum of all values in the row.
Python3
# import the functions as F from pyspark.sqlimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType  # define the sum_coldef Total(Course_Fees, Discount):    res = Course_Fees - Discount    return res  # integer datatype is definednew_f = F.udf(Total, IntegerType())  # calling and creating the new# col as udf_method_sumnew_df = df.withColumn(  "Total_price", new_f("Course_Fees", "Discount"))  # Showing the Dataframenew_df.show()
Output:
Picked
Python-Pyspark
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to ignore mouse interaction on overlay image using JavaScript ?

22 Jun, 2020
Ignoring mouse interaction on overlay image can be controlled by a CSS property namely pointer-events.It is a property that defines if an element of the page will react to the pointer-events.
Syntax:
pointer-events: auto\none;
Example: The following example demonstrates the use of pointer-events property.
<!DOCTYPE html><html>  <head>  <title>CSS pointer events</title>    <style>    .main {      position: relative;      width: 450px;      font: 25px Verdana;    }      .overlay {      position: absolute;      left: 0px;      top: 0;      width: 225px;      height: 225px;    }      .pointer-events-none {      pointer-events: none;    }  </style>    <script>    window.onload = function () {      document.getElementById(        "enable-disable-pointer-events")        .onclick = function () {          document.getElementById("overlay")            .className = "overlay "             + ((this.checked) ?             "pointer-events-none" : "");      };    };  </script></head>  <body>  <div class="main">    <a href="https://www.geeksforgeeks.org/">      <img        src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200618233603/gfg3.png"></a>    GeeksforGeeks: A computer     Science portal for Geeks.          <div id="overlay" class="overlay"></div>          <p>      <input id="enable-disable-pointer-events"           type="checkbox">      <label for="enable-disable-pointer-events">        Disable pointer events for image      </label>    </p>  </div></body>  </html>
Output:When the checkbox was not selected:When the checkbox is selected:
Final Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
PyQt5 QListWidget – Current Selected Row Signal

01 Aug, 2020
In this article we will see how we can get the current selected row changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method. This signal is emitted whenever the current item changes.
In order to do this we will use currentRowChanged method with the list widget object.
Syntax : list_widget.currentRowChanged.connect(method)
Argument : It takes method as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting current row        list_widget.setCurrentRow(2)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 300, 80)          # making label multi line        label.setWordWrap(True)                  # getting row changed signal        list_widget.currentRowChanged.connect(lambda: label.setText("Row Changed Signal"))      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a Toggle Button in JavaFX?

A button is a component, which performs an action (like submit, login, etc..) when pressed. It is usually labeled with a text or an image specifying the respective action.
A toggle button indicates whether it is elected or not, using toggle button(s) you can switch between multiple states. Generally, multiple toggle buttons are grouped and you can select only one at a time.
You can create a toggle button in JavaFX by instantiating the javafx.scene.control.ToggleButton class. You can assign a toggle button to a group using the setToggleGroup() method.
Only one button will be selected in a toggle group, unlike the radio button if you click
on the selected toggle button it will be un-selected.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ToggledButtonExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating toggle buttons
      ToggleButton button1 = new ToggleButton("Java");
      ToggleButton button2 = new ToggleButton("Python");
      ToggleButton button3 = new ToggleButton("C++");
      //Toggle button group
      ToggleGroup group = new ToggleGroup();
      button1.setToggleGroup(group);
      button2.setToggleGroup(group);
      button3.setToggleGroup(group);
      //Adding the toggle button to the pane
      VBox box = new VBox(5);
      box.setFillWidth(false);
      box.setPadding(new Insets(5, 5, 5, 50));
      box.getChildren().addAll(button1, button2, button3);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("Toggled Button Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
PATHCONTAINS function

Returns TRUE if the specified item exists within the specified path. Otherwise, returns FALSE.
PATHCONTAINS (<path>, <item>) 

path
A string created as the result of evaluating a PATH function.
item
A text expression to look for in the path result.
TRUE or FALSE.
If the item is an integer number, it is converted to text and then the function is evaluated. If conversion fails, then the function returns an error.
= PATHCONTAINS("OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014", "OrgEmp000 7") returns FALSE. 
= PATHCONTAINS("OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014", "OrgEmp000 6") returns TRUE.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Python Pandas CategoricalIndex - Reorder categories

To eorder categories, use the CategoricalIndex reorder_categories() method in Pandas. At first, import the required libraries −
import pandas as pd
CategoricalIndex can only take on a limited, and usually fixed, number of possible values. Set the categories for the categorical using the "categories" parameter. Treat the categorical as ordered using the "ordered" parameter −
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
Display the CategoricalIndex −
print("CategoricalIndex...\n",catIndex)

Get the categories −
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)
Reorder categories using reorder_categories(). Set the categories in new order as a parameter −
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))
Following is the code −
import pandas as pd

# CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)

# Get the categories
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Reorder categories using reorder_categories()
# Set the categories in new order as a parameter
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"]))
This will produce the following output −
CategoricalIndex...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

DisplayingCategories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')

CategoricalIndex after reordering categories...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')
Construct Pushdown automata for L = {0n1m2(n+m) | m,n ≥ 0} - GeeksforGeeks

23 Aug, 2018
Prerequisite – Pushdown automata, NPDA for accepting the language L = {ambnc(m+n) | m,n ≥ 1}PDA plays a very important role in task of compiler designing. That is why there is a need to have a good practice on PDA. Our objective is to construct a PDA which accepts a string of the form {(0^n)(1^m)(2^(n+m))}
Example-
Input: 00001112222222
Output: Accepted

Input: 00011112222
Output: Not Accepted 
Approach used in this PDA –There can be four cases while processing the given input string.
Case 1- m=0: In this cases the input string will be of the form {0n2n}. In this condition, keep on pushing 0’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 0, then pop it from the stack. Keep on popping 0’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state.
Case 2- n=0: In this cases the input string will be of the form {1m2m}. In this condition, keep on pushing 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1, then pop it from the stack. Keep on popping 1’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state.
Case 3- m, n>0: In this cases the input string will be of the form {0n1m2(n+m)}. In this condition, keep on pushing 0’s and 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1 or 0, then pop it (1 or 0) from the stack. Keep on poping 1’s or 0’s until all the 2’s of the input string are processed. If we reach to the end of input string and stack becomes empty, then reach to final state i.e. accept the input string else move to dead state.
Case 4- m=0, n=0: In this case the input string will be empty. Therefore directly jump to final state.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Difference between DFA and NFA
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
Conversion of Epsilon-NFA to NFA
Boyer-Moore Majority Voting Algorithm