code-rag-bench/online-tutorials huggingface dataset:
PriorityQueue size() Method in Java

10 Dec, 2018
The Java.util.PriorityQueue.size() method is used to get the size of the PriorityQueue or the number of elements present in the PriorityQueue.
Syntax:
Priority_Queue.size()

Parameters: This method does not takes any parameter.
Return Value: The method returns the size or the number of elements present in the PriorityQueue.
Below programs illustrate the Java.util.PriorityQueue.size() method:Program 1:
// Java code to illustrate size()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<String> queue = new PriorityQueue<String>();          // Use add() method to add elements into the Queue        queue.add("Welcome");        queue.add("To");        queue.add("Geeks");        queue.add("For");        queue.add("Geeks");          // Displaying the PriorityQueue        System.out.println("PriorityQueue: " + queue);          // Displaying the size of the PriorityQueue        System.out.println("The size of the queue is: " + queue.size());    }}
PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The size of the queue is: 5

Program 2:
// Java code to illustrate size()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();          // Use add() method to add elements into the Queue        queue.add(10);        queue.add(15);        queue.add(30);        queue.add(20);        queue.add(5);        queue.add(18);          // Displaying the PriorityQueue        System.out.println("PriorityQueue: " + queue);          // Displaying the size of the PriorityQueue        System.out.println("The size of the queue is: " + queue.size());    }}
PriorityQueue: [5, 10, 18, 20, 15, 30]
The size of the queue is: 6

Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sort nested dictionary by key

11 May, 2020
Sorting has quite vivid applications and sometimes, we might come up with the problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let’s discuss certain ways in which this can be performed.
Method #1 : Using OrderedDict() + sorted()
This task can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed.
# Python3 code to demonstrate# Sort nested dictionary by key# using OrderedDict() + sorted()from collections import OrderedDictfrom operator import getitem  # initializing dictionarytest_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},             'Akshat' : {'roll' : 54, 'marks' : 12},              'Akash' : { 'roll' : 12, 'marks' : 15}}  # printing original dictprint("The original dictionary : " + str(test_dict))  # using OrderedDict() + sorted()# Sort nested dictionary by keyres = OrderedDict(sorted(test_dict.items(),       key = lambda x: getitem(x[1], 'marks')))  # print resultprint("The sorted dictionary by marks is : " + str(res))
The original dictionary : {‘Nikhil’: {‘roll’: 24, ‘marks’: 17}, ‘Akash’: {‘roll’: 12, ‘marks’: 15}, ‘Akshat’: {‘roll’: 54, ‘marks’: 12}}The sorted dictionary by marks is : OrderedDict([(‘Akshat’, {‘roll’: 54, ‘marks’: 12}), (‘Akash’, {‘roll’: 12, ‘marks’: 15}), (‘Nikhil’, {‘roll’: 24, ‘marks’: 17})])
 
Method #2 : Using sorted()
We can achieve the above result better if we just use the sorted function as it returns the result in a more usable format, dict and performs exactly the desired task.
# Python3 code to demonstrate# Sort nested dictionary by key# using sorted()  # initializing dictionarytest_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},             'Akshat' : {'roll' : 54, 'marks' : 12},              'Akash' : { 'roll' : 12, 'marks' : 15}}  # printing original dictprint("The original dictionary : " + str(test_dict))  # using sorted()# Sort nested dictionary by keyres = sorted(test_dict.items(), key = lambda x: x[1]['marks'])  # print resultprint("The sorted dictionary by marks is : " + str(res))
The original dictionary : {‘Nikhil’: {‘marks’: 17, ‘roll’: 24}, ‘Akshat’: {‘marks’: 12, ‘roll’: 54}, ‘Akash’: {‘marks’: 15, ‘roll’: 12}}The sorted dictionary by marks is : [(‘Akshat’, {‘marks’: 12, ‘roll’: 54}), (‘Akash’, {‘marks’: 15, ‘roll’: 12}), (‘Nikhil’, {‘marks’: 17, ‘roll’: 24})]
Python dictionary-programs
Python-nested-dictionary
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert a character data frame to numeric data frame in R?

Sometimes numerical values are recorded as character values and we need to convert them to numeric type before starting our analysis. This is also possible for a whole data frame in R. Therefore, we can use sapply function to convert the columns of the data frame to numeric type and save the output in a data frame by reading it with as.data.frame.
Consider the below data frame −
 Live Demo
x<−sample(c("1","2","3"),20,replace=TRUE)
df1<−data.frame(x)
df1
   x
