code-rag-bench/online-tutorials huggingface dataset:
IntStream iterator() method in Java

The iterator() method of the IntStream class in Java is used to return an iterator for the elements of this stream.
The syntax is as follows
PrimitiveIterator.OfInt iterator()
Here, PrimitiveIterator.OfInt is an Iterator specialized for int values. To work with the IntStream class in Java, import the following package
import java.util.stream.IntStream;
Create an IntStream and add some elements
IntStream intStream = IntStream.of(15, 40, 55, 70, 95, 120);
To return an iterator for the stream elements
PrimitiveIterator.OfInt primIterator = intStream.iterator();
The following is an example to implement IntStream iterator() method in Java
 Live Demo
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(15, 40, 55, 70, 95, 120);
      PrimitiveIterator.OfInt primIterator = intStream.iterator();
      while (primIterator.hasNext()) {
         System.out.println(primIterator.nextInt());
      }
   }
}
15
40
55
70
95
120
Maximum Average Subarray I in C++

Suppose we have an array with n elements, we have to find the contiguous subarray of given length k that has the maximum average value. We have to return the maximum average value.
So, if the input is like [1,13,-5,-8,48,3] and k = 4, then the output will be 12.0, as (13-5-8+48)/4 = 12.0.
To solve this, we will follow these steps −
sum := 0
sum := 0
for initialize i := 0, when i < k, update (increase i by 1), do −sum := sum + nums[i]
for initialize i := 0, when i < k, update (increase i by 1), do −
sum := sum + nums[i]
sum := sum + nums[i]
maxi := sum
maxi := sum
for initialize i := k, when i < size of nums, update (increase i by 1), do −sum := sum + nums[i] - nums[i - k]if sum > maxi, then −maxi := sum
for initialize i := k, when i < size of nums, update (increase i by 1), do −
sum := sum + nums[i] - nums[i - k]
sum := sum + nums[i] - nums[i - k]
if sum > maxi, then −maxi := sum
if sum > maxi, then −
maxi := sum
maxi := sum
return maxi / k
return maxi / k
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   double findMaxAverage(vector<int>& nums, int k) {
      int sum = 0;
      for (int i = 0; i < k; i++) {
         sum += nums[i];
      }
      double maxi = sum;
      for (int i = k; i < nums.size(); i++) {
         sum += nums[i] - nums[i - k];
         if (sum > maxi) {
            maxi = sum;
         }
      }
      return maxi / k;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,13,-5,-8,48,3};
   cout << (ob.findMaxAverage(v, 4));
}
{1,13,-5,-8,48,3}, 4
12
How to match a nonwhitespace character in python using Regular Expression?

The following code matches all non-whitespace characters in the given string.
import re
foo = re.search(r'\S+', 'Need for Speed 2')
print foo
<_sre.SRE_Match object at 0x0000000004A06648>
The following code matches and finds all non-whitespace characters in the given string and prints them
import re
foo = re.findall(r'\S+', 'Need for Speed 2')
print foo
['Need', 'for', 'Speed', '2']
How to get the content of a textarea using jQuery?

Here I am using one textarea and one button.The first textarea is used for user input then click the button and display the value in the alert box.
 Live Demo
<html>
<head>
   <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
      <script type="text/javascript">
         $(document).ready(function () {
            $("button").click(function () {
               var dim = $("#txt").val();
               alert(dim);
            });
         });
   </script>
</head>
<body>
<div>
<textarea id="txt" rows="5" cols="20"></textarea>
<button type="button" id="btn">Click Here</button>
</div>
</body>
</html>
Python | Program to extract frames using OpenCV

15 May, 2018
OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV.
OpenCv library can be used to perform multiple operations on videos. Let’s try to do something interesting using CV2. Take a video as input and break the video into frame by frame and save those frame. Now, number of operations can be performed on these frames. Like reversing the video file or crop the video etc. For playing video in reverse mode, we need only to store the frames in a list and iterate reverse in the list of frames. Use reverse method of the list for reversing the order of frames in the list.
Function Used :
VideoCapture(File_path) : Read the video(.mp4 format)
read() : Read data depending upon the type of object that calls
imwrite(filename, img[, params]) : Saves an image to a specified file.
 Below is the implementation :
