code-rag-bench/online-tutorials huggingface dataset:
Stack of Pair in C++ STL with Examples

25 Mar, 2020
Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.
Pair in STL The pair container is a simple container defined in header consisting of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).
Stack of pair in STL: Stack of pair can be very efficient in designing complex data structures.
Syntax:
stack<pair<datatype, datatype>> stack_of_pair;

Below is an example to show the Stack of Pairs:
// CPP program to demonstrate// the working of STL stack of pairs  #include <bits/stdc++.h>using namespace std;  // Print the current pairvoid printPair(pair<int, int> p){      cout << "("         << p.first << ", "         << p.second << ") ";}  // Print the Stack of Pairsvoid Showstack(stack<pair<int, int> > s){    while (!s.empty()) {        printPair(s.top());        s.pop();    }      cout << '\n';}  // Driver codeint main(){    stack<pair<int, int> > s;      s.push({ 10, 20 });    s.push({ 15, 5 });    s.push({ 1, 5 });    s.push({ 5, 10 });    s.push({ 7, 9 });      cout << "Stack of Pairs: ";    Showstack(s);      cout << "\nSize of Stack of Pairs: "         << s.size();    cout << "\nTop of Stack of Pairs: ";    printPair(s.top());      cout << "\n\nRemoving the top pair\n";    s.pop();      cout << "Current Stack of Pairs: ";    Showstack(s);      return 0;}
Stack of Pairs: (7, 9) (5, 10) (1, 5) (15, 5) (10, 20) 

Size of Stack of Pairs: 5
Top of Stack of Pairs: (7, 9) 

Removing the top pair
Current Stack of Pairs: (5, 10) (1, 5) (15, 5) (10, 20)

Below are the images to show the working of Stack of Pairs:
cpp-pair
STL
C++ Programs
Data Structures
Stack
Data Structures
Stack
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Dynamic _Cast in C++
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
What is Hashing | A Complete Tutorial
Introduction to Data Structures
Optional get() method in Java with examples

30 Jul, 2019
The get() method of java.util.Optional class in Java is used to get the value of this Optional instance. If there is no value present in this Optional instance, then this method throws NullPointerException.
Syntax:
public T get()

Parameters: This method do not accept any parameter.
Return value: This method returns the value of this instance of the Optional class.
Exception: This method throws NoSuchElementExcpetion if there is no value present in this Optional instance.
Below programs illustrate get() method:Program 1:
// Java program to demonstrate// Optional.get() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);          // get the value        System.out.println("Value of this Optional: "                           + op.get());    }}
Optional: Optional[9455]
Value of this Optional: 9455

Program 2:
// Java program to demonstrate// Optional.get() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // get the value            System.out.println("Value of "                               + "this Optional: "                               + op.get());        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
java.util.NoSuchElementException: No value present

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#get–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
One bit memory cell (or Basic Bistable element)

22 Aug, 2019
One Bit memory cell is also called Basic Bistable element. It has two cross-coupled inverters, 2 outputs Q and Q’. It is called “Bistable” as the basic bistable element circuit has two stable states logic 0 and logic 1.
The following diagram shows the Basic Bistable element:
(A) when A=0,
(i) In inverter1, Q = A'= B= 1
(ii)In inverter2, Q' = B' = A = 0

(B) when A=1,
(i) In inverter1, Q = A'= B= 0
(ii)In inverter2, Q' = B' = A = 1 
Some key points:
The 2 outputs are always complementary.The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state.The circuit can store 1-bit of digital information and so it is called one-bit memory cell.The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch.
The 2 outputs are always complementary.
The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state.
The circuit can store 1-bit of digital information and so it is called one-bit memory cell.
The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch.
One-bit six transistor SRAM memory cell is volatile. Fast switching speed is its main advantage. It needs a constant power supply because of its volatility. The demand for faster and denser memory devices has seen memristors being proposed as replacements for flash memory, Static Random Access Memory (SRAM) and Random Access Memory (RAM). The most salient feature of memristors is its resistive switching ability that can retain resistance states for long periods despite without power supply.
The One-bit non-volatile memory cell can be designed using transmission gates and memristor. Memristive devices have high switching speed, low energy consumption, non-volatile and small device size. The non-volatility of memristor used in designs as the information storage element provides retention ability of up to 10 years in the absence of power supply. The transmission gates used ensures that voltage is not lost through other components of the memory cell, thus improves the switching speed by providing a larger potential difference across the memristor.
Other advantages of using memristors in memory devices are its long retention period, excellent endurance properties, and good scalability compared to NAND-based flash memory devices.
Reference:DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. GodseIEEE XPLORE, Digital library – One-bit non-volatile memory cell using memristor and transmission gates.
Computer Organization & Architecture
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Store Even & Odd Elements of an Array into Separate Arrays

