code-rag-bench/online-tutorials huggingface dataset:
Default values of static variables in C

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.
Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program.
Here is the syntax of static variables in C language,
static datatype variable_name;
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
Here is an example of static variables in C language,
 Live Demo
#include <stdio.h>
int main() {
   static int a;
   int b;
   printf("Default value of static variable : %d\n", a);
   printf("Default value of non-static variable : %d\n", b);
   return 0;
}
Default value of static variable : 0
Default value of non-static variable : 0
In the above program, two variables are declared, one is static and another is non-static. The default values of both variables are displayed as follows −
static int a;
int b;
printf("Default value of static variable : %d\n", a);
printf("Default value of non-static variable : %d\n", b);
\raise - Tex Command

\raise - Used to raises the argument by the amount specified in <dimen>
{ \raise <dimen> #1 }
\raise command is used to raises the argument by the amount specified in <dimen>

h\raise 2pt {ighe} r

higher



h\raise 2pt {ighe} r

higher


h\raise 2pt {ighe} r

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Kotlin While Loop

Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
  // code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as 
the counter variable (i) is less than 5:
var i = 0
while (i < 5) {
  println(i)
  i++
} 
Note: Do not forget to increase the variable used in the condition, otherwise 
the loop will never end.
The do..while loop is a variant of the while loop. This loop will 
execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
do {
  // code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be 
executed at least once, even if the condition is false, because the code block 
is executed before the condition is tested:
var i = 0
do {
  println(i)
  i++
  }
while (i < 5) 
Do not forget to increase the variable used in the condition, otherwise 
the loop will never end!
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Comparing enum members in C#

To compare enum members, use the Enum.CompareTo() method.
Firstly, set the values for students.
enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
Now use the compareTo() method to compare one enum value with another.
Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
The following is the code to compare enum members in C#.
 Live Demo
using System;
public class Demo {
   enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
   public static void Main() {
      StudentRank student1 = StudentRank.Tom;
      StudentRank student2 = StudentRank.Henry;
      StudentRank student3 = StudentRank.Amit;
      Console.WriteLine("{0} has more rank than {1}?", student1, student2);
      Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
   }
}
Tom has more rank than Henry?
Yes
PDF Viewer for Python Tkinter

Python is well known for its large set of libraries and extensions, each for different features, properties and use-cases. To handle PDF files, Python provides PyPDF2 toolkit which is capable of processing, extracting, merging multiple pages, encrypting PDF files, and many more. It is a very useful Package for managing and manipulating the file streams such as PDFs. Using PyPDF2, we will create a Tkinter application that reads the PDF file by asking users to select and open a PDF file from the local directory.
To create the application, we will follow the steps given below −
Install the requirement by typingpip install PyPDF2in the command Shell. Once installed, import the library in the notebook using import Pypdf2 in Notebook.
Install the requirement by typing
pip install PyPDF2
Import filedialog to create a dialog box for selecting the file from the local directory.
Import filedialog to create a dialog box for selecting the file from the local directory.
Create a Text Widget and add some Menus to it like Open, Clear, and Quit.
Create a Text Widget and add some Menus to it like Open, Clear, and Quit.
Define a function for each Menu.
Define a function for each Menu.
Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file.
Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file.
Insert the content in the Text Box.
Insert the content in the Text Box.
Define the function for Quit Menu.
Define the function for Quit Menu.
#Import the required Libraries
import PyPDF2
from tkinter import *
from tkinter import filedialog
#Create an instance of tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x450")
#Create a Text Box
text= Text(win,width= 80,height=30)
text.pack(pady=20)
#Define a function to clear the text
def clear_text():
   text.delete(1.0, END)
#Define a function to open the pdf file
def open_pdf():
   file= filedialog.askopenfilename(title="Select a PDF", filetype=(("PDF    Files","*.pdf"),("All Files","*.*")))
   if file:
      #Open the PDF File
      pdf_file= PyPDF2.PdfFileReader(file)
      #Select a Page to read
      page= pdf_file.getPage(0)
      #Get the content of the Page
      content=page.extractText()
      #Add the content to TextBox
      text.insert(1.0,content)

#Define function to Quit the window
def quit_app():
   win.destroy()
#Create a Menu
my_menu= Menu(win)
win.config(menu=my_menu)
#Add dropdown to the Menus
file_menu=Menu(my_menu,tearoff=False)
my_menu.add_cascade(label="File",menu= file_menu)
file_menu.add_command(label="Open",command=open_pdf)
file_menu.add_command(label="Clear",command=clear_text)
file_menu.add_command(label="Quit",command=quit_app)
win.mainloop()
Running the above code will display a full-fledged tkinter application. It has functionalities of opening the file, clearing the file, and quit to terminate the application.
Click the "File" Menu on upper left corner of the application, open a new PDF File in the Text Box.
DAX Filter - CALCULATE function

Evaluates an expression in a context that is modified by the specified filters.
CALCULATE (<expression>, [<filter1>], [<filter2>] ...) 

expression
The expression to be evaluated.
filter1, filter2, ...
Optional.
A comma separated list of Boolean expressions or a table expression that defines a filter.
The value that is the result of the expression.
The expression used as the first parameter is essentially the same as a calculated field.
If Boolean expressions are used as arguments, the following restrictions apply −
An expression cannot reference a calculated field.
An expression cannot reference a calculated field.
An expression cannot use a nested CALCULATE function.
An expression cannot use a nested CALCULATE function.
An expression cannot use any function that scans a table or returns a table, including aggregation functions.
An expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
If the data has been filtered, the CALCULATE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter argument, any existing filters on that column are removed, and the filter used in the filter argument is applied instead.
= COUNTA (Results[Medal])/CALCULATE (COUNTA (Results[Medal], ALL (Results)) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
remainder() in C++

Here we will see the functionality of remainder() method of C++. The remainder() function is used to compute the floating point remainder of numerator/denominator.
So the remainder(x, y) will be like below.
remainder(x, y) = x – rquote * y
The rquote is the value of x/y. This is rounded towards the nearest integral value. This function takes two arguments of type double, float, long double, and returns the remainder of the same type, that was given as argument. The first argument is numerator, and the second argument is the denominator.
#include <iostream>
#include <cmath>
using namespace std;
main() {
   double x = 14.5, y = 4.1;
   double res = remainder(x, y);
   cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
   x = -34.50;
   y = 4.0;
   res = remainder(x, y);
   cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
   x = 65.23;
   y = 0;
   res = remainder(x, y);
   cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
}
Remainder of 14.5/4.1 is: -1.9
Remainder of -34.5/4 is: 1.5
Remainder of 65.23/0 is: nan
How to check an element is exists in array or not in PHP ? - GeeksforGeeks

31 Oct, 2021
An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :
Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not. 
in_array(element , array)
Arguments : 
element: The element to check in the array
array: The array to look for element
Example:
PHP
<?php  // Declaring an array object $arr = array("Hello", "GEEKs" , "User" , "PHP");print("Original Array </br>");print (json_encode($arr) . " </br>");  // Declaring element$ele = "GEEKs";  // Check if element existsif(in_array($ele, $arr)){    print($ele . " - Element found.");}else{    print($ele . "Element not found.");}?>
Output:
Original Array:
["Hello","GEEKs","User","PHP"]
GEEKs - Element found.
Approach 2 (Using for loop): A for loop iteration is done throughout the array. A boolean flag is declared to check for the presence of an element. It is initialized to the boolean value of false. In case the value is false, and the element is found in the array, the flag value is changed to the true value. No further modifications in the flag value are made. 
Example:
PHP
<?php  // Declaring an array object $arr = array(1, 3, 5, 6);print("Original Array </br>");print (json_encode($arr)." </br>");  // Declaring element$ele = 5;  // Declare a flag $flag = FALSE;  // Check if element existsforeach($arr as $val){    if($flag == FALSE){        if($val == $ele){            $flag = TRUE;        }    }}if($flag ==TRUE){    print($ele . " - Element found.");}else{    print($ele . " - Element not found.");}?>
Output:
Original Array
[1, 3, 5, 6]
5 - Element found.
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
PHP str_replace() Function
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
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?
Enumeration hasMoreElements() Method in Java with Examples - GeeksforGeeks

27 Jun, 2019
An object that implements the Enumeration interface generates a series of elements, one at a time. hasMoreElements() method of Enumeration used to tests if this enumeration contains more elements. If enumeration contains more element then it will return true else false.
Syntax:
boolean hasMoreElements()

Parameters: This method accepts nothing.
Return value: This method returns true if and only if this enumeration object contains at least one more element to provide; false otherwise.
Below programs illustrate hasMoreElements() method:Program 1:
// Java program to demonstrate// Enumeration.hasMoreElements() method  import java.util.*;  public class GFG {      @SuppressWarnings({ "unchecked", "rawtypes" })    public static void main(String[] args)    {          Enumeration Days;        Vector week = new Vector();          week.add("Sunday");        week.add("Monday");        week.add("Tuesday");        week.add("Wednesday");        week.add("Thursday");        week.add("Friday");        week.add("Saturday");        Days = week.elements();          while (Days.hasMoreElements()) {            System.out.println("Day = "                               + Days.nextElement());        }    }}
Day = Sunday
Day = Monday
Day = Tuesday
Day = Wednesday
Day = Thursday
Day = Friday
Day = Saturday

Program 2:
// Java program to demonstrate// Enumeration.hasMoreElements() method  import java.util.*;  public class GFG {      @SuppressWarnings({ "unchecked", "rawtypes" })    public static void main(String[] args)    {          Enumeration<Integer> classNine;        Vector<Integer> rollno = new Vector<Integer>();          rollno.add(1);        rollno.add(2);        rollno.add(3);        rollno.add(4);        rollno.add(5);        rollno.add(6);        rollno.add(7);        rollno.add(8);        classNine = rollno.elements();          while (classNine.hasMoreElements()) {            System.out.println("Roll No = "                               + classNine.nextElement());        }    }}
Roll No = 1
Roll No = 2
Roll No = 3
Roll No = 4
Roll No = 5
Roll No = 6
Roll No = 7
Roll No = 8

References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#hasMoreElements()
Java - util package
Java-Enumeration
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
C++ Program to Find Transpose of a Matrix

A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. A transpose of a matrix is a new matrix in which the rows of the original are the columns now and vice versa. For example.
A matrix is given below −
1 2 3
4 5 6
7 8 9
The transpose of the above matrix is as follows.
1 4 7
2 5 8
3 6 9
A program to find the transpose of a matrix is as follows −
 Live Demo
#include<iostream<
using namespace std;
int main() {
   int transpose[10][10], r=3, c=2, i, j;
   int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
   cout<<"The matrix is:"<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<a[i][j]<<" ";
      cout<<endl;
   }
   cout<<endl;
   for(i=0; i<r; ++i)
   for(j=0; j<c; ++j) {
      transpose[j][i] = a[i][j];
   }
   cout<<"The transpose of the matrix is:"<<endl;
   for(i=0; i<c; ++i) {
      for(j=0; j<r; ++j)
      cout<<transpose[i][j]<<" ";
      cout<<endl;
   }
   return 0;
}
The matrix is:
1 2
3 4
5 6

The transpose of the matrix is:
1 3 5
2 4 6
In the above program, the matrix is initialized. Then its values are displayed. This is shown in the following code snippet.
int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<a[i][j]<<" ";
   cout<<endl;
}
The transpose of the matrix is calculated using a nested for loop. This is given as follows.
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
   transpose[j][i] = a[i][j];
}
Finally, the transpose is obtained and it is printed on the screen. This is done with the following code snippet.
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
   for(j=0; j<r; ++j)
   cout<<transpose[i][j]<<" ";
   cout<<endl;
}
fread() function in C++ - GeeksforGeeks