# Program To Read video# and Extract Framesimport cv2  # Function to extract framesdef FrameCapture(path):          # Path to video file    vidObj = cv2.VideoCapture(path)      # Used as counter variable    count = 0      # checks whether frames were extracted    success = 1      while success:          # vidObj object calls read        # function extract frames        success, image = vidObj.read()          # Saves the frames with frame-count        cv2.imwrite("frame%d.jpg" % count, image)          count += 1  # Driver Codeif __name__ == '__main__':      # Calling the function    FrameCapture("C:\\Users\\Admin\\PycharmProjects\\project_1\\openCV.mp4")
Output :
OpenCV
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
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
Python Program for Activity Selection Problem | Greedy Algo-1

30 Jun, 2022
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example:
Example 1 : Consider the following 3 activities sorted
by finish time.
     start[]  =  {10, 12, 20};
     finish[] =  {20, 25, 30};
A person can perform at most two activities. The 
maximum set of activities that can be executed 
is {0, 2} [ These are indexes in start[] and 
finish[] ]

Example 2 : Consider the following 6 activities 
sorted by finish time.
     start[]  =  {1, 3, 0, 5, 8, 5};
     finish[] =  {2, 4, 6, 7, 9, 9};
A person can perform at most four activities. The 
maximum set of activities that can be executed 
is {0, 1, 3, 4} [ These are indexes in start[] and 
finish[] ]
Python
"""The following implementation assumes that the activitiesare already sorted according to their finish time""" """Prints a maximum set of activities that can be done by asingle person, one at a time"""# n --> Total number of activities# s[]--> An array that contains start time of all activities# f[] --> An array that contains finish time of all activities def printMaxActivities(s, f ):    n = len(f)    print "The following activities are selected"     # The first activity is always selected    i = 0    print i,     # Consider rest of the activities    for j in xrange(n):         # If this activity has start time greater than        # or equal to the finish time of previously        # selected activity, then select it        if s[j] >= f[i]:            print j,            i = j # Driver program to test above functions = [1, 3, 0, 5, 8, 5]f = [2, 4, 6, 7, 9, 9]printMaxActivities(s, f) # This code is contributed by Nikhil Kumar Singh
The following activities are selected
0 1 3 4
Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!
nidhi_biet
mitalibhola94
Python DSA-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python program to interchange first and last elements in a list
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Python | Check if a variable is string
Find the length of each string element in the Numpy array - GeeksforGeeks

06 Mar, 2019
NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc).
In this post we are going to discuss ways in which we can find the length of each string element in the given numpy array.
Problem #1 : Given a numpy array whose underlying data is of string type. Find the length of each element in the given object.
Solution : We are going to use numpy.vectorize() function to find the length of each element in the given numpy array object.
# importing the numpy library as npimport numpy as np  # Create a numpy arrayarr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])  # Print the arrayprint(arr)
Output :
Now we will use numpy.vectorize() function to find the length of each element in the given numpy array object.
# Use vectorize function of numpylength_checker = np.vectorize(len)  # Find the length of each elementarr_len = length_checker(arr)  # Print the length of each elementprint(arr_len)
Output :
As we can see in the output, we have successfully calculated the length of each string element in the given numpy array object.
Problem #2 : Given a numpy array whose underlying data is of string type. Find the length of each element in the given object.
Solution : We are going to use List comprehension technique to find the length of each element in the given numpy array object.
# importing the numpy library as npimport numpy as np  # Create a numpy arrayarr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])  # Print the arrayprint(arr)
Output :
Now we will use List comprehension technique to find the length of each element in the given numpy array object.
# Find the length of each elementarr_len = [len(i) for i in arr]  # Print the length of each elementprint(arr_len)
Output :
As we can see in the output, we have successfully calculated the length of each string element in the given numpy array object.
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
How to concatenate Two Arrays in C#?

To concatenate two arrays in C#, let us first declare and initialize the array. Here, we have considered a string array −
string[] str = new string[] { "Hello","World" };
Now let us use the join() method to concatenate −.
string.Join(" ", str);
Now let us see the complete code to concatenate two arrays.
 Live Demo
using System;