1  2
2  2
3  2
4  1
5  2
6  3
7  1
8  2
9  2
10 2
11 1
12 1
13 2
14 2
15 1
16 1
17 3
18 2
19 3
20 1
Checking the structure of df1 −
str(df1)
'data.frame': 20 obs. of 1 variable:
$ x: chr "2" "2" "2" "1" ...
Converting the data type of columns of df1 to numeric data type −
df1<−as.data.frame(sapply(df1,as.numeric))
str(df1)
'data.frame': 20 obs. of 1 variable:
$ x: num 2 2 2 1 2 3 1 2 2 2 ...
 Live Demo
y1<−sample(c("254","324","220","301"),20,replace=TRUE)
df2<−data.frame(y1)
df2
   y1
1  324
2  254
3  220
4  254
5  220
6  220
7  324
8  254
9  324
10 220
11 324
12 324
13 301
14 324
15 220
16 301
17 301
18 324
19 301
20 254
str(df2)
'data.frame': 20 obs. of 1 variable:
$ y1: chr "324" "254" "220" "254" ...
df2<−as.data.frame(sapply(df2,as.numeric))
str(df2)
'data.frame': 20 obs. of 1 variable:
$ y1: num 324 254 220 254 220 220 324 254 324 220 ...
What is the difference between static_cast<> and C style casting?

Here we will see what are the differences between static_cast<> and normal C style cast.
The normal cast like (int)x is C style typecasting where static_cast<int>(x) is used in C++.
This static_cast<>() gives compile time checking facility, but the C style casting does not support that. This static_cast<>() can be spotted anywhere inside a C++ code. And using this C++ cast the intensions are conveyed much better.
In C like cast sometimes we can cast some type pointer to point some other type data.
Like one integer pointer can also point character type data, as they are quite similar, only difference is character has 1-byte, integer has 4-bytes. In C++ the static_cast<>() is more strict than C like casting. It only converts between compatible types.
char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = (int*)&c; //4-byte
Since in a 4-byte pointer, it is pointing to 1-byte of allocated memory, it may generate runtime error or will overwrite some adjacent memory.
In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.
char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = static_cast<int>(&c);
This will generate compile time error.
GATE | GATE CS 2020 | Question 63

26 May, 2021
Consider a paging system that uses 1-level page table residing in main memory and a TLB for address translation. Each main memory access takes 100 ns and TLB lookup takes 20 ns. Each page transfer to/from the disk takes 5000 ns. Assume that the TLB hit ratio is 95%, page fault rate is 10%. Assume that for 20% of the total page faults, a dirty page has to be written back to disk before the required page is read from disk. TLB update time is negligible.
The average memory access time in ns (round off to 1 decimal places) is ___________ .
Note – This question was Numerical Type.(A) 154.5(B) 155(C) 755(D) 725Answer: (A)Explanation: Given,
M = 100 ns
T = 20 ns
D = 5000 ns

h = 0.95

p = 0.1, 
(1-p) = 0.9

d = 0.2, 
(1-d) = 0.8 
Therefore, average memory access time,
= h×(T+M) + (1-h)[(1-p)×2M + p[(1-d)[D+M] + d(2D+M)] + T]
= 0.95×(20+100) + (1-0.95)[(1-0.1)×200 + (0.1)[(1-0.2)[5000+100] + (0.2)(10000+100)] + 20]
= 154.5 (in ns) 
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get HTML Source of WebElement in Selenium WebDriver using Python.

We can get html source of a webelement with Selenium webdriver.We can get the innerHTML attribute to get the source of the web element.
The innerHTML is an attribute of a webelement which is equal to the text that is present between the starting and ending tag. The get_attribute method is used for this and innerHTML is passed as an argument to the method.
s = element.get_attribute('innerHTML')
We can obtain the html source of the webelement with the help of Javascript Executor. We shall utilize the execute_script method and pass arguments index.innerHTML and webelement whose html source is to be retrieved to the method.
s = driver.find_element_by_id("txt-search")
driver.execute_script("return arguments[0].innerHTML;",s)
Let us see the below html code of an element. The innerHTML of the element shall be − You are browsing the best resource for <b>Online Education</b>.
Code Implementation with get_attribute.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe"
# implicit wait applied
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and obtain innerHTML with get_attribute
l = driver.find_element_by_css_selector("h4")
print("HTML code of element: " + l.get_attribute('innerHTML'))
Code Implementation with Javascript Executor.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe"
# implicit wait applied
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and obtain innerHTML with execute_script
l = driver.find_element_by_css_selector("h4")
h= driver.execute_script("return arguments[0].innerHTML;",l)
print("HTML code of element: " + h)
HTML | DOM Location href Property