13 Apr, 2022
Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after traversing and start storing them.
Below is the implementation of the above approach:
Java
// Java Program to Store Even & Odd// Elements of an Array into Separate Arrays public class Even_Odd {     // Print array method    public static void printArray(int[] array)    {        for (int i = 0; i < array.length; i++)            System.out.print(array[i] + " ");        System.out.println();    }    public static void main(String[] args)    {        int n = 8;        // array with N size        int array[] = { 23, 55, 54, 9, 76, 66, 2, 91 };         int evenSize = 0;        int oddSize = 0;        for (int i = 0; i < n; i++) {            if (array[i] % 2 == 0)                evenSize++;            else                oddSize++;        }        // odd and even arrays with size        int[] even = new int[evenSize];        int[] odd = new int[oddSize];        // odd and even array iterator        int j = 0, k = 0;        for (int i = 0; i < n; i++) {            if (array[i] % 2 == 0)                even[j++] = array[i];            else                odd[k++] = array[i];        }        // print array method        System.out.print("Even Array contains: ");        printArray(even);        System.out.print("Odd Array contains: ");        printArray(odd);    }}
Output:
Even Array contains: 54 76 66 2 
Odd Array contains: 23 55 9 91 
Time Complexity: O(n)
Space Complexity: O(n)
shmkmr38
Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Rooted and Binary Tree

A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m = 2, the rooted tree is called a binary tree.
The binary Search tree is a binary tree which satisfies the following property −
X in left sub-tree of vertex V, Value(X) ≤ Value (V)
Y in right sub-tree of vertex V, Value(Y) ≥ Value (V)
So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree.
BST_Search(x, k)
if ( x = NIL or k = Value[x] )
   return x;
if ( k < Value[x])
   return BST_Search (left[x], k);
else
   return BST_Search (right[x], k)
Powershell - Get System Time

Get-Date cmdlet is used to get System Date-Time.
In this example, we're using Get-Date without any parameter
Type the following command in PowerShell ISE Console
Get-Date
You can see following output in PowerShell console.
Get-Date
Wednesday, April 04, 2018 5:24:51 PM

In this example, we're using -DisplayHint to print only Time.
Type the following command in PowerShell ISE Console
Get-Date -DisplayHint Time
You can see following output in PowerShell console.
Get-Date -DisplayHint Date
5:26:36 PM


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Drop rows containing specific value in PySpark dataframe - GeeksforGeeks

30 Jun, 2021
In this article, we are going to drop the rows with a specific value in pyspark dataframe.
Creating dataframe for demonstration:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  datadata = [["1", "sravan", "vignan"],        ["2", "ojaswi", "vvit"],        ["3", "rohith", "vvit"],        ["4", "sridevi", "vignan"],        ["6", "ravi", "vrs"],        ["5", "gnanesh", "iit"]]  # specify column namescolumns = ['ID', 'NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  print('Actual data in dataframe')dataframe.show()
Output:
Method 1: Using where() function
This function is used to check the condition and give the results. That means it drops the rows based on the values in the dataframe column
Syntax: dataframe.where(condition)
Example 1: Python program to drop rows with college = vrs.
Python3
# drop rows with college vrsdataframe.where(dataframe.college!='vrs').show()
Output:
Example 2: Python program to drop rows with ID=1
Python3
# drop rows with id=1 dataframe.where(dataframe.ID !='1').show()
Output:
Method 2: Using filter() function
This function is used to check the condition and give the results, Which means it drops the rows based on the values in the dataframe column. Both are similar.
Syntax: dataframe.filter(condition)
Example: Python code to drop row with name = ravi.
Python3
# drop rows with name = ravi dataframe.filter(dataframe.NAME !='ravi').show()
Output:
Picked
Python-Pyspark
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | os.getegid() and os.setegid() method - GeeksforGeeks