class Program {
   static void Main() {
      string[] str = new string[] { "Hello","World" };

      string res = string.Join(" ", str);
      Console.WriteLine(res);
   }
}
Hello World
C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each 
value.
To declare an array, define the variable type, specify the name 
of the array followed by square brackets 
and specify the number of elements it should store:
We have now declared a variable that holds an array of four strings. To insert 
values to it, we can use an array literal - place the values in a 
comma-separated list, inside curly braces:
To create an array of three integers, you could write:
You access an array element by referring to the index number inside square 
brackets [].
This statement accesses the value of the first element in 
cars:
Note: Array indexes start with 0: [0] is the first element. [1] is the second 
element, etc.
To change the value of a specific element, refer to the index number:
Create an array of type string called cars.
 [4] = {"Volvo", "BMW", "Ford", "Mazda"};

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.
How to center align component using BoxLayout with Java?

Let us first create a panel and set some buttons −
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
Now, use the setAlignmentX() and within that specify alignment to the center of the component −
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
The following is an example to center align component using BoxLayout −
package my;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
      JPanel panel = new JPanel();
      JButton btn1 = new JButton("One");
      JButton btn2 = new JButton("Two");
      JButton btn3 = new JButton("Three");
      JButton btn4 = new JButton("Four");
      JButton btn5 = new JButton("Five");
      panel.add(btn1);
      panel.add(btn2);
      panel.add(btn3);
      panel.add(btn4);
      panel.add(btn5);
      panel.setAlignmentX(Component.CENTER_ALIGNMENT);
      panel.setPreferredSize(new Dimension(400, 100));
      panel.setMaximumSize(new Dimension(400, 100));
      panel.setBorder(BorderFactory.createTitledBorder("demo"));
      frame.getContentPane().add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
JavaScript - Get the text of a span element

To get the text of the span element in JavaScript, the code is as follows −
 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Date Methods</h1>
<span class="test">This is some sample text inside a span element</span>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to get the span text
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let spanEle = document.querySelector(".test");
   document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML = "The span text is = " + spanEle.innerHTML;
   });
</script>
</body>
</html>
On clicking the “CLICK HERE” button −
Aurelia - Routing

Routing is an important part of every application. In this chapter, you will learn how to use the router in Aurelia framework.
We have already created a components folder in one of the former chapters. If you don't have it created already, you should place it inside the src folder.
C:\Users\username\Desktop\aureliaApp\src>mkdir components

Inside this folder, we will create home and about directories.
C:\Users\username\Desktop\aureliaApp\src\components>mkdir home
C:\Users\username\Desktop\aureliaApp\src\components>mkdir about

Inside the home folder, we need to create view and view-model files.
C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.js
C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.html

We also need view and view-model for about page.
C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.js
C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.html

Note − You can also create all the above folders manually.
Next, we need to add some default code to the files we created.
<template>
   <h1>HOME</h1>
</template>
export class Home {}
<template>
   <h1>ABOUT</h1>
</template>
export class About {}
We will create view-model for router inside app.js file.
export class App {
   configureRouter(config, router) {
      config.title = 'Aurelia';
		
      config.map([
         { route: ['','home'],  name: 'home',  
            moduleId: './components/home/home',  nav: true, title:'Home' },
         { route: 'about',  name: 'about',
            moduleId: './components/about/about',    nav: true, title:'About' }
      ]);

      this.router = router;
   }
}
Our router view will be placed in app.html.
<template>
   <nav>
      <ul>
         <li repeat.for = "row of router.navigation">
            <a href.bind = "row.href">${row.title}</a>
         </li>
      </ul>
   </nav>	
   <router-view></router-view>
</template>
When we run the app, we will can change the routes by clicking home or about links.
 Print
 Add Notes
 Bookmark this page
banner command in Linux with examples - GeeksforGeeks

31 Aug, 2021
banner command in linux is used to print the ASCII character string in large letter to standard output. 
Syntax: 
banner text
Example 1: Printing “1234567890” in large letters. 
Example 2: Printing “GeeksforGeeks” in large letters. There are two things:  
First, all the letter will be displayed in Capital letters in standard output.
Second, only “GEEKSFORGE” will be printed as banner has a default capacity of 10 characters in a word. After that, you have to give space which is shown in further examples.
Example 3: Printing “Geeks for Geeks” on display. 
Example 4: Trying to print 1234567890123 in a single word but only 1234567890 will be printed on display. 
info banner or man banner command : It displays help information. 
Note: If the terminal shows banner not found, then in UBUNTU use ‘sudo apt install sysvbanner‘ or ‘sudo apt install banner‘ to download it. 
sagar0719kumar
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
Index inside map() Function