05 Jul, 2022
The Location href property in HTML is used to set or return the complete URL of the current page. The Location href property can also be used to set the href value point to another website or point to an email address. The Location href property returns a string which contains the entire URL of the page, including the protocol. 
Syntax:
It returns the href property.
location.href
It is used to set the href property.
location.href = URL
Below programs illustrate the Location href Property in HTML: 
Example 1: 
html
<!DOCTYPE html><html> <head>    <title>DOM Location href Property</title>    <style>        h1 {            color: green;        }                 h2 {            font-family: Impact;        }                 body {            text-align: center;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>DOM Location href Property</h2>    <p>      For returning the entire URL current page,      double click the "Return URL" button:    </p>    <button ondblclick="myhref()">Return URL</button>    <p id="href"></p>    <script>        function myhref() {            var h = location.href;            document.getElementById("href").innerHTML = h;        }    </script></body> </html>
Output:
  
After click on the button:
  
Example 2: Set the href value to point another URL of website. 
html
<!DOCTYPE html><html> <head>    <title>DOM Location href Property</title>    <style>        h1 {            color: green;        }                 h2 {            font-family: Impact;        }                 body {            text-align: center;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>DOM Location href Property</h2>    <p>      For redirecting to GeeksforGeeks homepage,      double click the "Redirect" button:    </p>    <button ondblclick="myhref()">Redirect</button>    <script>        function myhref() {            location.href =              "https://www.geeksforgeeks.org";        }    </script></body> </html>
Output:
  
After click on the button:
  
Supported Browsers: The browser supported by Location href Property are listed below:
Google Chrome 1
Edge 12
Internet Explorer 3
Firefox 1
Opera 12.1
Safari 1
geeksr3ap
HTML-DOM
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
NumberFormat Class in Java

09 Feb, 2022
NumberFormat is an abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales (US, India, Italy, etc.) have number formats and their names. NumberFormat helps you to format and parse numbers for any locale. 
Example: Suppose we have a double type number. But this double type number is represented in different ways in different countries. To represent a number according to various countries, we have to take the help of NumberFormat class like: 
double d = 123456.789;
For India, it is represented like 1,23,456.789
For US, it is represented like 123,456.789
For ITALY, it is represented like 123.456,789
Some Important Points About NumberFormat Class: 
NumberFormat class is present in java.text package, and it is an abstract class.
NumberFormat class implements Serializable, Cloneable.
NumberFormat is the direct child class of Format class.
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
Example:
Java
// Java Program to illustrate NumberFormat class use import java.text.*;import java.util.*; class NumberFormatDemo {    public static void main(String[] args)    {        double d = 123456.789;        NumberFormat nf            = NumberFormat.getInstance(Locale.ITALY);        System.out.println("ITALY representation of " + d                           + " : " + nf.format(d));    }}
ITALY representation of 123456.789 : 123.456,789
nishkarshgandhi
Java-Data Types
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to declare a local variable in Java?

Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
A local variable is the one which is declared within a method. The scope of this variable is within the method.
public abstract class Sample {
   public static void main(String args[]){
      int data = 4044;
      System.out.println(data);
   }
}
4044
How do I create a popup window in Tkinter?

Popup window in Tkinter can be created by defining the Toplevel(win) window. A Toplevel window manages to create a child window along with the parent window. It always opens above all the other windows defined in any application. We can create a top-level window or child window by initializing the object of Toplevel(parent). It inherits all the property of its parent window such as geometry, title, and width or height.
In this example, we will create a button that will open a Popup window above all the other windows.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter frame
win.geometry("750x270")

def open_popup():
   top= Toplevel(win)
   top.geometry("750x250")
   top.title("Child Window")
   Label(top, text= "Hello World!", font=('Mistral 18 bold')).place(x=150,y=80)

Label(win, text=" Click the Below Button to Open the Popup Window", font=('Helvetica 14 bold')).pack(pady=20)
#Create a button in the main Window to open the popup
ttk.Button(win, text= "Open", command= open_popup).pack()
win.mainloop()
Run the above code to display the output which contains a button and a Label Text.
When we click the "Open" button, it will open the popup window (top-level window) on the screen.
HTML | Marquee start method - GeeksforGeeks

20 Jan, 2022
The Marquee start method in HTML is used to start the scrolling. To stop the scrolling use stop() method.
Syntax:
Object.start()
Return value: This method has no return value.
Example:
<!DOCTYPE html><html>  <head>    <title>Marquee start method</title>    <style>        .main {            text-align: center;        }    </style></head>  <body>    <h1 style="color:green; text-align:center;">      GeeksforGeeks  </h1>    <div class="main">        <marquee id="marID"                  bgcolor="Green"                 direction="left"                  loop="">            Scrolling        </marquee>        <br />        <input type="button"               onclick="marID.start()"                value="Start">                <input type="button"                onclick="marID.stop()"                value="Stop">    </div></body>  </html>
Output:
Supported Browsers: The browsers supported by HTML Marquee start method are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
chhabradhanvi
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
How to auto-resize an image to fit a div container using CSS?
Design a web page using HTML and CSS
How to Show Images on Click using HTML ?
HTML Course | First Web Page | Printing Hello World
Express.js express.Router() Function
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Python Number abs() Method

Python number  method abs() returns absolute value of x - the (positive) distance between x and zero.
Following is the syntax for abs() method −
abs( x )

x − This is a numeric expression.
x − This is a numeric expression.
This method returns absolute value of x.
The following example shows the usage of abs() method.
#!/usr/bin/python

print "abs(-45) : ", abs(-45)
print "abs(100.12) : ", abs(100.12)
print "abs(119L) : ", abs(119L)
When we run above program, it produces following result −
abs(-45) :  45
abs(100.12) :  100.12
abs(119L) :  119


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Depth First Search (DFS) for a Graph

The Depth-First Search (DFS) is a graph traversal algorithm. In this algorithm, one starting vertex is given, and when an adjacent vertex is found, it moves to that adjacent vertex first and tries to traverse in the same manner.
It moves through the whole depth, as much as it can go, after that it backtracks to reach previous vertices to find the new path.
To implement DFS in an iterative way, we need to use the stack data structure. If we want to do it recursively, external stacks are not needed, it can be done internal stacks for the recursion calls.
Input:
The Adjacency matrix of a graph.
 
        A B C D E F
      A 0 1 1 1 0 0
      B 1 0 0 1 1 0
      C 1 0 0 1 1 0
      D 1 1 1 0 1 1
      E 0 1 0 1 0 1
      F 0 0 1 1 1 0

Output:
DFS Traversal: C F E B D A
dfs(vertices, start)
Input: The list of all vertices, and the start node.
Output: Traverse all nodes in the graph.
Begin
   initially make the state to unvisited for all nodes
   push start into the stack

   while stack is not empty, do
      pop element from stack and set to u
      display the node u

      if u is not visited, then
         mark u as visited
         for all nodes i connected to u, do
            if ith vertex is unvisited, then
               push ith vertex into the stack
               mark ith vertex as visited
         done
   done
End
#include<iostream>
#include<stack>
using namespace std;
#define NODE 6

typedef struct node {
   int val;
   int state; //status
}node;

int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0, 0},
   {1, 0, 0, 1, 1, 0},
   {1, 0, 0, 1, 0, 1},
   {1, 1, 1, 0, 1, 1},
   {0, 1, 0, 1, 0, 1},
   {0, 0, 1, 1, 1, 0}
};