31 Oct, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.getegid() method in Python is used to get the current process’s effective group id and os.setegid() method is used to set effective group id of the current process.
Note: os.setegid() and os.getegid() methods are available only on UNIX platforms and the functionality of os.setegid() method is typically available only to the superuser.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system.
Syntax: os.getegid()
Parameter: No parameter is required
Return Type: This method returns an integer value which represents the current process’s effective group id.
# Python program to explain os.getegid() method   # importing os module import os  # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid()  # Print the effective group id# of the current processprint("Effective group id of the current process:", egid)
Output:
Syntax: os.setegid(egid)
Parameter:egid: An integer value representing new effective group id for the current process.
Return Type: This method does not return any value.
# Python program to explain os.setegid() method   # importing os module import os  # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid()  # Print the effective group id# of the current processprint("Effective group id of the current process:", egid)    # Change the effective group id# for the current process# using os.setegid() methodegid = 200os.setegid(egid)print("Effective group id changed")  # Print the effective group id# of the current processegid = os.getegid()print("Effective group id of the current process:", egid)
Output:
Akanksha_Rai
python-os-module
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()
How to change default font in Tkinter? - GeeksforGeeks

24 Jan, 2021
Prerequisites: Tkinter
Tkinter provides a variety of fonts for different things i.e Heading, Caption, Text, Menu, etc. But the good thing is we can override these fonts using tkinter.font module.
Some fonts provided by the Tkinter are:
TkDefaultFont
TkMenuFont
TkFixedFont
TkSmallCaptionFont and so on.
In this article, we are going to change the default font. In order to do this, we need to override/ change the configuration of TkDefaultFont. Changing/ overriding the default font is very easy and can be done in the listed way:
Create the font object using font.nametofont method.
Use the configure method on the font object
Then change font style such as font-family, font-size, and so on.
Given below is the proper approach for doing the same.
Import module
Create window
Create the font object using font.nametofont method.
Use the configure method on the font object
Then change font style such as font-family, font-size, and so on.
Add required elements
Execute code
Program:
Python3
# Import tkinter.Tk and widgetsfrom tkinter import Tk, fontfrom tkinter.ttk import Button, Label    class App:    def __init__(self, master: Tk) -> None:        self.master = master          # Creating a Font object of "TkDefaultFont"        self.defaultFont = font.nametofont("TkDefaultFont")          # Overriding default-font with custom settings        # i.e changing font-family, size and weight        self.defaultFont.configure(family="Segoe Script",                                   size=19,                                   weight=font.BOLD)          # Label widget        self.label = Label(self.master, text="I'm Label")        self.label.pack()          # Button widget        self.btn = Button(self.master, text="I'm Button")        self.btn.pack()    if __name__ == "__main__":    # Top level widget    root = Tk()      # Setting window dimensions    root.geometry("300x150")      # Setting app title    root.title("Changing Default Font")      print(font.names())      app = App(root)      # Mainloop to run application    # infinitely    root.mainloop()
Output:
Before changing configuration
After changing configuration
Picked
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
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
What are the best input sanitizing functions in PHP ? - GeeksforGeeks

08 Aug, 2020
Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.The PHP Filter Extension: PHP filters are used to sanitize and validate external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to do data sanitization easier and quicker. This function, when using the flag in the example, is making sure that the code removes all characters except letters, digits and the following characters !#$%&’*+-=?_`{|}~@.[] . Advantages of using Filters: Many web applications receive external input. External input/data can be:  
User input from a form
Cookies
Web services data
Server Variables
Database query results
Sanitizing a String: The following example uses the filter_var() function to remove all HTML tags from a string.Program  
php
<?php //Use of filter_var()$str = "<h1>GeeksforGeeks</h1>"; $newstr = filter_var($str,    FILTER_SANITIZE_STRING);     echo $newstr;?>
GeeksforGeeks



 
Sanitizing an Email Address: The following example uses the filter_var() function to remove all illegal characters from the $email variable.Program: 
php
<?php $email = "geeksforgeeks@gmail.co<m>";  // Remove all illegal characters// from email$nemail = filter_var($email,        FILTER_SANITIZE_EMAIL);         echo $nemail;?>
geeksforgeeks@gmail.com



 
Sanitizing a URL: The following example uses the filter_var() function to remove all illegal characters from a URL:Program:  
php
<?php $url = "www.geeksforgeeks.or°g";  // Remove all illegal characters// from a url$nurl = filter_var($url,        FILTER_SANITIZE_URL);         echo $nurl;?>
www.geeksforgeeks.org



 
apoorv__maheshwari
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to disable spell checking from Input Box and Textarea in HTML forms? - GeeksforGeeks