22 Nov, 2019
In JavaScript, map() method handles array elements, which creates a new array with the help of results obtained from calling function for each and every array element in an array. The index is used inside map() method to state the position of each element in an array, but it doesn’t change the original array.
Syntax:
array.map(function(currentelement, index, arrayobj) {

  // Returns the new value instead of the item

});

Parameters: The Index inside function accepts three parameters as mentioned above and described below:
currentelement: The currentelement is a required argument in map() which is the value of current element.
index: The index is an optional argument map() which is an array index of provided current element.
arrayobj: The arrayobj is an optional argument in map() which is the array object where the current element belongs.
Below examples illustrate the Index inside map() function:
Example 1:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <meta name="viewport" content=           "width=device-width, initial-scale=1"></head>  <body style="text-align:center;">          <h1 style="color:green;padding:13px;">        GeeksforGeeeks    </h1>          <h3>Index inside map() Function</h3>          <script>        var student = ["Arun", "Arul",             "Sujithra", "Jenifer", "Wilson"];                  student.map((stud, index) => {            alert("Hello... " + stud + "\n");                          var index = index + 1;                          alert("Your Position in Top 5"                + " Rank is " + index + "\n");        });    </script></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html lang="en">   <head>    <meta charset="utf-8">          <meta name="viewport" content=        "width=device-width, initial-scale=1"></head>   <body style="text-align:center;">          <h1 style="color:green;padding:13px;">      GeeksforGeeeks    </h1>          <h3>Index inside map() Function</h3>          <script>        var webname = ["welcome", "to",                    "GeeksforGeeeks"];                  webname.map((web, index) => {            document.write(web + "<br>");        });                  // check in console        webname.map((web, index)            => console.log(web, index));    </script></body>   </html>
Output:
welcome
0
to
1
GeeksforGeeeks
2
Supported Browsers: The browsers supported by Index inside map() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to disable dropdown in ReactJS?

18 Jan, 2021
Disable dropdown means the user can’t interact with the dropdown nor its options. Material UI for React has this component available for us and it is very easy to integrate. We can disable the dropdown using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';  const App = () => {    // Sample options for dropdown  const myOptions = ['One', 'Two', 'Three', 'Four', 'Five'];    return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        style={{width:500}}        disabled        options={myOptions}        renderInput={(params) => (          <TextField {...params}            variant="outlined"            label="Disabled Dropdown"           />        )}      />    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
How to pass data from one component to other component in ReactJS ?
Java 8 | IntSupplier Interface with Examples

10 Oct, 2018
The IntSupplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take any argument but produces an int value.
The lambda expression assigned to an object of IntSupplier type is used to define its getAsInt() which eventually applies the given operation on its argument. It is similar to using an object of type Supplier<Integer>
The IntSupplier interface consists of the only one function:
This method does not take in any value but produces an int-valued result.
Syntax:
int getAsInt()
Return Value: This method returns an int value.
Below is the code to illustrate getAsInt() method:
Program:
// Java program to illustrate// getAsInt method of IntSupplier Interface  import java.util.function.IntSupplier;  public class GFG {    public static void main(String args[])    {          // Create a IntSupplier instance        IntSupplier            sup            = () -> (int)(Math.random() * 10);          // Get the int value        // Using getAsInt() method        System.out.println(sup.getAsInt());    }}
7

Java - util package
Java 8
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for Sum the digits of a given number

02 Nov, 2021
Given a number, find sum of its digits.Example :  
Input : n = 687
Output : 21