void dfs(node *vertex, node start) {
   node u;
   stack<node> myStack;

   for(int i = 0; i<NODE; i++) {
      vertex[i].state = 0;   //not visited
   }

   myStack.push(start);
   while(!myStack.empty()) {
      //pop and print node
      u = myStack.top();
      myStack.pop();
      cout << char(u.val+'A') << " ";

      if(u.state != 1) {
         //update vertex status to visited
         u.state = 1;
         vertex[u.val].state = 1;

         for(int i = 0; i<NODE; i++) {
            if(graph[i][u.val]) {
               if(vertex[i].state == 0) {
                  myStack.push(vertex[i]);
                  vertex[i].state = 1;
               }
            }
         }
      }
   }
}

int main() {
   node vertices[NODE];
   node start;
   char s;

   for(int i = 0; i<NODE; i++) {
      vertices[i].val = i;
   }

   s = 'C';   //starting vertex C
   start.val = s-'A';
   cout << "DFS Traversal: ";
   dfs(vertices, start);
   cout << endl;
}
DFS Traversal: C F E B D A
How to do string interpolation in JavaScript?

JavaScript since ES6 has template string support which gives native support for string interpolation. These are called template literals. Template literals are string literals that allow embedded expressions. Template strings use back-ticks (``) rather than the single or double-quotes. A template string could thus be written as −
var greeting = `Hello World!`;
Template strings can use placeholders for string substitution using the
${ } syntax.
var name = "Brendan";
console.log('Hello, ${name}!');
This will give the following output −
Hello, Brendan!
Template literals and expressions
var a = 10;
var b = 10;
console.log(`The sum of ${a} and ${b} is ${a+b} `);
This will give the following output −
The sum of 10 and 10 is 20
Template literals and function expression
function fn() { return "Hello World"; }
console.log(`Message: ${fn()} !!`);
This will give the following output −
Message: Hello World !!
Template strings can contain multiple lines.
var multiLine = `
   This is
   a string
   with multiple
   lines`;