16 Feb, 2021
The fread() function in C++ reads the block of data from the stream. This function first, reads the count number of objects, each one with a size of size bytes from the given input stream. The total amount of bytes reads if successful is (size*count). According to the no. of characters read, the indicator file position is incremented. If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0.Syntax :  
size_t fread(void * buffer, size_t size, size_t count, FILE * stream)
Parameter : The function accepts four mandatory parameters which are described as below:  
buffer: it specifies the pointer to the block of memory with a size of at least (size*count) bytes to store the objects.
size: it specifies the size of each object in bytes. size_t is an unsigned integral type.
count: it specifies the number of elements, each one with a size of size bytes.
stream: it specifies the file stream to read the data from.
Return Value: The function returns the number of objects read successfully. If an error occurs, the return value can be less than the count.Below programs illustrate the above function: Program 1:  
CPP
// C++ program to illustrate fread() function#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){    FILE* file_;    char buffer[100];    file_ = fopen("g4g.txt", "aman");    while (!feof(file_)) // to read file    {        // function used to read the contents of file        fread(buffer, sizeof(buffer), 1, file_);        cout << buffer;    }    return 0;}
Suppose the file g4g.txt contains following data:  
Geeks : DS-ALgo 
Gfg : DP 
Contribute : writearticle 
Then, when you will run the program, the output will be  
Harry Potter : Specs
Hermione : Smart
Weasley : FlyingCar
Dumbledore : Wand
Program 2 :  
CPP
// C++ program to illustrate fread() function// when file's size or count is equal to 0#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){    FILE* file_;    char buffer[100];     file_ = fopen("g4g.txt", "aman");    cout << "count = 0, return value = " <<    fread(buffer, sizeof(buffer), 0, file_);    cout << "\nsize = 0, return value = " <<    fread(buffer, 0, 1, file_) << endl;    return 0;}
count = 0, return value = 0
size = 0, return value = 0
 
arorakashish0911
C-File Handling
cpp-file-handling
CPP-Functions
File Handling
C++
File Handling
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
vector erase() and clear() in C++
How to Create Query Parameters in JavaScript ? - GeeksforGeeks

18 Mar, 2020
The task is to create a query URL for GET request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach.
Make a variable query.
Loop through all the keys and values of the json and attach them together with ‘&’ symbol.
Examples:
Input: {'website':'geeks', 'location':'india'}
Output: website=geeks&location=india
Syntax:
function encodeQuery(data){
    let query = ""
    for (let d in data)
         query += encodeURIComponent(d) + '=' + 
            encodeURIComponent(data[d]) + '&'
    return query.slice(0, -1)
}
Below examples implements the above approach:
Example 1:
<script>function encodeQuery(data){    let query = ""    for (let d in data)         query += encodeURIComponent(d) + '='                   + encodeURIComponent(data[d]) + '&'    return query.slice(0, -1)}  // Json object that should be// converted to query parameterdata = {     'website':'geeks',    'location':'india'}queryParam = encodeQuery(data)console.log(queryParam)</script>
Output:
website=geeks&location=india
Example 2: In this example, we will create a complete URL from the given JSON data.
<script>function encodeQuery(data){    let query = data.url    for (let d in data.params)         query += encodeURIComponent(d) + '='              + encodeURIComponent(data.params[d]) + '&';    return query.slice(0, -1)}  // Json object that should be// converted to query parameterdata = {     url : 'www.geeksforgeeks.com/',    params : {        'website':'geeks',        'location':'india'    }}queryParam = encodeQuery(data)console.log(queryParam)</script>
Output:
www.geeksforgeeks.com/website=geeks&location=india
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
HTML | DOM Window opener Properties - GeeksforGeeks

26 Jul, 2019
The Window opener property in HTML DOM is used to return the reference of newly created windows. This property is used to return the details of the source (parent) window. A window is opened using the window.open() method and closed using the window.opener.close() method.
Syntax:
window.opener
Return Value: It returns the reference of created window.
Example 1:
<!DOCTYPE html><html>      <head>    <title>        HTML DOM Window opener Property    </title></head>  <body>          <h2>        HTML DOM Window opener Property    </h2>          <button onclick = "myGeeks()">        Click Here!    </button>      <!-- script to open new windows -->    <script>        function myGeeks() {            var win = window.open("", "win",                        "width = 500, height = 300");                                      win.document.write("<p>New Window</p>");                          win.opener.document.write("<p>Parent Window</p>");        }    </script></body>  </html>                                    
Output:Before click on the button:After click on the button:
Example 2:
<!DOCTYPE html><html>      <head>    <title>        HTML DOM Window opener Property    </title></head>  <body>          <h2>        HTML DOM Window opener Property    </h2>          <button onclick = "myGeeks()">        Click Here!    </button>          <!-- script to create two window -->    <script>        function myGeeks() {            var win1 = window.open("", "win1",                     "width = 500, height = 300");                                  var win2 = window.open("", "win2",                    "width = 400, height = 250");                                  win1.document.write("<p>New Window 1</p>");            win2.document.write("<p>New Window 2</p>");                          win1.opener.document.write("<p>Parent Window</p>");            win2.opener.document.write("<p>Parent Window</p>");        }    </script></body>  </html>                    
Output:Before click on the button:After click on the button:
Supported Browsers: The browser supported by DOM Window opener property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
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?
Get super class of an object in Java