Input : n = 12
Output : 3
1. Iterative:  
Java
// Java program to compute// sum of digits in number.import java.io.*; class GFG {         /* Function to get sum of digits */    static int getSum(int n)    {           int sum = 0;                 while (n != 0)        {            sum = sum + n % 10;            n = n/10;        }         return sum;    }     // Driver program    public static void main(String[] args)    {        int n = 687;         System.out.println(getSum(n));    }} // This code is contributed by Gitanjali
Time Complexity: O(|n|)
Auxiliary Space: O(1)
How to compute in single line?  
Java
// Java program to compute// sum of digits in number.import java.io.*; class GFG {         /* Function to get sum of digits */    static int getSum(int n)    {        int sum;         /* Single line that calculates sum */        for (sum = 0; n > 0; sum += n % 10,                                  n /= 10);         return sum;    }     // Driver code    public static void main(String[] args)    {        int n = 687;         System.out.println(getSum(n));    }} // This code is contributed by Gitanjali
Time Complexity: O(|n|)
Auxiliary Space: O(1)
2. Recursive  
Java
// Java program to compute// sum of digits in number.import java.io.*; class GFG {       /* Function to get sum of digits */    static int sumDigits(int no)    {        return no == 0 ? 0 : no%10 +                  sumDigits(no/10) ;    }     // Driver code    public static void main(String[] args)    {    int n = 687;     System.out.println(sumDigits(n));    }} // This code is contributed by Gitanjali
Time Complexity: O(log10n)
Auxiliary Space: O(log10n)
Please refer complete article on Program for Sum the digits of a given number for more details! 
rishavmahato348
subham348
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert BLOB into VARCHAR in MySQL?

28 Nov, 2021
In this article, we would be learning a SQL query to convert a column of BLOB Data Type to VARCHAR Data Type. To execute this query we would need to alter the table and subsequently a column’s definition. We would first need to use the ALTER TABLE command to change the table.
ALTER TABLE: ALTER TABLE is a command used to add, delete, or modify columns in an existing table. It is also used to add and drop various constraints on an existing table. We have two commands for alter table MODIFY and CHANGE.
Step 1: Creating a database
To create a database using the following query
Query : 
CREATE DATABASE geek;
Step 2: Using the database
To use the database use the following query
Query : 
USE geek;
Step 3: Creating a table
Create a table having one of the columns with BLOB Data Type.
Query : 
CREATE TABLE demo_table(AGE INT,
PHOTO BLOB,
SALARY FLOAT);
Step 4: Describing the table
Use this query to describe the properties of a table.
Query : 
DESCRIBE demo_table;
Output:
Step 5: Changing column Data Type from BLOB to VARCHAR(100). We will be changing the PHOTO column as it is of the BLOB Data Type.
Method 1: USING MODIFY
To change a column definition use MODIFY along with the ALTER command.
Query : 
ALTER TABLE demo_table
MODIFY PHOTO VARCHAR(100);
Method 2: USING CHANGE 
With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name.
Query : 
ALTER TABLE demo_table CHANGE 
PHOTO PHOTO_CHANGE VARCHAR(100);
Step 6: Describe your table to see the changes 
DESCRIBE demo_table;
Output: Results after using MODIFY
Output: Results after using CHANGE
mysql
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.insert() - GeeksforGeeks

03 May, 2021
Pandas insert method allows the user to insert a column in a dataframe or series(1-D Data frame). A column can also be inserted manually in a data frame by the following method, but there isn’t much freedom here. For example, even column location can’t be decided and hence the inserted column is always inserted in the last position.Syntax:  
DataFrameName.insert(loc, column, value, allow_duplicates = False)
Parameters:  
loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right. column: column is a string which is name of column to be inserted. value: value is simply the value to be inserted. It can be int, string, float or anything or even series / List of values. Providing only one value will set the same value for all rows. allow_duplicates : allow_duplicates is a boolean value which checks if column with same name already exists or not.  
Find the link to csv file used from here. 
Python3
# importing pandas moduleimport pandas as pd  # reading csv filedata = pd.read_csv("pokemon.csv")  # displaying  dataframe - Output 1data.head()
Output:  
After Inserting column:  
Python3
# importing pandas moduleimport pandas as pd # reading csv filedata = pd.read_csv("pokemon.csv") # displaying  dataframe - Output 1data.head() # inserting column with static value in data framedata.insert(2, "Team", "Any") # displaying data frame again - Output 2data.head()
In this example, a series is created and some values are passed to the series through a for loop. After that, the series is passed in pandas insert function to append series in the Data frame with values passed. 
Python
# importing pandas moduleimport pandas as pd # creating a blank seriesType_new = pd.Series([]) # reading csv filedata = pd.read_csv("pokemon.csv")  # running a for loop and assigning some values to seriesfor i in range(len(data)):    if data["Type"][i] == "Grass":        Type_new[i]="Green"     elif data["Type"][i] == "Fire":        Type_new[i]="Orange"     elif data["Type"][i] == "Water":        Type_new[i]="Blue"     else:        Type_new[i]= data["Type"][i]          # inserting new column with values of list made above       data.insert(2, "Type New", Type_new) # list outputdata.head()
Output:
simranarora5sos
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
Replacing words with asterisks in C++