console.log(multiLine)
This will give the following output −
This is
a string
with multiple
line
Border Around Equation in LATEX - GeeksforGeeks

17 Mar, 2021
The Latex command to put the border (box) around an equation is as
\fbox or \boxed
Description :
\boxed command draws a box around argument. The argument is in text mode.
Example :
\boxed{sin\frac{x}{2} = \frac{1}{4}}
Output :
Next we can add the desire color to the border as
\color{colorName}
Description :
\color command set color of the font or the border around the box. The argument is the name of the color.
Example :
\color{green}\boxed{\color{black} x + y = 10}
Output :
Lastly let’s see the boxes filled with color through command as
\colorbox{colorName}{text}
Description :
\colorbox command fills the background color of the box with the argument. The argument is the name of the color.
Example :
\colorbox{green}{\color{white}Hello from GeeksForGeeks}
Output:
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Proof that vertex cover is NP complete
Brackets in Latex
Betweenness Centrality (Centrality Measure)
Introduction of Statistics and its Types
Mathematics | Introduction of Set theory
Python Program to check if a matrix is symmetric - GeeksforGeeks

11 Jan, 2022
A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row.
Examples: 
Input : 1 2 3
        2 1 4
        3 4 3
Output : Yes

Input : 3 5 8
        3 4 7
        8 5 3
Output : No
A Simple solution is to do following. 
1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not.  
Python
# Simple Python code for check a matrix is# symmetric or not.   # Fills transpose of mat[N][N] in tr[N][N]def transpose(mat, tr, N):    for i in range(N):        for j in range(N):            tr[i][j] = mat[j][i]   # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N):          tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ]    transpose(mat, tr, N)    for i in range(N):        for j in range(N):            if (mat[i][j] != tr[i][j]):                return False    return True   # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)):    print "Yes"else:    print "No"  # This code is contributed by Sachin Bisht
Output : 
 Yes
Time Complexity : O(N x N) Auxiliary Space : O(N x N)
An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i].  
Python
# Efficient Python code for check a matrix is# symmetric or not.  # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N):    for i in range(N):        for j in range(N):            if (mat[i][j] != mat[j][i]):                return False    return True   # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)):    print "Yes"else:    print "No"  # This code is contributed by Sachin Bisht
Output: 
Yes
Time Complexity : O(N x N) Auxiliary Space : O(1)
Please refer complete article on Program to check if a matrix is symmetric for more details!
Matrix
Python
Python Programs
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Flood fill Algorithm - how to implement fill() in paint?
Check for possible path in 2D matrix
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Output of C++ Program | Set 4 - GeeksforGeeks

27 Dec, 2016
Difficulty Level: Rookie
Predict the output of below C++ programs.
Question 1
#include<iostream>using namespace std;  int x = 10;void fun(){    int x = 2;    {        int x = 1;        cout << ::x << endl;     }}  int main(){    fun();    return 0;}
Output: 10If Scope Resolution Operator is placed before a variable name then the global variable is referenced. So if we remove the following line from the above program then it will fail in compilation.
  int x = 10;
Question 2
#include<iostream>using namespace std;class Point {private:    int x;    int y;public:    Point(int i, int j);  // Constructor};  Point::Point(int i = 0, int j = 0)  {    x = i;    y = j;    cout << "Constructor called";}  int main(){   Point t1, *t2;   return 0;}
Output: Constructor called.If we take a closer look at the statement “Point t1, *t2;:” then we can see that only one object is constructed here. t2 is just a pointer variable, not an object.
Question 3
#include<iostream>using namespace std;  class Point {private:    int x;    int y;public:    Point(int i = 0, int j = 0);    // Normal Constructor    Point(const Point &t); // Copy Constructor};  Point::Point(int i, int j)  {    x = i;    y = j;    cout << "Normal Constructor called\n";}  Point::Point(const Point &t) {   y = t.y;   cout << "Copy Constructor called\n";}  int main(){   Point *t1, *t2;   t1 = new Point(10, 15);   t2 = new Point(*t1);   Point t3 = *t1;   Point t4;   t4 = t3;   return 0;}
Output:Normal Constructor calledCopy Constructor calledCopy Constructor calledNormal Constructor called
See following comments for explanation:
Point *t1, *t2;   // No constructor callt1 = new Point(10, 15);  // Normal constructor callt2 = new Point(*t1);   // Copy constructor call Point t3 = *t1;  // Copy Constructor callPoint t4;   // Normal Constructor callt4 = t3;   // Assignment operator call
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12
PHP | DsCollection toArray() Function - GeeksforGeeks