The immediate superclass of any entity such as an object, class, primitive type, interface etc. can be obtained using the method java.lang.Class.getSuperclass(). This method contains no parameters.
A program that demonstrates this is given as follows −
 Live Demo
public class Main {
   public static void main(String[] args) {
      Object obj1 = new String("Hello");
      Object obj2 = new Integer(15);
      Class c1 = obj1.getClass().getSuperclass();
      System.out.println("Super Class = " + c1);
      Class c2 = obj2.getClass().getSuperclass();
      System.out.println("Super Class = " + c2);
   }
}
Super Class = class java.lang.Object
Super Class = class java.lang.Number
Now let us understand the above program.
In the method main(), getClass() is used to obtain the class and getSuperclass() is used to obtain the super class of objects obj1 and obj2. Then the super class is printed. A code snippet which demonstrates this is as follows −
Object obj1 = new String("Hello");
Object obj2 = new Integer(15);
Class c1 = obj1.getClass().getSuperclass();
System.out.println("Super Class = " + c1);
Class c2 = obj2.getClass().getSuperclass();
System.out.println("Super Class = " + c2);
Java program to swap first and last characters of words in a sentence

Following is the Java program to swap first and last characters of word in a sentence −
 Live Demo
public class Demo {
   static String swap_chars(String my_str) {
      char[] my_ch = my_str.toCharArray();
      for (int i = 0; i < my_ch.length; i++) {
         int k = i;
         while (i < my_ch.length && my_ch[i] != ' ')
            i++;
            char temp = my_ch[k];
            my_ch[k] = my_ch[i - 1];
            my_ch[i - 1] = temp;
      }
      return new String(my_ch);
   }
   public static void main(String[] args) {
      String my_str = "Thas is a sample";
      System.out.println("The string after swapping the last characters of every word is : ");
      System.out.println(swap_chars(my_str));
   }
}
The string after swapping the last characters of every word is :
shaT si a eampls
A class named Demo contains a function named ‘swap_chars’ which returns a string as output. In this function, the string is converted to a character array. The character array is iterated over, and if the next element in the word is not a space, the first and the last elements are swapped, and this string is returned as output of the function. The same is repeated for all words in a sentence. In the main function, the string is defined, and the function is called by passing this string as a parameter to it.
Single Number in Python

Suppose we have an array A. In this array there are many numbers that occur twice. Only one element can be found a single time. We have to find that element from that array. Suppose A = [1, 1, 5, 3, 2, 5, 2], then the output will be 3. As there is each number twice, we can perform XOR to cancel out that element. because we know y XOR y = 0
To solve this, we will follow these steps.
Take one variable res = 0
for each element e in array A, preform res = res XOR e
return res
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def singleNumber(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      ans = nums[0]
      for i in range(1,len(nums)):
         ans ^=nums[i]
      return ans
ob1 = Solution()
print(ob1.singleNumber([1,1,5,3,2,5,2]))
nums = [1,1,5,3,2,5,2]
3
Matplotlib - Working with Images

The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image.
Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG images. The commands shown below fall back on Pillow if the native read fails.
The image used in this example is a PNG file, but keep that Pillow requirement in mind for your own data. The imread() function is used to read image data in an ndarray object of float32 dtype.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('mtplogo.png')
Assuming that following image named as mtplogo.png is present in the current working directory.
Any array containing image data can be saved to a disk file by executing the imsave() function. Here a vertically flipped version of the original png file is saved by giving origin parameter as lower.
plt.imsave("logo.png", img, cmap = 'gray', origin = 'lower')
The new image appears as below if opened in any image viewer.
To draw the image on Matplotlib viewer, execute the imshow() function.
imgplot = plt.imshow(img)

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Extracting MAC address using Python

We know that the MAC address is a hardware address which means it is unique for the network card installed on our PC. It is always unique that means no two devices on a local network could have the same MAC addresses.
The main purpose of MAC address is to provide a unique hardware address or physical address for every node on a local area network (LAN) or other networks. A node means a point at which a computer or other device (e.g. a printer or router) will remain connected to the network.
Using uuid.getnode()
In this example getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.
 Live Demo
import uuid
print (hex(uuid.getnode()))
0x242ac110002L

Using getnode() + format() [ This is for better formatting ]
import uuid
# after each 2 digits, join elements of getnode().
print ("The formatted MAC address is : ", end="")
print (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0,2*6,2)][::-1]))
The formatted MAC address is : 3e:f8:e2:8b:2c:b3

Using getnode() + findall() + re()[ This is for reducing complexity]
import re, uuid
# after each 2 digits, join elements of getnode().
# using regex expression
print ("The MAC address in expressed in formatted and less complex way : ", end="")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
The MAC address in expressed in formatted and less complex way : 18:5e:0f:d4:f8:b3
Display flex items horizontally on a specific screen size in Bootstrap

To set flex item horizontally in different screen size, use the flex-*-row class.
The varied screen sizes is set for small, medium, large and extra large screen size. Let us see how to align flex items horizontally for small screen size −
<h2>Flex Row (Small Screen)</h2>
<div class="d-sm-flex flex-sm-row bg-primary mb-3">
  <div class="p-2 bg-primary">Audi</div>
  <div class="p-2 bg-warning">BMW</div>
  <div class="p-2 bg-secondary">Benz</div>
</div>
The following is an example to display flex items horizontally on different screen size −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

  <div class="container mt-3">
    <h2>Flex</h2>
    <p>Resize the browser window to check the effect.</p>
    <h2>Flex Row</h2>
    <div class="d-flex flex-row bg-primary mb-3">
      <div class="p-2 bg-secondary">Audi</div>
      <div class="p-2 bg-warning">BMW</div>
      <div class="p-2 bg-info">Benz</div>
    </div>
    <h2>Flex Row (Small Screen)</h2>
    <div class="d-sm-flex flex-sm-row bg-primary mb-3">
      <div class="p-2 bg-primary">Audi</div>
      <div class="p-2 bg-warning">BMW</div>
      <div class="p-2 bg-secondary">Benz</div>
    </div>
    <h2>Flex Row (Medium Screen)</h2>
    <div class="d-md-flex flex-md-row bg-primary mb-3">
      <div class="p-2 bg-warning">Audi</div>
      <div class="p-2 bg-danger">BMW</div>
      <div class="p-2 bg-primary">Benz</div>
    </div>
    <h2>Flex Row (Large Screen)</h2>
    <div class="d-lg-flex flex-lg-row bg-primary mb-3">
      <div class="p-2 bg-primary">Audi</div>
      <div class="p-2 bg-danger">BMW</div>
      <div class="p-2 bg-info">Benz</div>
    </div>
  </div>

 </body>
</html>
Drag and Drop a File feature in React JS

Drag and Drop interfaces enable web applications to allow users to drag and drop files on a web page. In this article, we will see how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. Here, we will be using the react-dropzone package. Let's get started.
First of all, create a React project −
npx create-react-app newproject
Go to the project directory −
cd newproject
Now download and install the react-dropzone package −
npm i --save react-dropzone
We will use this library to add a droppable area inside our React
element's area. This is used to add a file selection area too.
In this example, we will add the name of a file in a list using drag-and-drag feature. Insert the following lines of code in App.js −
import React from "react";
import { useDropzone } from "react-dropzone";
function Basic(props) {
   const { acceptedFiles, getRootProps, getInputProps } =
useDropzone();

   const files = acceptedFiles.map((file) => (
      <li key={file.path}>
         {file.path} - {file.size} bytes
      </li>
   ));
   return (
   <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
         <input
            {...getInputProps()}
            style={{ backgroundColor: "black", color: "white" }}
         />
         <br />
         <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
         <h4>Files</h4>
         <ul>{files}</ul>
      </aside>
      </section>
   );
}
export default App

function App() {
   return <Basic />;
}
We have created three variables −
The first variable stores all the file details,
The first variable stores all the file details,
The second variable defines the area where this drag-and-drop feature will work, and
The second variable defines the area where this drag-and-drop feature will work, and
The third variable makes the input field droppable.
The third variable makes the input field droppable.
On execution, it will produce the following output −
You can drag-and-drop files onto this page from any folder. It will
display the file name along with its size. Also, you can use the "Choose
files" button to open a folder location and select a file.
Chain Multiple Decorators in Python - GeeksforGeeks

08 Jun, 2020
Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.
So, here in this post we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for resuabale building blocks as it accumulates the several effects together. It is also knows as nested decorators in Python.
Syntax: 
@decor1
@decor
def num():
    statement(s)    
Example: For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator.
Python3
# code for testing decorator chainingdef decor1(func):    def inner():        x = func()        return x * x    return inner  def decor(func):    def inner():        x = func()        return 2 * x    return inner  @decor1@decordef num():    return 10  print(num())
Output:
400
Python Decorators
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
Python | Finding 'n' Character Words in a Text File - GeeksforGeeks

26 Mar, 2020
This article aims to find words with a certain number of character. In the code mentioned below, a python program is given to find the words contain three characters in the text file.
Examples:
Input : Hello, how are you ?
Output :howareyou
Code: Python program to find the words contain three characters in the text file
count = 1chrw = ""  # text filefile = open('textfile.txt', 'r')while 1:    sp = file.read(1)      if count<= 3:        chrw = chrw + sp      if count>3:        if sp ==" ":            count = 0            if len(chrw)>0:                print(chrw)                chrw =""        elif sp !=" ":            chrw =""    count = count + 1      if not sp:        break  file.close() 
Output:
how 
are 
you

Python file-handling-programs
python-file-handling
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 ?
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
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?
Difference between Boxing and Unboxing in C# - GeeksforGeeks

17 Apr, 2019
Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enables a unified view of the type system in which a value of any type can be treated as an object.
// C# program to illustrate Boxingusing System;  public class GFG {    static public void Main()    {        int val = 2019;          // Boxing        object o = val;          // Change the value of val        val = 2000;          Console.WriteLine("Value type of val is {0}", val);        Console.WriteLine("Object type of val is {0}", o);    }}
Output:
Value type of val is 2000
Object type of val is 2019

// C# program to illustrate Unboxingusing System;  public class GFG {    static public void Main()    {        int val = 2019;          // Boxing        object o = val;          // Unboxing        int x = (int)o;          Console.WriteLine("Value of o is {0}", o);        Console.WriteLine("Value of x is {0}", x);    }}
Output:
Value of o is 2019
Value of x is 2019

CSharp-Basics
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
LocalTime toString() method in Java with Examples - GeeksforGeeks

06 Dec, 2018
The toString() method of LocalTime class is used to represents this time as a String, such as 20:15:34.111.
Following ISO-8601 formats are used for representation:
HH:mm
HH:mm:ss
HH:mm:ss.SSS
HH:mm:ss.SSSSSS
HH:mm:ss.SSSSSSSSS
This method is derived from the Object Class and behaves in a similar way.
Syntax:
public String toString()

Parameters: This method accepts no parameter.
Return value: This method returns a String representation of this LocalTime.
Below programs illustrate the toString() method:
Program 1:
// Java program to demonstrate// LocalTime.toString() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime object        LocalTime time            = LocalTime.parse("19:34:50.63");          // print LocalTime        System.out.println("LocalTime : "                           + time.toString());    }}
LocalTime : 19:34:50.630

Program 2:
// Java program to demonstrate// LocalTime.toString() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime object        LocalTime time            = LocalTime.parse("01:00:01");          // print LocalTime        System.out.println("Old LocalTime: "                           + time.toString());          // add 600 Minutes using plusMinutes()        LocalTime value = time.plusMinutes(600);          // print result        System.out.println("New LocalTime: "                           + value.toString());    }}
Old LocalTime: 01:00:01
New LocalTime: 11:00:01

References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#toString()
Java-Functions
Java-LocalTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
varchar, varchar(max) and nvarchar in MS SQL Server - GeeksforGeeks

03 Sep, 2020
We know that a database can different datatypes. Consider an organization having various databases like Employees, Departments, Finance. The employee database has a table that stores the details of each employee and employee is uniquely identified using the employee ID.
In most of the cases, an employee ID has a combination of digits and letters. How can the database store the values? It uses a special datatype named varchar or Variable Character datatype. It uses numbers and letters.
varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n)
n – is the number of bytes. The maximum storage capacity is upto 8000 bytes.varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max)
nvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar
n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table.
varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n)
n – is the number of bytes. The maximum storage capacity is upto 8000 bytes.
varchar (n)

n – is the number of bytes. The maximum storage capacity is upto 8000 bytes.
varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max)

Syntax :
varchar(max)

nvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar
n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table.
nvarchar

n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table.
An overview of these datatypes :
*n is the number of bytes
*max is the maximum storage value.
*n is the number of bytes.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
SQL | Subquery
AngularJS | ng-focus Directive - GeeksforGeeks

31 Aug, 2021
The ng-focus Directive in AngluarJS is used to apply custom behavior when an element is focused. It can be used to show/hide some element or it can popup alert when element is being focused. It is supported by <a>, <input>, <select> and <textarea> elements.
Syntax:  
<element ng-focus="expression"> Contents... </element>
Where expressions tells what to do when input get focused.
Example 1: This example uses ng-focus Directive to display text area field.  
html
<!DOCTYPE html><html>     <head>    <title>ng-focus Directive</title>     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head> <body ng-app=""  style="text-align:center">         <h1 style="color:green">GeeksforGeeks</h1>         <h2>ng-focus Directive</h2>         <a href="" ng-focus="isCheck=true">        Click to proceed.    </a>         <br><br>         <div class="row" ng-show="isCheck">        Enter Name: <input type="text"            ng-focus="isCheck=true"            placeholder="geeksforgeeks" />    </div></body> </html>
Output: Before clicking the link:  
After clicking the link:  
Example 2: This example uses ng-focus Directive to display focus on input text field.  
html
<!DOCTYPE html><html>     <head>    <title>ng-focus Directive</title>     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head> <body ng-app="app" style="text-align:center;">         <h1 style="color:green">GeeksforGeeks</h1>         <h2>ng-focus Directive</h2>         <div ng-controller="geek">        Input: <input type="text" ng-focus="focused = true"                ng-blur="focused = false" />                 <pre ng-show="focused">Input is focused.</pre>    </div>         <script>        var app = angular.module("app", []);        app.controller('geek', ['$scope', function ($scope) {        }]);    </script></body> </html>
Output: Before click on text area:  
After click on text area:  
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari 
ysachin2314
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
What is AOT and JIT Compiler in Angular ?
How to bundle an Angular app for production?
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?