06 Sep, 2021
Basically the concept of spell check feature is used when we enter the grammatically incorrect words inside <input> or <textarea> fields in HTML form you will see the red underline below the incorrect words. It is used to detect grammatical or spelling mistakes in the text fields.
To disable spellcheck in an HTML form the spellcheck attribute is set to “false”. Below is the sample HTML program with disabled spellcheck.
Example:  
html
<!DOCTYPE html><html><body><h2>a    GeeksForGeeks</h2>  <h2>      How to disable spell checkingfrom Input Box and Textarea in HTML forms   </h2>    <form>    <h4>Enabling the spell check Property</h4>      <input type="text" spellcheck="true">         <h4> Disabling the spell check Property</h4>            <input type="text" spellcheck="false">        </p>            <p>            <textarea spellcheck="false"></textarea>        </p>          <button type="reset">Reset</button>    </form></body></html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
anikaseth98
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Catch and Throw Exception In Ruby - GeeksforGeeks

11 Oct, 2019
An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that’s not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement.
Syntax:
catch :lable_name do
# matching catch will be executed when the throw block encounter

throw :lable_name condition
# this block will not be executed

end
The catch block is used to jump out from the nested block and the block is labeled with a name. This block works normally until it encounters with the throw block that’s why catch and throw used instead of raise or rescue.
Example #1:
# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do  # a code block of catch similar to begin    number = rand(2)    throw :divide if number == 0    number # set gfg = number if    # no exception is thrownendputs gfg
Output :


In above example, if the number is 0 then the exception:divide is thrown which returns nothing to the catch statement resulting in “”set to gfg. if the number is 1 then the exception is not thrown and the gfg variable is set to 1.
 
Example #2: throw with default value.
In the above example when the exception was thrown, the value of variable gfg was set to “”. we can change that by passing the default argument to the throw keyword.
# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do  # a code block of catch similar to begin    number = rand(2)    throw :divide, 10 if number == 0    number # set gfg = number if    # no exception is thrownendputs gfg
Output :
10

In above example, if number is 0 we get 10. if number is 1 we get 1. Example 3: nested construct example, here we will see how we can jump out of nested constructs.
# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do  # a code block of catch similar to begin    100.times do      100.times do        100.times do          number = rand(10000)          # comes out of all of the loops           # and goes to catch statement          throw :divide, 10 if number == 0        end      end    end    number # set gfg = number if    # no exception is thrownendputs gfg
Output :
10

if number is 0 even once in the loops we get 10 otherwise we get the number .
Picked
Ruby-Exception-handling
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Print Strings without Quotes in R Programming - noquote() Function - GeeksforGeeks

01 Jun, 2020
noquote() function in R Language is used to prints strings without quotes.
Syntax: noquote(x)
Parameters:x: character vector
Example 1:
# R program to illustrate# noquote function  # Getting letters without the help# of noquote() functionletters  # Getting letters with the help# of noquote() functionnoquote(letters)
Output :
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[1] a b c d e f g h i j k l m n o p q r s t u v w x y z

Example 2:
# R program to illustrate# noquote function  # Initializing a stringx <- "GFG"  # Getting the string without the help# of noquote() functionx  # Getting the string with the help# of noquote() functionnoquote(x)
Output:
[1] "GFG"
[1] GFG

R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
How to delete text from file using preg_replace() function in PHP ? - GeeksforGeeks

14 Feb, 2020
Given a file containing some elements and the task is to delete the content of the file using preg_replace() function. The preg_replace() function is searches the string pattern in the file and if string pattern found then it replace with the required string. In simple words it can modify the contents of a file.
Syntax:
preg_replace( $pattern,  $replacement, $subject);
Parameters:
$pattern: It contains the string we have to replace.
$replacement: It contains the string that will replace the existing string.
$subject: It contains the main string file where need to remove the string.
We have created a text file named as fruits.txtfruits.txt
mango
apple
papaya
guava
apple
grapes
mango
apple
Program 1: This program removes all the strings from the given file.
<?php  $a = 'fruits.txt';$b = file_get_contents('fruits.txt');echo "File contents before using "        . "preg_replace() function<br>";echo $b;echo "<br><br>File contents after using "        . "preg_replace() function<br> ";$c = preg_replace('/[a-z]/', '', $b);echo $c;file_put_contents($a, $c);?>
Output:
File contents before using preg_replace() function
mango apple papaya guava apple grapes mango apple

File contents after using preg_replace() function
Program 2: This program deletes a specific content from the file using preg_replace() function.
<?php  $a = 'fruits.txt';   $b = file_get_contents('fruits.txt');  echo "File contents before using "        + "preg_replace() function<br>";echo $b;  echo "<br><br>File contents after using "        + "preg_replace() function<br>";  $c = preg_replace('/[a]/', '', $b);echo $c;  file_put_contents($a, $c); ?>
Output:
File contents before using preg_replace() function
mango apple papaya guava apple grapes mango apple

File contents after using preg_replace() function
mngo pple ppy guv pple grpes mngo pple
Program 3: This program deletes the entire word from the file.
<?php  $a = 'fruits.txt';   $b = file_get_contents('fruits.txt');  echo "File contents before using "        . "preg_replace() function<br>";echo $b;  echo "<br><br>File contents after using "        . "preg_replace() function<br>";  $c = preg_replace('/apple/', '', $b);echo $c;  file_put_contents($a, $c); ?>
Output:
File contents before using preg_replace() function
mango apple papaya guava apple grapes mango apple

File contents after using preg_replace() function
mango papaya guava grapes mango
PHP-function
PHP-Misc
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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?
SQL Query to Count the Number of Rows in a Table - GeeksforGeeks

13 Apr, 2021
In this article, we are going to write an SQL query to count the number of rows in a table.  For is we will be making use of the count() function of SQL.  For this article, we will be making use of the Microsoft SQL Server as our database.
Let’s do the same by building a table inside the database and counting its rows. We will first create a database called “geeks” and then create an “Employee” table in this database and will execute our query on that table.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE geeks(
    id int(20) , 
    name varchar(200));
Output:
You can use the below statement to query the description of the created table:
EXEC sp_columns employees;
Use the below statement to add data to the Employee table:
INSERT INTO geeks(id,name) values(1,'nikhil');
INSERT INTO geeks(id,name) values(2,'kartik');
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
Syntax: SELECT COUNT(colmn_name) from table_name;
Example:
Using ‘ * ‘  we get all the rows as shown below:
SELECT * FROM geeks;
This will result in the below image:
The table we will be operating has 2 rows. So let’s feed in the query to get the no. of rows a specific column(say, id)as:
SELECT COUNT(id) from geeks;
Output:
We can even change the display name for displaying count:
SELECT COUNT(id) as id_count FROM geeks
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
MATLAB - Ideal Lowpass Filter in Image Processing - GeeksforGeeks

22 Apr, 2020
In the field of Image Processing, Ideal Lowpass Filter (ILPF) is used for image smoothing in the frequency domain. It removes high-frequency noise from a digital image and preserves low-frequency components.
It can be specified by the function-
Where,
 is a positive constant. ILPF passes all the frequencies within a circle of radius  from the origin without attenuation and cuts off all the frequencies outside the circle.
This  is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed as cutoff frequency.
 is the Euclidean Distance from any point (u, v) to the origin of the frequency plane, i.e,
Approach:
Step 1: Input – Read an imageStep 2: Saving the size of the input image in pixelsStep 3: Get the Fourier Transform of the input_imageStep 4: Assign the Cut-off Frequency Step 5: Designing filter: Ideal Low Pass FilterStep 6: Convolution between the Fourier Transformed input image and the filtering maskStep 7: Take Inverse Fourier Transform of the convoluted imageStep 8: Display the resultant image as output
Implementation in MATLAB:
% MATLAB Code | Ideal Low Pass Filter  % Reading input image : input_image input_image = imread('[name of input image file].[file format]');  % Saving the size of the input_image in pixels-% M : no of rows (height of the image)% N : no of columns (width of the image)[M, N] = size(input_image);  % Getting Fourier Transform of the input_image% using MATLAB library function fft2 (2D fast fourier transform)  FT_img = fft2(double(input_image));  % Assign Cut-off Frequency  D0 = 30; % one can change this value accordingly  % Designing filteru = 0:(M-1);idx = find(u>M/2);u(idx) = u(idx)-M;v = 0:(N-1);idy = find(v>N/2);v(idy) = v(idy)-N;  % MATLAB library function meshgrid(v, u) returns% 2D grid which contains the coordinates of vectors% v and u. Matrix V with each row is a copy % of v, and matrix U with each column is a copy of u[V, U] = meshgrid(v, u);  % Calculating Euclidean DistanceD = sqrt(U.^2+V.^2);  % Comparing with the cut-off frequency and % determining the filtering maskH = double(D <= D0);  % Convolution between the Fourier Transformed% image and the maskG = H.*FT_img;  % Getting the resultant image by Inverse Fourier Transform% of the convoluted image using MATLAB library function % ifft2 (2D inverse fast fourier transform)  output_image = real(ifft2(double(G)));  % Displaying Input Image and Output Imagesubplot(2, 1, 1), imshow(input_image),subplot(2, 1, 2), imshow(output_image, [ ]);
Input Image –
Output:
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction
Maximum value of signed char in C++ - GeeksforGeeks

06 Jan, 2021
In this article, we will discuss the signed char data type in C++.
Some properties of the signed char data type are:
It is generally used to store 8-bit characters.
Being a signed data type, it can store positive values as well as negative values.
Size of 8 bits is occupied where 1 bit is used to store the sign of the value.
A maximum value that can be stored in a signed char data type is typically 127, around 27 – 1(but is compiler dependent).
The maximum and minimum value that can be stored in a signed char is stored as a constant in climits header file and can be named as SCHAR_MAX and SCHAR_MIN respectively.
A minimum value that can be stored in a signed char data type is typically -128, i.e. around –27 (but is compiler dependent).
In case of overflow or underflow of data type, the value is wrapped around. For example, if -128 is stored in a signed char data type and 1 is subtracted from it, the value in that variable will become equal to 127. Similarly, in the case of overflow, the value will round back to -128.
Below is the program to get the highest value that can be stored in signed char in C++:
C++
// C++ program to obtain the maximum value// that we can store in signed char#include <climits>#include <iostream>using namespace std;  // Driver Codeint main(){      // From the constant of climits    // header file    signed char valueFromLimits = SCHAR_MAX;    cout << "Maximum value from "         << "climits constant: "         << (int)valueFromLimits         << '\n';      valueFromLimits = SCHAR_MIN;    cout << "Minimum value from "         << "climits constant: "         << (int)valueFromLimits         << '\n';      // Using the wrap around property    // of data types      // Initialize two variables one    // value with -1 as previous and    // one with 0 as present    signed char previous = -1;    signed char present = 0;      // Keep on increasing both values    // until the present increases to    // the max limit and wraps around to    // the negative value i.e., present    // becomes less the previous value    while (present > previous) {        previous++;        present++;    }      cout << "Maximum value using the "         << "wrap around property: "         << (int)previous << '\n';      cout << "Maximum value using the "         << "wrap around property: "         << (int)present;      return 0;}
Maximum value from climits constant: 127
Minimum value from climits constant: -128
Maximum value using the wrap around property: 127
Maximum value using the wrap around property: -128

C-Data Types
Data Type
Data Types
C++
C++ Programs
Data Type
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
C# Program to Create a Directory - GeeksforGeeks