23 Jan, 2019
The Ds\Collection::toArray() function is an inbuilt function in PHP which is used to converts the collections into array.
Syntax:
public Ds\Collection::toArray( void ) : array
Parameters: This function does not accepts any parameters.
Return Value: This function returns an array containing all collection elements.
Below programs illustrate the public Ds\Collection::toArray() function in PHP:
Example 1:
<?php   // Create a collection $collection = new \Ds\Vector([10, 15, 21, 13, 16, 18]);   // Use toArray() function to convert// collections to arrayvar_dump($collection->toArray());   ?> 
Output:
array(6) {
  [0] => int(10)
  [1] => int(15)
  [2] => int(21)
  [3] => int(13)
  [4] => int(16)
  [5] => int(18)
}
Example 2:
<?php   // Create a collection$collection = new \Ds\Vector([10, 15, 21, 13, 16, 18]);   // Display the collection element print_r($collection);   // Use toArray() function to convert // collection into array and print itprint_r($collection->toArray());   ?> 
Output:
Ds\Vector Object
(
    [0] => 10
    [1] => 15
    [2] => 21
    [3] => 13
    [4] => 16
    [5] => 18
)
Array
(
    [0] => 10
    [1] => 15
    [2] => 21
    [3] => 13
    [4] => 16
    [5] => 18
)
Reference: http://php.net/manual/en/ds-collection.toarray.php
PHP-DS\Collection
PHP-function
PHP
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 ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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?
Python - Variable Operations Dictionary update - GeeksforGeeks

22 Jun, 2021
Sometimes, while working with Python dictionaries we can have a problem in which we need to perform a population of dictionary values using assigned variables after certain operation among them. This can have application in day-day programming. Let’s discuss certain ways in which this task can be performed.Method #1 : Using lambda + dictionary comprehension The combination of above functions can be used to solve this problem. In this, we perform the assignment using dictionary comprehension and values computations using lambda functions. 
Python3
# Python3 code to demonstrate working of# Variable Operations Dictionary update# Using lambda + dictionary comprehension # helper functionshelper_fnc = {'Gfg': lambda: x + y,         'best': lambda: x * y} # initializing variablesx = 6y = 7 # Variable Operations Dictionary update# Using lambda + dictionary comprehensionres = {key: val() for key, val in hlper_fnc.items()} # printing resultprint("The Initialized dictionary : " + str(res))
The Initialized dictionary : {'best': 42, 'Gfg': 13}
 
 Method #2 : Using operators library This task can also be performed using above functionality. In this, we use inbuilt operations provided by the operator library to achieve this task. 
Python3
# Python3 code to demonstrate working of# Variable Operations Dictionary update# Using lambda + dictionary comprehensionfrom operator import add, mul # helper functionshelper_fnc = {'Gfg': add,         'best': mul} # initializing variablesx = 6y = 7 # Variable Operations Dictionary update# Using lambda + dictionary comprehensionres = {'Gfg' : hlper_fnc['Gfg'](x, y), 'best' : hlper_fnc['best'](x, y)} # printing resultprint("The Initialized dictionary : " + str(res))
The Initialized dictionary : {'best': 42, 'Gfg': 13}
 
surindertarika1234
Python dictionary-programs
Python
Python Programs
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
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert list into list of lists - GeeksforGeeks

30 Jul, 2019
Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists.
Examples:
Input : ['alice', 'bob', 'cara']
Output : [['alice'], ['bob'], ['cara']]

Input : [101, 202, 303, 404, 505] 
Output : [[101], [202], [303], [404], [505]]

 Approach #1 : Naive Approach
Use another list ‘res’ and a for a loop. Using split() method of Python we extract each element from the list in the form of the list itself and append it to ‘res’. Finally, return ‘res’. One drawback of this method is that it does not work with integer list as ‘int’ object has no attribute ‘split’.
# Python3 program to convert # list into a list of lists  def extractDigits(lst):    res = []    for el in lst:        sub = el.split(', ')        res.append(sub)          return(res)                  # Driver codelst = ['alice', 'bob', 'cara']print(extractDigits(lst))
[['alice'], ['bob'], ['cara']]

 Approach #2 : List comprehension