This aim of this program to replace a particular word with asterisks in the string by using the c++ programming code. The essential function of vector and string class essay a key role to achieve the prospective results. The algorithm is as follows;
START
   Step-1: Input string
   Step-2 Split the string into words and store in array list
   Step-3: Iterate the loop till the length and put the asterisk into a variable
   Step-4: Traverse the array foreah loop and compare the string with the replaced word
   Step-5: Print
END
Now, the following code is carved out based on the algorithm. Here, the strtok() method of string split the string and returns the array list type of vector class.
#include <cstring>
#include <iostream>
#include <vector>
#include <string.h>
//method for spliting string
std::vector<std::string> split(std::string str,std::string sep){
   char* cstr=const_cast<char*>(str.c_str());
   char* current;
   std::vector<std::string> arr;
   current=strtok(cstr,sep.c_str());
   while(current!=NULL){
      arr.push_back(current);
      current=strtok(NULL,sep.c_str());
   }
   return arr;
}
int main(){
   std::vector<std::string> word_list;
   std::cout<<"string before replace::"<<"Hello ajay yadav ! you ajay you are star"<<std::endl;
   std::cout<<"word to be replaced::"<<"ajay"<<std::endl;
   word_list=split("Hello ajay yadav ! you ajay you are star"," ");
   std::string result = "";
   // Creating the censor which is an asterisks
   // "*" text of the length of censor word
   std::string stars = "";
   std::string word = "ajay";
   for (int i = 0; i < word.length(); i++)
      stars += '*';
      // Iterating through our list
      // of extracted words
      int index = 0;
      for (std::string i : word_list){
         if (i.compare(word) == 0)
         // changing the censored word to
         // created asterisks censor
         word_list[index] = stars;
         index++;
      }
      // join the words
      for (std::string i : word_list){
         result += i + ' ';
      }
      std::cout<<"output::"<<result;
      return 0;
   }
}
As seen in the above code, all string operation code is bundled into the retrieveChar() method, later on, which call is passed to program main() execution.
String before replace::Hello ajay yadav ! you ajay you are star
Word to be replaced::ajay
Output::Hello **** yadav ! you **** you are star
How to avoid null result of “SELECT max(rank) FROM test” for an empty table?