30 Nov, 2021
A directory is a file system that stores file. Now our task is to create a directory in C#. We can create a directory by using the CreateDirectory() method of the Directory class. This method is used to create directories and subdirectories in a specified path. If the specified directory exists or the given path is invalid then this method will not create a directory. To use CreateDirectory() method we have to import the system.IO namespace in the program.
Syntax:
public static System.IO.DirectoryInfo CreateDirectory (string path);
Parameter: path is the directory path.
Return: This will return the object of the specified created directory.
Exception: It will throw the following exception:
IOException: This exception occurs when the directory specified by path is a file.
UnauthorizedAccessException: This exception occurs when the caller does not have the required permission.
ArgumentException: This exception occurs when the path is prefixed with, or contains, only a colon character (:).
ArgumentNullException: This exception occurs when the path is null.
PathTooLongException: This exception occurs when the specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: This exception occurs when the specified path is invalid 
NotSupportedException: This exception occurs when the path contains a colon character(:) that is not part of a drive label (“D:\”).
Example:
C#
// C# program to illustrate how// to create directoryusing System;using System.IO;  class GFG{      public static void Main(){          // Create directory named Sravan in C drive    // Using CreateDirectory() method    Directory.CreateDirectory("C:\\sravan");          Console.WriteLine("Created");}}
Output:
Created
CSharp-File-Handling
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
disabled - Django Form Field Validation - GeeksforGeeks

13 Feb, 2020
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments.
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.
Syntax
field_name = models.Field(option = value)
Illustration of disabled using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options.
from django import forms  class GeeksForm(forms.Form):    geeks_field = forms.CharField(disabled = True)
Add the geeks app to INSTALLED_APPS
# Application definition  INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'geeks',]
Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm  # Create your views here.def home_view(request):    context = {}    form = GeeksForm(request.POST or None)    context['form'] = form    if request.POST:        if form.is_valid():            temp = form.cleaned_data.get("geeks_field")            print(temp)    return render(request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "POST">    {% csrf_token %}    {{ form }}    <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path  # importing views from views..pyfrom .views import home_view  URLpatterns = [    path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field CharField is created with disabled attribute and field is uneditable by user.
NaveenArora
Django-forms
Python Django
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Best approach for “Keep Me Logged In” using PHP

10 May, 2020
We all have noticed the “Keep Me Logged In” checkbox in most of the websites we log in to. There are different ways and approaches to achieve this through code.
The best approach among those is saving the User information in the user browser as cookies. Basically, we have to store both the Username and the Password in the user’s browser as cookies. Then every time the page loads the session variable will be set. Hence the user can log in without having to enter the Username and Password again until the life of that cookie expires. The example code given below is the way how to remember password checkbox works through PHP.
Example
<?phpsession_start();if (isset($_SESSION["name"])){    header("location:home.php");}$connect = mysqli_connect("localhost", "root", "", "testing");if (isset($_POST["login"])){    if (!empty($_POST["user_name"]) && !empty($_POST["user_password"]))    {        $name = mysqli_real_escape_string($connect, $_POST["user_name"]);        $password = md5(mysqli_real_escape_string($connect,                                               $_POST["user_password"]));        $sql = "Select * from login where name = '" . $name . "                                   ' and password = '" . $password . "'";        $result = mysqli_query($connect, $sql);        $user = mysqli_fetch_array($result);        if ($user)        {            // Saving the username and password as cookies            if (!empty($_POST["rememberme"]))            {                  // Username is stored as cookie for 10 years as                // 10years * 365days * 24hrs * 60mins * 60secs                setcookie("user_login", $name, time() +                                    (10 * 365 * 24 * 60 * 60));                  // Password is stored as cookie for 10 years as                 // 10years * 365days * 24hrs * 60mins * 60secs                setcookie("user_password", $password, time() +                                    (10 * 365 * 24 * 60 * 60));                  // After setting cookies the session variable will be set                $_SESSION["name"] = $name;              }            else            {                if (isset($_COOKIE["user_login"]))                {                    setcookie("user_login", "");                }                if (isset($_COOKIE["user_password"]))                {                    setcookie("user_password", "");                }            }            header("location:home.php");        }        else        {            $message = "Invalid Login Credentials";        }    }    else    {        $message = "Both are Required Fields. Please fill both the fields";    }}?>
Output By understanding the above code by reading the comments and explanation you must able to execute the PHP code on the server with storing the Username and Password as cookies in the user’s browser. So in this way remember password task can be achieved.
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
Write From Home
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.