List comprehension is an efficient approach as it doesn’t make use of extra space. For each element ‘el’ in list, it simply appends [el] to the output list.
# Python3 program to convert # list into a list of lists  def extractDigits(lst):    return [[el] for el in lst]                  # Driver codelst = ['alice', 'bob', 'cara']print(extractDigits(lst))
[['alice'], ['bob'], ['cara']]

 Approach #3 : Python map()
The given code maps the function el:[el] for each item of the given iterable ‘lst’. Hence outputs each element as a list itself.
# Python3 program to convert # list into a list of lists  def extractDigits(lst):    return list(map(lambda el:[el], lst))                    # Driver codelst = ['alice', 'bob', 'cara']print(extractDigits(lst))
[['alice'], ['bob'], ['cara']]

ManasChhabra2
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to concrete a single Series into a string Python Pandas library?

Using pandas.Series.to_string() we can convert a single series into a string.Let’s take some examples and see how it’s gonna work.
Create a pandas Series using string dtype data, then convert it to a string.
# create a series
ds = pd.Series(["a", "b", "c", "a"], dtype="string")
print(ds) # display series
s = ds.to_string() # convert to string
print()
print(repr(s)) display converted output
The variable ds holds a pandas Series with all string data by defining dtype as a string. Then convert the series into a string by using the pandas.Series.to_string method, here we define it as ds.to_string(). Finally, the converted string is assigned to the s variable. And displayed output (variable s) by using the repr() function to return printable representational string.
0   a
1   b
2   c
3   a
dtype: string

'0   a\n1   b\n2   c\n3   a'
The first part of the above block represents the output of a series with dtype is a string, and the second part of the block represents the converted string output of a single pandas series.
In the above example, we converted a string dtype series to string, but we can convert series with any dtype. Let's take another example.
ds = pd.Series([1,2,3,3])
print(ds)
s = ds.to_string()
print()
print(repr(s))
In this example, it has only integer type data present in the pandas series. For that, directly declare a list of integers to the pd.Series() method and it will create a pandas Series. After that, convert the Series “ds” to string by using ds.to_string() method.
0   1
1   2
2   3
3   3
dtype: int64

'0   1\n1   2\n2   3\n3   3'
We can see the converted string from a single Series with int64 dtype data in the above block. Like this, we can concrete a single series into a string by using the pandas to_string method.
How to ignore using variable name as a literal while using push() in JavaScript?

To avoid using variable name as a literal, use square brackets. Following is the code −
var name = "David"
var putTheAllData = []
putTheAllData.push( { name: "The name is name will remain same" } )
putTheAllData.push( { [name]: "The name is David will be changed [name]"} )
console.log(putTheAllData);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo166.js. This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo166.js
[
   { name: 'The name is name will remain same' },
   { David: 'The name is David will be changed [name]' }
]
How to Find User Account Info and Login Details in Linux?

For the sysadmins, it is routine to monitor user details like who are active and who are not, who logged in in last 2 days, which users belong to a given group etc etc. To help these requirements, Linux provides below list of commands which can be used to gather various types of information about the users.
It gives the id details of users including the group id along with the secondary group IDs and names of a user choosen by the system. But you also ask for a specific user’sdeatils by giving the userid value in the command.
ubuntu@ubuntu:~$ id
ubuntu@ubuntu:~$ id 2112
Running the above code gives us the following result:
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=2112(uname1) gid=3421(uname1) groups=3421(uname1)
It displays the group names the currently logged in user belongs to.
ubuntu@ubuntu:~$ groups
Running the above code gives us the following result −
ubuntu adm cdrom sudo dip plugdev lpadmin sambashare
This command looks into passed file and gets the user details form there.
ubuntu@ubuntu:~$ getent passwd
Running the above code gives us the following result −
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
......
.........
The lslogins command displays details of the known users of the system.
ubuntu@ubuntu:~$ lslogins –u
Running the above code gives us the following result −
UID USER PROC PWD-LOCK PWD-DENY LAST-LOGIN GECOS
0 root 135 root
1000 ubuntu 70 23:04:25 ubuntu16LTS,,,
2112 uname1 0 storefront
9002 uname4 0 HR
It displays the current users logged in to the system and the processes they are running.
ubuntu@ubuntu:~$ w
Running the above code gives us the following result −
08:13:17 up 12:26, 1 user, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
ubuntu tty7 :0 23:04 12:58m 1:23 0.34s /sbin/upstart –user
What is the difference between Local Events and Global Events in jQuery?

Ajax requests produce a number of different events that you can subscribe to. There are two types of events:
Local Events
These are callbacks that you can subscribe to within the Ajax request object.
$.ajax({
   beforeSend: function(){
      // Handle the beforeSend event
   },
   complete: function(){
     // Handle the complete event
   }
   // ......
});
Global Events
These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. You can listen for these events like so:
$("#loading").bind("ajaxSend", function(){
   $(this).show();
 }).bind("ajaxComplete", function(){
   $(this).hide();
});
Global events can be disabled, for a particular Ajax request, by passing in the global option, like so:
$.ajax({
   url: "test.html",
   global: false,
   // ...
});
Heap queue (or heapq) in Python

Heap queue is a special tree structure in which each parent node is less than or equal to its child node. In python it is implemented using the heapq module. It is very useful is implementing priority queues where the queue item with higher weight is given more priority in processing.
A heap queue is created by using python’s inbuilt library named heapq. This library has the relevant functions to carry out various operations on a heap data structure. Below is a list of these functions.
heapify – This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted.
heappush – This function adds an element to the heap without altering the current heap.
heappop – This function returns the smallest data element from the heap.
heapreplace – This function replaces the smallest data element with a new value supplied in the function.
A heap is created by simply using a list of elements with the heapify function. In the below example we supply a list of elements and the heapify function rearranges the elements bringing the smallest element to the first position.
import heapq
H = [21,1,45,78,3,5]
# Use heapify to rearrange the elements
heapq.heapify(H)
print(H)
When the above code is executed, it produces the following result −
[1, 3, 5, 78, 21, 45]
Inserting a data element to a heap always adds the element at the last index. But you can apply heapify function again to bring the newly added element to the first index only if it smallest in value. In the below example we insert the number 8.
import heapq
H = [21,1,45,78,3,5]
# Covert to a heap
heapq.heapify(H)
print(H)
# Add element
heapq.heappush(H,8)
print(H)
When the above code is executed, it produces the following result −
[1, 3, 5, 78, 21, 45]
[1, 3, 5, 78, 21, 45, 8]
You can remove the element at first index by using this function. In the below example the function will always remove the element at the index position 1.
import heapq

H = [21,1,45,78,3,5]
# Create the heap

heapq.heapify(H)
print(H)

# Remove element from the heap
heapq.heappop(H)

print(H)
When the above code is executed, it produces the following result −
[1, 3, 5, 78, 21, 45]
[3, 21, 5, 78, 45]
The heapreplace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order.
import heapq
H = [21,1,45,78,3,5]
# Create the heap
heapq.heapify(H)
print(H)
# Replace an element
heapq.heapreplace(H,6)
print(H)
When the above code is executed, it produces the following result −
[1, 3, 5, 78, 21, 45]
[3, 6, 5, 78, 21, 45]
How to get the available height and available width of a screen in JavaScript?

The window.screen object has provided many features to get the information regarding the browser screen. It has provided screen.availWidth and screen.availHeight to get the available height and available width of the screen. Let's discuss them individually.
The screen.availWidth property returns the true width of the visitor's screen that means it subtracts the width of interface features like the Windows Taskbar. The resultant value will be in pixels.
Live Demo
<html>
<body>
<p id="width"></p>
<script>
   document.getElementById("Width").innerHTML =
   "Available screen width is " + screen.availWidth;
</script>
</body>
</html>
Available screen width is 1366
The screen.availHeight property returns the true height of the screen that means it subtracts the interface features like the Windows Taskbar. The resultant value will be in pixels.
Live Demo
<html>
<body>
<p id="height"></p>
<script>
   document.getElementById("height").innerHTML =
   "Available screen width is " + screen.availHeight;
</script>
</body>
</html>
Available screen height is 728
How to Delete Tkinter Text Box's Contents? - GeeksforGeeks

08 Oct, 2021
Prerequisite:
Python GUI – tkinter
Text Widget
Python offers multiple options for developing GUI (Graphical User Interface) out of which Tkinter is the most preferred means. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest, most reliable and easiest way to create a desired GUI application. 
The Text widget is used to for showing text data on the Python application. However, Tkinter supports Entry widget which can be used to implement a single line text box. But, a text widget can be used to display the multi-line formatted text with various styles and attributes.
Import module
Create a normal Tkinter window.
Add text Box
Syntax:
Text(Object Name, **attr)
For deleting content from Text Box, we will create a delete button to implement delete method. Clicking on this button will erase the content written in the text box.
Syntax:
Object_name.delete(first=number, last=number)
Given below is the program to implement the same:
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # specify size of window.root.geometry("400x500") # delete content from Text Box  def delete_text():    T.delete("1.0", "end")  # Create text widgetT = Text(root)T.pack() # Create Delete ButtonButton(root, text="Delete", command=delete_text).pack() # Execute Tkinterroot.mainloop()
Output:
gulshankumarar231
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
loops in python