You can use COALESCE() along with aggregate function MAX() for this.
The syntax is as follows
SELECT COALESCE(MAX(`yourColumnName`), 0) FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table avoidNullDemo
   -> (
   -> `rank` int
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into avoidNullDemo values(10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into avoidNullDemo values(NULL);
Query OK, 1 row affected (0.18 sec)
mysql> insert into avoidNullDemo values(20);
Query OK, 1 row affected (0.17 sec)
mysql> insert into avoidNullDemo values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into avoidNullDemo values(100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into avoidNullDemo values(NULL);
Query OK, 1 row affected (0.16 sec)
Display you all records from the table using select statement.
The query is as follows
mysql> select *from avoidNullDemo;
The following is the output with NULL values
+------+
| rank |
+------+
| 10   |
| NULL |
| 20   |
| NULL |
| 100  |
| NULL |
+------+
6 rows in set (0.00 sec)
Here is the query to avoid null result
mysql> select COALESCE(MAX(`rank`), 0) FROM avoidNullDemo;
The following is the output
+--------------------------+
| COALESCE(MAX(`rank`), 0) |
+--------------------------+
| 100                      |
+--------------------------+
1 row in set (0.00 sec)
Here is the case when table is empty.
Let us delete all records from the above table.
The query is as follows
mysql> truncate table avoidNullDemo;
Query OK, 0 rows affected (0.92 sec)
Now the above table is empty. Let us implement the above query for empty table
mysql> select COALESCE(MAX(`rank`), 0) FROM avoidNullDemo;
The following is the output
+--------------------------+
| COALESCE(MAX(`rank`), 0) |
+--------------------------+
| 0                        |
+--------------------------+
1 row in set (0.00 sec)
Downloading file to specified location with Selenium and python.

We can download files to a specified location with Selenium in Python. This is done by the help of the ChromeOptions class. We shall set the preferences of the browser and pass the download.default_directory parameter.
We need to mention the path of the download directory with that parameter. This preference is sent to the ChromeOptions object with the add_experimental_option method.
Finally, this browser information is shared with the driver object.
op = webdriver.ChromeOptions()
p = ("download.default_directory": "C:\\Users", "safebrowsing.enabled":"false")
op.add_experimental_option("prefs", p)
driver = webdriver.Chrome(chrome_options=op)
Code Implementation.
from selenium import webdriver
from selenium.webdriver.common.by import By
#object of ChromeOptions
op = webdriver.ChromeOptions()
#set download directory path
p = ("download.default_directory": "C:\\Users""safebrowsing.enabled":"false")
#adding preferences to ChromeOptions
op.add_experimental_option("prefs", p)
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", chrome_options=op)
driver.implicitly_wait(0.4)
driver.get("https://www.seleniumhq.org/download/");
#identify element
m = driver.find_element_by_link_text("32 bit Windows IE")
m.click()
How to use search input type in HTML?

The search input type is used in HTML using the <input type="search">. It is used for search fields and looks like a normal text field. This can be used to add a search bar.
You can try to run the following code to learn how to use search input type in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input search</title>
   </head>

   <body>
      <form action = "" method = "get">
         Search<br>
         <input type = "search" name = "search"><br>
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
Python Pandas - Filling missing column values with median

Median separates the higher half from the lower half of the data. Use the fillna() method and set the median to fill missing columns with median. At first, let us import the required libraries with their respective aliases −
import pandas as pd
import numpy as np
Create a DataFrame with 2 columns. We have set the NaN values using the Numpy np.NaN −
dataFrame = pd.DataFrame(
   {
      "Car": ['Lexus', 'BMW', 'Audi', 'Bentley', 'Mustang', 'Tesla'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN]
   }
)
Find median of the column values with NaN i.e, for Units columns here. Replace NaNs with the median of the column where it is located using median() on Units column −
dataFrame.fillna(dataFrame['Units'].median(), inplace = True)

Following is the code −
import pandas as pd
import numpy as np

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['Lexus', 'BMW', 'Audi', 'Bentley', 'Mustang', 'Tesla'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN]
   }
)

print"DataFrame ...\n",dataFrame

# finding median of the column values with NaN i.e, for Units columns here
# Replace NaNs with the median of the column where it is located
dataFrame.fillna(dataFrame['Units'].median(), inplace = True)

print"\nUpdated Dataframe after filling NaN values with median...\n",dataFrame
This will produce the following output −
DataFrame ...
       Car   Units
0    Lexus   100.0
1      BMW   150.0
2     Audi     NaN
3  Bentley    80.0
4  Mustang     NaN
5    Tesla     NaN

Updated Dataframe after filling NaN values with median...
       Car   Units
0    Lexus   100.0
1      BMW   150.0
2     Audi   100.0
3  Bentley    80.0
4  Mustang   100.0
5    Tesla   100.0
Node.js zlib.gzip() Method - GeeksforGeeks

12 Oct, 2021
The zlib.gzip() method is an inbuilt application programming interface of the Zlib module which is used to compresses a chunk of data.
Syntax:
zlib.gzip( buffer, options, callback )
Parameters: This method accepts three parameters as mentioned above and described below:
buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string.
options: It is an optional parameter that holds the zlib options.
callback: It holds the callback function.
Return Value: It returns the chunk of data after compression.
Below examples illustrate the use of zlib.gzip() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // gzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geek";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    if (!err) {      console.log(buffer.toString('base64'));  }   else {    console.log(err);  }});console.log("Data Compressed...");
Output:
Data Compressed...
H4sIAAAAAAAAA3NPTc0GAGGRcasEAAAA

Example 2:
// Node.js program to demonstrate the     // gzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geek";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    if (!err) {      console.log(buffer.toString('hex'));  }   else {    console.log(err);  }});console.log("Data Compressed...");
Output:
Hint: hit control+c anytime to enter REPL.
Data Compressed...
1f8b0800000000000003734f4dcd0600619171ab04000000

Reference: https://nodejs.org/api/zlib.html#zlib_zlib_gzip_buffer_options_callback
Node.js-Zlib-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.redirect() Function
Node.js fs.readdirSync() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
sympy.stats.Hypergeometric() function in Python - GeeksforGeeks

01 Jun, 2020
Hypergeometric distribution is a distribution of discrete probability that defines the probability of success in draws. With the help of sympy.stats.Hypergeometric() method, we can get the finite random variable who denotes the value of hypergeometric distribution by using sympy.stats.Hypergeometric() method.
Syntax : sympy.stats.Hypergeometric(name, N, m, n)
Parameters :name – It use to denote the distribution.N – Total population of size N.m – number of trialsn – number of draws
Return : Return the hypergeometric distribution.
Example #1 :In this example, we can see that by using sympy.stats.Hypergeometric() method, we are able to get the random variable denotes the hypergeometric distribution by using this method.
# Import sympy and hypergeometricfrom sympy.stats import Hypergeometric, density    # Using sympy.stats.Hypergeometric() method# Taking 10 marbles, 5 white(success), 3 drawsX = Hypergeometric('X', 10, 5, 3) gfg = density(X).dict  print(gfg)
Output :
{0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12}

Example #2 :
# Import sympy and hypergeometricfrom sympy.stats import Hypergeometric, density    # Using sympy.stats.Hypergeometric() methodX = Hypergeometric('X', 2, 1, 1)gfg = density(X).dict  print(gfg)
Output :
{0: 1/2, 1: 1/2}

Python SymPy-Stats
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
numpy.random.weibull() in Python - GeeksforGeeks

18 Aug, 2020
With the help of numpy.random.weibull() method, we can get the random samples from weibull distribution and return the random samples as numpy array by using this method.
Weibull Distribution
Syntax : numpy.random.weibull(a, size=None)
Return : Return the random samples as numpy array.
Example #1 :
In this example we can see that by using numpy.random.weibull() method, we are able to get the random samples from weibull distribution and return the numpy array.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  # Using weibull() methodgfg = np.random.weibull(5, 5000)  plt.hist(gfg, bins = 50, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  # Using weibull() methodgfg = np.random.weibull(6.78, 10000)  plt.hist(gfg, bins = 100, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Difference between SCAN and CSCAN Disk scheduling algorithms - GeeksforGeeks

04 May, 2020
Prerequisite – Disk Scheduling Algorithms
1. SCAN Disk Scheduling Algorithm :SCAN Disk Scheduling Algorithm is also known as Elevator algorithm. In this, head or pointer can move in both the direction i.e., disk arm starts to move from one end of the disk to the other end servicing all the requests until it reaches to the other end of the disk. After reaching the other end, head movement direction is reversed and further continues servicing the requests.
The problem with this is that it takes longer waiting time than the C-SCAN scheduling algorithm for requesting the locations.
Example :Assuming the head starts at 53 and starts moving towards left end.
Total head movements,
= (53-37)+(37-14)+(14-0)+(65-0)+(67-65)
             +(98-67)+(122-98)+(124-122)+(183-124)
= 236 
2. C-SCAN Disk Scheduling Algorithm :In C-SCAN disk scheduling algorithm, the only difference with respect to SCAN algorithm is that, it is designed to provide more uniformity in waiting time. In this, head or pointer works in a single direction i.e., it scans for the requests all the way to a direction and once it reaches the end, it jumps back to another end and services the requests in the same direction unlike, SCAN does it in both reversed and forward direction.
Example:Assuming the head starts at 53 and starts moving towards right end.
Total head movements,
= (65-53)+(67-65)+(98-67)+(122-98)+(124-122)
            +(183-124)+(199-183)+(199-0)+(14-0)+(37-14)
= 382 
Let’s see the difference between SCAN and C-SCAN disk scheduling algorithm –
vanshgaur14866
Picked
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS