code-rag-bench/online-tutorials huggingface dataset:
How to clear all cookies using JavaScript ?

29 Jan, 2020
Cookies provide a way for a client and server to interact and pass information via HTTP. This enables the client to store state information despite using HTTP which is a stateless protocol. When a browser requests a web page from a server, the server services the request and “forgets” about the visit. But it passes some information to the user’s browser. The browser stores the information in the form of key=value pairs and also manages this information.
Cookie information is passed in the HTTP request header during every subsequent visit to the domain from the user’s browser.
Information like login details, consent, other preferences are used to enhance and customize the user experience.
HTTP cookies expire, the date and time are specified in the “expires” attribute. As a result, the browser automatically deletes the cookies when the date and time exceed the expiration date (and time). As this attribute is configurable*, it is possible to delete all the cookies by setting the “expiry” to any value that has already passed.
The cookie property of the current document is used to modify the attributes of the cookies buy using HTML DOM cookie Property. The document.cookie returns a single string of all the cookies separated by semicolons associated with the current document.
Syntax:
document.cookie = "key=value";
Code: The code below illustrates how cookies can be deleted using JavaScript. The code is run on an online editor to demonstrate that only cookies created by your site can be deleted by the code.
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>        Clear cookies using Javascript    </title></head>  <body>    <center>        <h1 style="color:green">             GeeksforGeeks        </h1>        <script type="text/javascript">            document.cookie = "1P_JAR=akjdsbJKHdjhbk";            document.cookie = "CONSENT=YES+IN.en+20170903-09-0";              function displayCookies() {                  var displayCookies = document.getElementById("display");                displayCookies.innerHTML = document.cookie;            }              function deleteCookies() {                var allCookies = document.cookie.split(';');                                // The "expire" attribute of every cookie is                 // Set to "Thu, 01 Jan 1970 00:00:00 GMT"                for (var i = 0; i < allCookies.length; i++)                    document.cookie = allCookies[i] + "=;expires="                    + new Date(0).toUTCString();                  displayCookies.innerHTML = document.cookie;              }        </script>        <button onclick="displayCookies()">Display Cookies</button>        <button onclick="deleteCookies()">Delete Cookies</button>        <p id="display"></p>    </center></body>  </html>   
Output:Note: If the attribute “HTTP” of a cookie is set to “True”, it is not possible to modify any of its attributes using JavaScript.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C Programs | Set 4

20 Jan, 2022
Predict the output of below programs 
Question 1  
c
#include‹stdio.h›int main(){    struct site    {        char name[] = "GeeksforGeeks";        int no_of_pages = 200;    };    struct site *ptr;    printf("%d",ptr->no_of_pages);    printf("%s",ptr->name);    getchar();    return 0;}
Output: Compiler errorExplanation: Note the difference between structure/union declaration and variable declaration. When you declare a structure, you actually declare a new data type suitable for your purpose. So you cannot initialize values as it is not a variable declaration but a data type declaration.Reference: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/SYNTAX/struct.htmlQuestion 2  
c
int main(){    char a[2][3][3] = {'g','e','e','k','s','f','o',                           'r','g','e','e','k','s'};    printf("%s ", **a);    getchar();    return 0;}
Output: geeksforgeeksExplanation: We have created a 3D array that should have 2*3*3 (= 18) elements, but we are initializing only 13 of them. In C when we initialize less no of elements in an array all uninitialized elements become ‘\0’ in case of char and 0 in case of integers. Question 3  
c
int main(){   char str[]= "geeks\nforgeeks";   char *ptr1, *ptr2;         ptr1 = &str[3];   ptr2 = str + 5;   printf("%c", ++*str - --*ptr1 + *ptr2 + 2);   printf("%s", str);     getchar();   return 0;}
Output: heejs forgeeksExplanation: Initially ptr1 points to ‘k’ and ptr2 points to ‘\n’ in “geeks\nforgeeks”. In print statement value at str is incremented by 1 and value at ptr1 is decremented by 1. So string becomes “heejs\nforgeeks” . First print statement becomes printf(“%c”, ‘h’ – ‘j’ + ‘\n’ + 2)‘h’ – ‘j’ + ‘\n’ + 2 = -2 + ‘\n’ + 2 = ‘\n’First print statements newline character. and next print statement prints “heejs\nforgeeks”. Question 4  
c
#include <stdio.h>int fun(int n){    int i, j, sum = 0;    for(i = 1;i<=n;i++)        for(j=i;j<=i;j++)            sum=sum+j;    return(sum);} int main(){    printf("%d", fun(15));    getchar();    return 0;}
Output: 120 Explanation: fun(n) calculates sum of first n integers or we can say it returns n(n+1)/2.Question 5  
c
#include <stdio.h>int main(){    int c = 5, no = 1000;    do {        no /= c;    } while(c--);     printf ("%d\n", no);    return 0;}
Output: Exception – Divide by zeroExplanation: There is a bug in the above program. It goes inside the do-while loop for c = 0 also. Be careful when you are using do-while loop like this!! 
notaverageuser
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python: Weight Conversion GUI using Tkinter

15 Jan, 2021
Prerequisites: Python GUI – tkinterPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. 
Steps to Create a Tkinter:  
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets.  
Below is what the GUI looks like:
Let’s create a GUI based weight converter that accepts a kilogram input value and converts that value to grams, pounds, and ounces when the user clicks the Convert button.
Below is the implementation. 
Python3
# Python program to  create a simple GUI # weight converter using Tkinter  from tkinter import *  # Create a GUI windowwindow = Tk()  # Function to convert weight# given in kg to grams, pounds# and ouncesdef from_kg():         # convert kg to gram    gram = float(e2_value.get())*1000         # convert kg to pound    pound = float(e2_value.get())*2.20462         # convert kg to ounce    ounce = float(e2_value.get())*35.274         # Enters the converted weight to    # the text widget    t1.delete("1.0", END)    t1.insert(END,gram)         t2.delete("1.0", END)    t2.insert(END,pound)         t3.delete("1.0", END)    t3.insert(END,ounce) # Create the Label widgetse1 = Label(window, text = "Enter the weight in Kg")e2_value = StringVar()e2 = Entry(window, textvariable = e2_value)e3 = Label(window, text = 'Gram')e4 = Label(window, text = 'Pounds')e5 = Label(window, text = 'Ounce') # Create the Text Widgetst1 = Text(window, height = 1, width = 20)t2 = Text(window, height = 1, width = 20)t3 = Text(window, height = 1, width = 20) # Create the Button Widgetb1 = Button(window, text = "Convert", command = from_kg) # grid method is used for placing# the widgets at respective positions# in table like structuree1.grid(row = 0, column = 0)e2.grid(row = 0, column = 1)e3.grid(row = 1, column = 0)e4.grid(row = 1, column = 1)e5.grid(row = 1, column = 2)t1.grid(row = 2, column = 0)t2.grid(row = 2, column = 1)t3.grid(row = 2, column = 2)b1.grid(row = 0, column = 2) # Start the GUIwindow.mainloop()
Output:
abhigoya
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Create Dictionary Of Tuples

10 Oct, 2021
In this article, we will discuss how to create a dictionary of tuples in Python.
Here we will pass keys as tuples inside a dictionary
Syntax:
{(tuple1):value,(tuple2):value,.........,(tuple3):value}
Here tuple is a collection of elements that work as a key for some value
Example: Python program to create a dictionary of tuples with a tuple as keys
Python3
# tuple of favourite food as key# value is name of studentdata = {("chapathi", "roti"): 'Bobby',         ("Paraota", "Idly", "Dosa"): 'ojaswi'}  # displaydata
Output:
{('Paraota', 'Idly', 'Dosa'): 'ojaswi', ('chapathi', 'roti'): 'Bobby'}
Here we will pass values as tuples inside a dictionary
Syntax:
{key:(tuple),key :(tuple2).........,key:(tuple)}
Here tuple is a collection of elements that represent some value for some key.
Example: Python program to create dictionary of tuples with tuple as values
Python3
# tuple of favourite food as value# key is name of studentdata = {'Bobby': ("chapathi", "roti"),         'ojaswi': ("Paraota", "Idly", "Dosa")}  # displaydata
Output:
{'Bobby': ('chapathi', 'roti'), 'ojaswi': ('Paraota', 'Idly', 'Dosa')}
Here we will create a dictionary from nested tuples and for that we need to pass two values in each tuple one will represent key and the other its corresponding value in the dictionary.
Syntax:
dict((value, key) for key,value in nested_tuple)
Example: Create a dictionary from tuples
Python3
# one value is age of student# second value is student namedata = ((24, "bobby"), (21, "ojsawi"))  # convert into dictionaryfinal = dict((value, key) for key, value in data)  # displayprint(final)
Output:
{'bobby': 24, 'ojsawi': 21}
Picked
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plot a black-and-white binary map in Matplotlib

To plot black-and-white binary map in matplotlib, we can create and add two subplots to the current figure using subplot() method, where nrows=1 and ncols=2. To display the data as a binary map, we can use greys colormap in imshow() method.
Create data using numpy
Add two sublots, nrows=1 and ncols=2. Consider index 1.
To show colored image, use imshow() method.
Add title to the colored map.
Add a second subplot at index 2.
To show the binary map, use show() method with Greys colormap.
To adjust the padding between and around the subplots, use tight_layout() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
plt.subplot(121)
plt.imshow(data)
plt.title("Colored Image")
plt.subplot(122)
plt.imshow(data, cmap='Greys_r', interpolation='nearest')
plt.title("Greys Image")
plt.tight_layout()
plt.show()
Algorithms | Sorting | Question 23 - GeeksforGeeks

19 Nov, 2018
Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this:
2  5  1  7  9  12  11  10 
Which statement is correct?(A) The pivot could be either the 7 or the 9.(B) The pivot could be the 7, but it is not the 9(C) The pivot is not the 7, but it could be the 9(D) Neither the 7 nor the 9 is the pivot.Answer: (A)Explanation: 7 and 9 both are at their correct positions (as in a sorted array). Also, all elements on left of 7 and 9 are smaller than 7 and 9 respectively and on right are greater than 7 and 9 respectively.Quiz of this Question
Algorithms-Sorting-Quiz
Sorting Quiz
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Bit Algorithms | Question 3
Algorithms | Bit Algorithms | Question 2
Algorithms | Bit Algorithms | Question 1
Data Structures and Algorithms | Set 38
Algorithms | Divide and Conquer | Question 2
Algorithms | Divide and Conquer | Question 4
Algorithms | Dynamic Programming | Question 7
Nuclei - Fast and Customizable Vulnerability Scanner - GeeksforGeeks

28 Jul, 2021
Nuclei is a Fast and Customizable Vulnerability Scanner. Nuclei tool is Golang Language-based tool used to send requests across multiple targets based on nuclei templates leading to zero false positive or irrelevant results and provides fast scanning on various hosts. Nuclei have built-in support to automatically update the templates to their newer version with more data. Nuclei-templates projects provide a regular Updates list to ready-to-use templates regularly. Nuclei offer to scan for various protocols, including DNS, HTTP, TCP, and many more. All kinds of security checks can be performed using nuclei templates.
Note: As Nuclei is a Golang language-based tool, so you need to have a Golang environment on your system.
Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command.
go version
Step 2: Get the Nuclei repository or clone the Nuclei tool from Github, use the following command.
sudo GO111MODULE=on go get -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei
Step 3: Copy the Nuclei tool in the bin directory so we can easily use the tool without running the tool manually by golang, use the following command.
sudo cp /root/go/bin/nuclei /usr/local/go/bin/
Step 4: Update the Nuclei templates, use the following command.
sudo nuclei -update-templates
Step 5: Check the help menu page to get a better understanding of the Nuclei tool, use the following command.
nuclei -h
Example 1: Running single template
nuclei -u http://testphp.vulnweb.com/ -t technologies/ngix-version.yaml
Example 2: Running multiple templates with speed.
nuclei -u http://example.com -t cves/ -t exposures/
Example 3: Scanning for CVEs on a given list of URLs.
nuclei -l target_urls.txt -t cves/
Example 4: Excluding single template.
nuclei -u https://evil.com -t cves/ - evclude-templates cves/2020/
Example 5: Excluding single template.
nuclei -u http://example.com -exclude-templates exposed-panels/ -exclude-templates technologies/
Example 6: Excluding templates with a single tag.
nuclei -u https://facebook.com -t cves/ -etags xss
Example 7: Excluding templates with multiple tags.
nuclei -u geeksforgeeks.org -t cves/ -etags sqli.rce
Example 8: Running blocked templates.
nuclei -l target_urls.txt -include-tags iot,misc,fuzz
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Fabric.js Image scaleX Property - GeeksforGeeks

29 Jan, 2021
Fabric.js is a JavaScript library that is used to work with canvas. The canvas Image is one of the class of fabric.js that is used to create Image instances. The Image in Fabric.js is movable and can be stretched according to requirement. In this article, we will be using the scaleX property to set the horizontal scale of the canvas Image.
Approach: First import the Fabric.js library. After importing the library, create a canvas block in the body tag which will contain the Image. After this, initialize an instance of Canvas and Image class provided by Fabric.js, use the scaleX property to set the default horizontal scale of the Image, and render this Image on the Canvas.
Syntax:
fabric.Image(image, {
  scaleX : number
});
Parameters: This function accepts a single parameter as mentioned above and described below:
scaleX: It specifies the default horizontal scale.
Example: This example uses Fabric.js to set the scaleX property of the canvas Image as shown in the below example:
HTML
<html> <head>     <!-- Adding the FabricJS library -->    <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script> </head> <body>     <h1 style="color: green;">         GeeksforGeeks     </h1>     <b>         Fabric.js | Image scaleX Property     </b>     <canvas id="canvas" width="400" height="300"            style="border:2px solid #000000">     </canvas>     <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png"        width="100" height="100" id="my-image"        style="display: none;">     <br>     <script>         // Creating the instance of canvas object         var canvas = new fabric.Canvas("canvas");           // Getting the Image         var img = document.getElementById('my-image');           // Creating the Image instance         var geeks = new fabric.Image(img, {            scaleX : 2.3        });           canvas.add(geeks);         canvas.centerObject(geeks);     </script> </body> </html>
Output:
Fabric.js
HTML
JavaScript
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Python | Pandas Series.as_matrix() - GeeksforGeeks

27 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.as_matrix() function is used to convert the given series or dataframe object to Numpy-array representation.
Syntax: Series.as_matrix(columns=None)
Parameter :columns : If None, return all columns, otherwise, returns specified columns.
Returns : values : ndarray
Example #1: Use Series.as_matrix() function to return the numpy-array representation of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
City 1    New York
City 2     Chicago
City 3     Toronto
City 4      Lisbon
City 5         Rio
dtype: object
Now we will use Series.as_matrix() function to return the numpy array representation of the given series object.
# return numpy array representationresult = sr.as_matrix()  # Print the resultprint(result)
Output :
['New York' 'Chicago' 'Toronto' 'Lisbon' 'Rio']

As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object. Example #2 : Use Series.as_matrix() function to return the numpy-array representation of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None])  # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
2010-12-31 08:45:00    11.0
2011-12-31 08:45:00    21.0
2012-12-31 08:45:00     8.0
2013-12-31 08:45:00    18.0
2014-12-31 08:45:00    65.0
2015-12-31 08:45:00    18.0
2016-12-31 08:45:00    32.0
2017-12-31 08:45:00    10.0
2018-12-31 08:45:00     5.0
2019-12-31 08:45:00    32.0
2020-12-31 08:45:00     NaN
Freq: A-DEC, dtype: float64
Now we will use Series.as_matrix() function to return the numpy array representation of the given series object.
# return numpy array representationresult = sr.as_matrix()  # Print the resultprint(result)
Output :
[ 11.  21.   8.  18.  65.  18.  32.  10.   5.  32.  nan]
As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python 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
Accessing array out of bounds in C/C++

In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds.
A program that demonstrates this in C is given as follows.
 Live Demo
#include <stdio.h>
int main() {
   int arr[] = {1,2,3,4,5};
   printf("The elements of array : ");
   for(int i = 0; i<6; i++)
   printf(" %d",arr[i]);
   return 0;
}
The output of the above program is as follows.
The elements of array : 1 2 3 4 5 32765
Now let us understand the above program.
The array arr has assigned values only till subscript 4. So when the array elements are printed, arr[5] results in a garbage value. The code snippet that shows this is as follows.
int arr[] = {1,2,3,4,5};
printf("The elements of array : ");
for(int i = 0; i<6; i++)
printf(" %d",arr[i]);
list remove() function in C++ STL - GeeksforGeeks

20 Jun, 2018
The list::remove() is a built-in function in C++ STL which is used to remove elements from a list container. It removes elements comparing to a value. It takes a value as the parameter and removes all the elements from the list container whose value is equal to the value passed in the parameter of the function.
Syntax:
list_name.remove(val) 

Parameters: This function accepts a single parameter val which refers to the value of elements needed to be removed from the list. The remove() function will remove all the elements from the list whose value is equal to val.
Return Value: This function does not returns any value.
Below program illustrates the list::remove() function.
// CPP program to illustrate the// list::remove() function#include <bits/stdc++.h>using namespace std;  int main(){    // Creating a list    list<int> demoList;      // Add elements to the List    demoList.push_back(10);    demoList.push_back(20);    demoList.push_back(20);    demoList.push_back(30);    demoList.push_back(40);      // List before removing elements    cout << "List before removing elements: ";    for (auto itr = demoList.begin();         itr != demoList.end(); itr++) {        cout << *itr << " ";    }      // delete all elements with value 20    demoList.remove(20);      // List after removing elements    cout << "\nList after removing elements: ";    for (auto itr = demoList.begin();         itr != demoList.end(); itr++) {        cout << *itr << " ";    }      return 0;}
List before removing elements: 10 20 20 30 40 
List after removing elements: 10 30 40

Note: This function works in linear time complexity.
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
Map in C++ Standard Template Library (STL)
Iterators in C++ STL
C++ Classes and Objects
Operator Overloading in C++
Multidimensional Arrays in C / C++
Constructors in C++
Object Oriented Programming in C++
Virtual Function in C++
Java Substring Comparisons

Following is an example which compares Strings and portion of strings in Java? Explain with an example.
Live Demo
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials point";
      String str2 = str1.substring(10);
      int result = str1.compareTo(str2);
      // prints the return value of the comparison
      if (result < 0) {
         System.out.println("str1 is greater than str2");
      }else if (result == 0) {
         System.out.println("str1 is equal to str2");
      }else {
         System.out.println("str1 is less than str2");
      }
   }
}
str1 is less than str2
How to create a TreeMap in reverse order in Java - GeeksforGeeks

25 Oct, 2019
By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.reverseOrder() method in Java and display the elements in descending order of keys.
The Collections.reverseOrderS() method in Java returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort any list or any other collection in reverse order of user defined Comparator.
Examples:
// Insert elements to the TreeMap

Input : treemap.put("1", "Welcome");
             treemap.put("2", "to");
             treemap.put("3", "the");
             treemap.put("4", "Geeks");
             treemap.put("5", "Community");

// Elements should be printed in reverse order
// of their insertion
Output : 5: Community
               4: Geeks
               3: the
               2: to
               1: Welcome

Below program shows how to traverse a TreeMap in reverse order:
// Java program to traverse a TreeMap// in reverse orderimport java.util.*;  class GFG {    public static void main(String args[])    {        // Map to store the elements        Map<String, String> treemap =                new TreeMap<String, String>(Collections.reverseOrder());          // Put elements to the map        treemap.put("1", "Welcome");        treemap.put("2", "to");        treemap.put("3", "the");        treemap.put("4", "Geeks");        treemap.put("5", "Community");          Set set = treemap.entrySet();        Iterator i = set.iterator();          // Traverse map and print elements        while (i.hasNext()) {            Map.Entry me = (Map.Entry)i.next();            System.out.print(me.getKey() + ": ");            System.out.println(me.getValue());        }    }}
5: Community
4: Geeks
3: the
2: to
1: Welcome

nidhi_biet
Java-Collections
Java-Map-Programs
java-TreeMap
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Collections in Java
Initializing a List in Java
Overriding in Java
How to create five equal columns in Bootstrap ? - GeeksforGeeks

19 Jun, 2019
Creating any number of equal columns in a ‘row’ was never as easier as it is now of Bootstrap 4.0+. With the introduction of ‘flexbox’ approach to the grid system, designers don’t have to worry about adding additional CSS to make it work. Here’s how it is done.
Go to the Bootstrap site and get the latest Bootstrap files onto your computer.
Write a basic HTML template using these files.
Once everything is set up, create a simple ‘container’ div inside <body> tag.
Inside the ‘container’, create another div with class ‘row’ and as the name suggests, we are creating a row for handling columns. Populate the ‘row’ div with 5 divs with class ‘col’. Because Bootstrap 4.0+ grid system has now shifted to Flexbox, the columns will arrange by themselves into five equally sized DOM elements.
Example:
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <meta name="viewport"          content="width=device-width,                    initial-scale=1,                   shrink-to-fit=no">      <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />      <title>5 cols a row</title>      <style>        .row .col {            height: 100px;            background: green;        }    </style></head>  <body>      <div class="container px-5 py-5">        <div class="row">            <div class="col mx-1">1</div>            <div class="col mx-1">2</div>            <div class="col mx-1">3</div>            <div class="col mx-1">4</div>            <div class="col mx-1">5</div>        </div>    </div>      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js">  </script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js">  </script></body>  </html>
To distinguish between the columns, a small margin is added to each of the columns.
Output:
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
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
firstof - Django Template Tags - GeeksforGeeks

27 Dec, 2021
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, firstof, etc. This article revolves about how to use firstof tag in Templates. firstof tag Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”. 
Syntax
{% firstof var1 var2 var3... %}
Example
{% firstof var1 var2 var3 %}
This is equivalent to: 
{% if var1 %}
    {{ var1 }}
{% elif var2 %}
    {{ var2 }}
{% elif var3 %}
    {{ var3 }}
{% endif %}
One can also use a literal string as a fallback value in case all passed variables are False: 
{% firstof var1 var2 var3 "fallback value" %}
 
Illustration of How to use firstof tag in Django templates 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 ?
Now create a view through which we will access the template, In geeks/views.py,  
Python3
# import Http Response from django# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request):    # create a dictionary    context = {        "var1":None,        "var2":None,        "var3":"GeeksForGeeks"    }    # return response    return render(request, "geeks.html", context)
Create a url path to map to this view. In geeks/urls.py, 
Python3
from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [    path('', geeks_view),]
Create a template in templates/geeks.html.  
html
<h3>Variable displayed : </h3> {% firstof var1 var2 var3 %}
Let’s check if data is displayed from the third variable in geeks.html  
 
This tag auto-escapes variable values. You can disable auto-escaping with:  
{% autoescape off %}
    {% firstof var1 var2 var3 "fallback value" %}
{% endautoescape %}
Or if only some variables should be escaped, you can use: 
{% firstof var1 var2|safe var3 "fallback value"|safe %}
You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable. 
surindertarika1234
Django-templates
Python Django
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 | String startswith() - GeeksforGeeks

11 Jan, 2018
The startswith() method returns True if a string starts with the given prefix otherwise returns False.
Syntax :
str.startswith(prefix, start, end)

Parameters :
prefix : prefix ix nothing but a string which needs to be checked.
start : Starting position where prefix is needs to be checked within the string.
end : Ending position where prefix is needs to be checked within the string.

NOTE : If start and end index is not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indes is not included in our search.
Returns :
It returns True if strings starts with the given
prefix otherwise returns False.

Examples:
Input : text = "geeks for geeks."
        result = text.startswith('for geeks')
Output : False

Input : text = "geeks for geeks."
        result = text.startswith('geeks', 0)
Output : True

Error : ValueError : This error is raised in the case when the argument string is not found in the target string
# Python code shows the working of# .startsswith() function   text = "geeks for geeks."   # returns Falseresult = text.startswith('for geeks')print (result)   # returns Trueresult = text.startswith('geeks')print (result)   # returns Falseresult = text.startswith('for geeks.')print (result)   # returns Trueresult = text.startswith('geeks for geeks.')print (result)
Output:
False
True
False
True

python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to copy readonly and hidden files/folders in the PowerShell?

To copy the readonly and hidden items from one location to another, you need to use the –Force parameter with Copy-Item cmdlet.
When you run the command without Force parameter for the readonly/hidden files, you will get the error. An example is given below.
Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\
PS C:\WINDOWS\system32> Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\
Copy-Item : Access to the path 'D:\TempContent\Readonlyfile.txt' is denied.
At line:1 char:1
+ Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo : PermissionDenied: (D:\Temp\Readonlyfile.txt:FileInfo) [Copy-Item], UnauthorizedAccessException
   + FullyQualifiedErrorId : CopyFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
When you add the –Force parameter in the cmdlet, it can copy the readonly/ hidden files as well.
An example is given below for the readonly file.
Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ -Force -PassThru
PS C:\WINDOWS\system32> Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ -Force -PassThru
    Directory: D:\TempContent
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---       13-01-2020     18:19              0 Readonlyfile.txt
The below example is for the Hidden file.
Copy-Item D:\Temp\hiddenfile.xlsx -Destination D:\TempContent\ -Force -PassThru
PS C:\WINDOWS\system32> Copy-Item D:\Temp\hiddenfile.xlsx -Destination D:\TempContent\ -Force -PassThru
    Directory: D:\TempContent
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a-h--       13-12-2019     09:52           6182 hiddenfile.xlsx
Function Wrappers in Python - GeeksforGeeks

22 Jun, 2020
Wrappers around the functions are also knows as decorators which are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
Syntax:
@wrapper
def function(n):
    statements(s)
This is also similar to
def function(n):
    statement(s)

function = wrapper(function)
Let’s see the below examples for better understanding.Example 1:
# defining a decorator def hello_decorator(func):         # inner1 is a Wrapper function in      # which the argument is called             # inner function can access the outer local     # functions like in this case "func"     def inner1():         print("Hello, this is before function execution")             # calling the actual function now         # inside the wrapper function.         func()             print("This is after function execution")                 return inner1         # defining a function, to be called inside wrapper def function_to_be_used():     print("This is inside the function !!")         # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used)         # calling the function function_to_be_used() 
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Example 2: Let’s define a decorator that count the time taken by the function for execution.
import time    def timeis(func):    '''Decorator that reports the execution time.'''      def wrap(*args, **kwargs):        start = time.time()        result = func(*args, **kwargs)        end = time.time()                  print(func.__name__, end-start)        return result    return wrap  @timeisdef countdown(n):    '''Counts down'''    while n > 0:        n -= 1  countdown(5)countdown(1000)
Output:
countdown 1.6689300537109375e-06
countdown 5.507469177246094e-05
It’s critical to emphasize that decorators generally do not alter the calling signature or return value of function being wrapped. The use of *args and**kwargs is there to make sure that any input arguments can be accepted. The return value of a decorator is almost always the result of calling func(*args, **kwargs), where func is the original unwrapped function.
Please refer Decorators in Python for more details.
Python Decorators
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
Python String | replace()
Reading and Writing to text files in Python
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
strupr() function in c - GeeksforGeeks

28 Sep, 2018
The strupr( ) function is used to converts a given string to uppercase.
Syntax:
char *strupr(char *str);

Parameter:
str: This represents the given string which we want to convert into uppercase.
Returns: It returns the modified string obtained after converting the characters of the given string str to uppercase.
Below programs illustrate the strupr() function in C:
Example 1:-
// c program to demonstrate// example of strupr() function.#include<stdio.h>#include<string.h>  int main(){    char str[ ] = "geeksforgeeks is the best";    //converting the given string into uppercase.    printf("%s\n", strupr (str));    return  0;}
Output:
GEEKSFORGEEKS IS THE BEST

Example 2:-
// c program to demonstrate// example of strupr() function.  #include<stdio.h>#include <string.h>  int main(){  char str[] = "CompuTer ScienCe PoRTAl fOr geeKS";    printf("Given string is: %s\n", str);    printf("\nstring after converting to the uppercase is: %s", strupr(str));  return 0;}
Output:
Given string is: CompuTer ScienCe PoRTAl fOr geeKS

string after converting to the uppercase is: COMPUTER SCIENCE PORTAL FOR GEEKS

Note : This is a non-standard function that works only with older versions of Microsoft C.
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Lexicographic rank of a string using STL - GeeksforGeeks

12 Apr, 2019
You are given a string, find its rank among all its permutations sorted lexicographically.
Examples:
Input : str[] = "acb"
Output : Rank = 2

Input : str[] = "string"
Output : Rank = 598

Input : str[] = "cba"
Output : Rank = 6

We have already discussed solutions to find Lexicographic rank of string
In this post, we use the STL function “next_permutation ()” to generate all possible permutations of the given string and, as it gives us permutations in lexicographic order, we will put an iterator to find the rank of each string. While iterating when Our permuted string becomes identical to the original input string, we break from the loop and the iterator value for the last iteration is our required result.
// C++ program to print rank of // string using next_permute()#include <bits/stdc++.h>using namespace std;   // Function to print rank of string// using next_permute()int findRank(string str){    // store original string    string orgStr = str;      // Sort the string in lexicographically    // ascending order    sort(str.begin(), str.end());       // Keep iterating until    // we reach equality condition    long int i = 1;    do {        // check for nth iteration        if (str == orgStr)            break;           i++;    } while (next_permutation(str.begin(), str.end()));       // return iterator value    return i;}   // Driver codeint main(){    string str = "GEEKS";    cout << findRank(str);    return 0;}
Output:
25

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
number-theory
STL
Combinatorial
Strings
number-theory
Strings
Combinatorial
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Generate all possible combinations of at most X characters from a given array
Given number of matches played, find number of teams in tournament
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks

27 Jul, 2021
Which of the following statements are true?
I. Shortest remaining time first scheduling may cause starvation
II. Preemptive scheduling may cause starvation
III. Round robin is better than FCFS in terms of response time
(A) I only(B) I and III only(C) II and III only(D) I, II and IIIAnswer: (D)Explanation: I) Shortest remaining time first scheduling is a pre-emptive version of shortest job scheduling. In SRTF, job with the shortest CPU burst will be scheduled first. Because of this process, It may cause starvation as shorter processes may keep coming and a long CPU burst process never gets CPU.
II) Pre-emptive just means a process before completing its execution is stopped and other process can start execution. The stopped process can later come back and continue from where it was stopped. In pre-emptive scheduling, suppose process P1 is executing in CPU and after some time process P2 with high priority then P1 will arrive in ready queue then p1 is pre-empted and p2 will brought into CPU for execution. In this way if process which is arriving in ready queue is of higher priority then p1, then p1 is always pre-empted and it may possible that it suffer from starvation.
III) round robin will give better response time then FCFS ,in FCFS when process is executing ,it executed up to its complete burst time, but in round robin it will execute up to time quantum. So Round Robin Scheduling improves response time as all processes get CPU after a specified time.
So, I,II,III are true which is option (D).
Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.htmlhttps://www.geeksforgeeks.org/operating-systems-set-7/
This solution is contributed by Nitika Bansal
Watch GeeksforGeeks Video Explanation :
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:21 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90