code-rag-bench/online-tutorials huggingface dataset:
Nested Classes in C++ - GeeksforGeeks

04 Jan, 2019
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.
For example, program 1 compiles without any error and program 2 fails in compilation.
Program 1
#include<iostream>  using namespace std;   /* start of Enclosing class declaration */  class Enclosing {         private:          int x;        /* start of Nested class declaration */     class Nested {      int y;         void NestedFun(Enclosing *e) {        cout<<e->x;  // works fine: nested class can access                      // private members of Enclosing class      }          }; // declaration Nested class ends here}; // declaration Enclosing class ends here  int main(){       }
Program 2
#include<iostream>  using namespace std;   /* start of Enclosing class declaration */  class Enclosing {                 int x;        /* start of Nested class declaration */     class Nested {      int y;      }; // declaration Nested class ends here     void EnclosingFun(Nested *n) {        cout<<n->y;  // Compiler Error: y is private in Nested   }      }; // declaration Enclosing class ends here  int main(){      }
References:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akshit Agarwal 3
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Substring in C++
Multidimensional Arrays in C / C++
C++ Data Types
Sorting a vector in C++
Set in C++ Standard Template Library (STL)
2D Vector In C++ With User Defined Size
Python program to find difference between current time and given time

30 Jan, 2020
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format.
Examples:
Input : h1=7, m1=20, h2=9, m2=45Output : 2 : 25The current time is 7 : 20 and given time is 9 : 45.The difference between them is 145 minutes.The result is 2 : 25 after converting to h : m format.
Input : h1=15, m1=23, h2=18, m2=54Output : 3 : 31The current time is 15 : 23 and given time is 18 : 54.The difference between them is 211 minutes.The result is 3 : 31 after converting to h : m format.
Input : h1=16, m1=20, h2=16, m2=20Output : Both times are sameThe current time is 16 : 20 and given time is also 16 : 20.The difference between them is 0 minutes.As the difference is 0, we are printing “Both are same times”.
Approach:
convert both the times into minutes
find the difference in minutes
if difference is 0, print “Both are same times”
else convert difference into h : m format and print
Below is the implementation.
# Python program to find the# difference between two times    # function to obtain the time# in minutes formdef difference(h1, m1, h2, m2):          # convert h1 : m1 into    # minutes    t1 = h1 * 60 + m1          # convert h2 : m2 into    # minutes     t2 = h2 * 60 + m2          if (t1 == t2):         print("Both are same times")        return     else:                  # calculating the difference        diff = t2-t1              # calculating hours from    # difference    h = (int(diff / 60)) % 24          # calculating minutes from     # difference    m = diff % 60      print(h, ":", m)  # Driver's codeif __name__ == "__main__":          difference(7, 20, 9, 45)    difference(15, 23, 18, 54)    difference(16, 20, 16, 20)  # This code is contributed by SrujayReddy
Output:
2 : 25
3 : 31
Both are same times

Python datetime-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
Splitting Strings in R programming – strsplit() method

11 Nov, 2021
strsplit() method in R Programming Language is used to split the string by using a delimiter.
Syntax: strsplit(string, split, fixed)
Parameters:
string: Input vector or string.
split: It is a character of string to being split.
fixed: Match the split or use the regular expression.
Return: Returns the list of words or sentences after split. 
Here, we are using strsplit() along with delimiter, delimiter is a character of an existing string to being removed from the string and display out.
R
# R program to split a string # Given Stringgfg < - "Geeks For Geeks" # Using strsplit() methodanswer < - strsplit(gfg, " ") print(answer)
Output:
[1] "Geeks" "For"   "Geeks"
Here, we are using regular expressions in delimiter to split the string.
R
# R program to split a string # Given Stringgfg <- "Geeks9For2Geeks" # Using strsplit() methodanswer <- strsplit(gfg, split = "[0-9]+") print(answer)
Output:
[1] "Geeks" "For"   "Geeks"
We can also manipulate with date using strsplit(), only we need to understand the date formatting, for example in this date( 2-07-2020) following the same pattern (-), so we can remove them using delimiter along with “-“. 
R
string_date<-c("2-07-2020","5-07-2020","6-07-2020",               "7-07-2020","8-07-2020")result<-strsplit(string_date,split = "-")print(result)
Output:
[[1]]
[1] "2"    "07"   "2020"

[[2]]
[1] "5"    "07"   "2020"

[[3]]
[1] "6"    "07"   "2020"

[[4]]
[1] "7"    "07"   "2020"

[[5]]
[1] "8"    "07"   "2020"
kumar_satyam
surinderdawra388
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
response.content – Python requests

26 Jul, 2021
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.content out of a response object. response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content. 
To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. 
Prerequisites –
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
Example code – 
Python3
import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request contentprint(response.content)
Example Implementation –
Save above file as request.py and run using  
Python request.py
Output –
Check that b’ at the start of output, it means the reference to a bytes object. 
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2 , treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.  
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. 
sumitgumber28
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Powershell - Write-Host Cmdlet

Write-Host cmdlet is used to write customized messages.
In these example, we're see the Write-Host cmdlet in action.
In this example, we'll show a customized message.
Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -BackgroundColor White
You can see the even numbers with separator, in green color and on white background.
2, -> 4, -> 6, -> 8, -> 10, -> 12
Node.js - Console

Node.js console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning, and error messages.
It is used in synchronous way when the destination is a file or a terminal and in asynchronous way when the destination is a pipe. 
Following is a list of methods available with the console global object.
console.log([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-like way.
console.info([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-like way.
console.error([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-like way.
console.warn([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-like way
console.dir(obj[, options])
Uses util.inspect on obj and prints resulting string to stdout.
console.time(label)
Mark a time.
console.timeEnd(label)
Finish timer, record output.
console.trace(message[, ...])
Print to stderr 'Trace :', followed by the formatted message and stack trace to the current position.
console.assert(value[, message][, ...])
Similar to assert.ok(), but the error message is formatted as util.format(message...).
Let us create a js file named main.js with the following code −
console.info("Program Started");

var counter = 10;
console.log("Counter: %d", counter);

console.time("Getting data");
//
// Do some processing here...
// 
console.timeEnd('Getting data');

console.info("Program Ended")
Now run the main.js to see the result −
node main.js

Verify the Output.
Program Started
Counter: 10
Getting data: 0ms
Program Ended


    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    88 Lectures 
     17 hours 

 Eduonix Learning Solutions

    32 Lectures 
     1.5 hours 

 Richard Wells

    8 Lectures 
     33 mins

 Anant Rungta

    9 Lectures 
     2.5 hours 

 SHIVPRASAD KOIRALA

    97 Lectures 
     6 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
GATE CS 2013 - GeeksforGeeks

11 Oct, 2021
Which one of the following does NOT equal to 
 
 
C 
D 
B 
A 
   
First of all, you should know the basic properties of determinants before approaching For these kind of problems. 1) Applying any row or column transformation does not change the determinant 2) If you interchange any two rows, sign of the determinant will change
 
 
A = | 1 x x^2 | | 1 y y^2 | | 1 z z^2 |
 
To prove option (b)
 
=> Apply column transformation C2 -> C2+C1
 
C3 -> C3+C1
 
=> det(A) = | 1 x+1 x^2+1 | | 1 y+1 y^2+1 | | 1 z+1 z^2+1 |
 
To prove option (c),
 
=> Apply row transformations R1 -> R1-R2
 
R2 -> R2-R3
 
=> det(A) = | 0 x-y x^2-y^2 | | 0 y-z y^2-z^2 | | 1 z z^2 |
 
To prove option (d),
 
=> Apply row transformations R1 -> R1+R2
 
R2 -> R2+R3
 
=> det(A) = | 2 x+y x^2+y^2 | | 2 y+z y^2+z^2 | | 1 z z^2 |
 
To insert 50, we will have to traverse all nodes.
        10
         \
          20
            \
             30
               \
                40

S->aB
B->bC
C->cd 
S -> aB ( Reduction 3 )
-> abC ( Reduction 2 )
-> abcd ( Reduction 1 )
S->abA
A-> cd
S -> abA ( Reduction 2 )
-> abcd ( Reduction 1 )
GROUP I                                         GROUP II
(P) Service oriented computing                 (1) Interoperability
(Q) Heterogeneous communicating systems        (2) BPMN
(R) Information representation                 (3) Publish-find-bind
(S) Process description                        (4) XML 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
HackWithInfy - A Coding Competition by Infosys
Design 101 sequence detector (Mealy machine) - GeeksforGeeks

01 Apr, 2021
Prerequisite – Mealy and Moore machines A sequence detector is a sequential state machine that takes an input string of bits and generates an output 1 whenever the target sequence has been detected. In a Mealy machine, output depends on the present state and the external input (x). Hence, in the diagram, the output is written outside the states, along with inputs. Sequence detector is of two types:  
OverlappingNon-Overlapping
Overlapping
Non-Overlapping
In an overlapping sequence detector, the last bit of one sequence becomes the first bit of the next sequence. However, in a non-overlapping sequence detector, the last bit of one sequence does not become the first bit of the next sequence. In this post, we’ll discuss the design procedure for non-overlapping 101 Mealy sequence detectors.  
Examples: 
For non overlapping case
Input :0110101011001
Output:0000100010000

For overlapping case
Input :0110101011001
Output:0000101010000
The steps to design a non-overlapping 101 Mealy sequence detectors are:  
Step 1: Develop the state diagram – The state diagram of a Mealy machine for a 101 sequence detector is: 
 
Step 2: Code Assignment – 
Rule 1 : States having the same next states for a given input condition should have adjacent assignments. Rule 2: States that are the next states to a single state must be given adjacent assignments. Rule 1 given preference over Rule 2. 
 
The state diagram after the code assignment is: 
 
Step 3: Make Present State/Next State table – We’ll use D-Flip Flops for design purposes. 
 
Step 4: Draw K-maps for Dx, Dy and output (Z) – 
 
Step 5: Finally implement the circuit – 
 
This is the final circuit for a Mealy 101 non-overlapping sequence detector. 
pavanpal25878543
Digital Electronics & Logic Design
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between RAM and ROM
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Difference between Half adder and full adder
Difference between DFA and NFA
Introduction of Finite Automata
Regular Expressions, Regular Grammar and Regular Languages
Conversion from NFA to DFA
Pumping Lemma in Theory of Computation
Find the next fibonacci number - GeeksforGeeks

10 Mar, 2022
Given a fibonacci number N, the task is to find the next fibonacci number.Examples:  
Input: N = 5 Output: 8 8 is the next fibonacci number after 5Input: N = 3 Output: 5  
 
Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is multiplied by ((1 + sqrt(5)) / 2) and round it, the resultant number will be the next fibonacci number.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the next// fibonacci numberint nextFibonacci(int n){    double a = n * (1 + sqrt(5)) / 2.0;    return round(a);} // Driver codeint main(){    int n = 5;    cout << nextFibonacci(n);} // This code is contributed by mohit kumar 29
// Java implementation of the approachclass GFG{         // Function to return the next    // fibonacci number    static long nextFibonacci(int n)    {        double a = n * (1 + Math.sqrt(5)) / 2.0;        return Math.round(a);    }         // Driver code    public static void main (String[] args)    {        int n = 5;        System.out.println(nextFibonacci(n));    }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachfrom math import * # Function to return the next# fibonacci numberdef nextFibonacci(n):    a = n*(1 + sqrt(5))/2.0    return round(a) # Driver coden = 5print(nextFibonacci(n))
// C# implementation of the approachusing System; class GFG{         // Function to return the next    // fibonacci number    static long nextFibonacci(int n)    {        double a = n * (1 + Math.Sqrt(5)) / 2.0;        return (long)Math.Round(a);    }         // Driver code    public static void Main(String[] args)    {        int n = 5;        Console.WriteLine(nextFibonacci(n));    }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Function to return the next// fibonacci numberfunction nextFibonacci(n){    let a = n * (1 + Math.sqrt(5)) / 2.0;    return Math.round(a);} // Driver code      let n = 5;    document.write(nextFibonacci(n)); // This code is contributed by Mayank Tyagi </script>
8
 
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
29AjayKumar
mayanktyagi1709
subham348
Fibonacci
Mathematical
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Program to multiply two matrices
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
Java program to convert the contents of a Map to list

The Map class’s object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately.
To convert a map to list −
Create a Map object.
Using the put() method insert elements to it as key, value pairs
Create an ArrayList of integer type to hold the keys of the map. In its constructor call the method keySet() of the Map class.
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Print the contents of both lists.
import java.util.HashMap;
import java.uitl.ArrayList;
import java.util.Map;

public class MapTohashMap {
   public static void main(String args[]){
      Map<Integer, String> myMap = new HashMap<>();
      myMap.put(1, "Java");
      myMap.put(2, "JavaFX");
      myMap.put(3, "CoffeeScript");
      myMap.put(4, "TypeScript");

      ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet());
      ArrayList<String> valueList = new ArrayList<String>(myMap.values());

      System.out.println("contents of the list holding keys the map ::"+keyList);
      System.out.println("contents of the list holding values of the map ::"+valueList);
   }
}

contents of the list holding keys the map::[1, 2, 3, 4]
contents of the list holding values of the map::[Java, JavaFX, CoffeeScript, Typescript]
How to adjust display settings of MySQL command line?

To adjust display settings of MySQL command line, use the /G at the end of MySQL queries instead of semicolon(;).
The syntax is as follows −
SELECT *FROM yourTableName \G
The above syntax adjusts the display settings. Here we will display records in row format from our sample ‘studenttable’ table which we created using CREATE −
mysql> create table StudentTable
   −> (
   −> Id int, 
   −> Name varchar(100)
   −> );
Query OK, 0 rows affected (0.65 sec)
To get all the records −
mysql> select *from StudentTable;
The following displays the records −
+------+---------+
| Id   | Name    |
+------+---------+
|    1 | Carol   |
|    2 | John    |
|    3 | Johnson |
+------+---------+
3 rows in set (0.00 sec)
The table ‘studenttable’ have some records that display all records in row format. The query is as follows to adjust display settings −
select *from studenttable \G
The following is the output −
*************************** 1. row ***************************
Id: 1
Name: Carol
*************************** 2. row ***************************
Id: 2
Name: John
*************************** 3. row ***************************
Id: 3
Name: Johnson
3 rows in set (0.04 sec)
VBA - Ltrim

The Ltrim function removes the blank spaces from the left side of the string.
LTrim(String)

Add a button and add the following function.
Private Sub Constant_demo_Click()
   Dim var as Variant
   var =       "             Microsoft VBScript"
   msgbox "After Ltrim : " & LTrim(var)
End Sub
When you execute the function, it produces the following output.
After Ltrim : Microsoft VBScript


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to create a WebView in an Android App using Kotlin?

This example demonstrates how to create a WebView in an Android App using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <WebView
      android:id="@+id/webView"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
   </WebView>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private val webView: WebView? = null
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val webView = findViewById<WebView>(R.id.webView)
      webView.webViewClient = WebViewClient()
      webView.loadUrl("https://www.google.com")
      val webSettings = webView.settings
      webSettings.javaScriptEnabled = true
   }
   override fun onBackPressed() {
      if (webView!!.canGoBack()) {
         webView.goBack()
      } else {
         super.onBackPressed()
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
   <application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:roundIcon="@mipmap/ic_launcher_round"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Remove vowels from a String in C++

The following C++ program illustrates how to remove the vowels (a,e, i,u,o) from a given string. In this context, we create a new string and process input string character by character, and if a vowel is found it is excluded in the new string, otherwise the character is added to the new string
after the string ends we copy the new string into the original string. The algorithm is as follows;
START
   Step-1: Input the string
   Step-3: Check vowel presence, if found return TRUE
   Step-4: Copy it to another array
   Step-5: Increment the counter
   Step-6: Print
END
In pursuance of the above algorithm, the following code in c++ language essayed as following;
#include <iostream>
#include <string.h>
#include <conio.h>
#include <cstring>
using namespace std;
int vowelChk(char);
int main(){
   char s[50], t[50];
   int c, d = 0;
   cout<<"Enter a string to delete vowels\n";
   cin>>s;
   for(c = 0; s[c] != '\0'; c++) {
      // check for If not a vowel
      if(vowelChk(s[c]) == 0){
         t[d] = s[c];
         d++;
      }
   }
   t[d] = '\0';
   strcpy(s, t);
   cout<<"String after delete vowels:"<<s;
   return 0;
}
int vowelChk(char ch){
   if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
      return 1;
   else
      return 0;
}
This C++ program deletes vowels from a string: if the input string is "ajaykumar" then it yields results as "jykmr". Finally, we obtain a string without vowels.
Enter a string to delete vowels
ajaykumar
String after delete vowels:jykmr
Unix / Linux - Shell Loop Types

In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −
The while loop
The for loop
The until loop
The select loop
You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.
Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc.
All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −
It is possible to use a while loop as part of the body of another while loop.
while command1 ; # this is loop1, the outer loop
do
   Statement(s) to be executed if command1 is true

   while command2 ; # this is loop2, the inner loop
   do
      Statement(s) to be executed if command2 is true
   done

   Statement(s) to be executed if command1 is true
done

Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used to count to nine −
#!/bin/sh

a=0
while [ "$a" -lt 10 ]    # this is loop1
do
   b="$a"
   while [ "$b" -ge 0 ]  # this is loop2
   do
      echo -n "$b "
      b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
PyQt5 Label - Adding shadow - GeeksforGeeks

10 May, 2020
In this article we will see how we can add shadow to the label by default there is no shadow to the label although we can create shadow to the label, below is the representation of how label with shadow box looks like
In order to do this we have to do the following –
1. Create a label2. Set geometry to the label3. Create a QGraphicsDropShadowEffect object4. Set blur radius to the object(optional)5. Add this object to the label with the help of setGraphicsEffect method
Syntax :
# creating a QGraphicsDropShadowEffect object
shadow = QGraphicsDropShadowEffect()

# setting blur radius (optional step)
shadow.setBlurRadius(15)

# adding shadow to the label
label.setGraphicsEffect(shadow)

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting background color of window        # self.setStyleSheet("background-color : black;")          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating label        label = QLabel("Label", self)          # setting alignment        label.setAlignment(Qt.AlignCenter)          # setting geometry to the label        label.setGeometry(200, 150, 200, 80)          # setting border        label.setStyleSheet("border : 10px solid black")          # creating a QGraphicsDropShadowEffect object        shadow = QGraphicsDropShadowEffect()          # setting blur radius        shadow.setBlurRadius(15)          # adding shadow to the label        label.setGraphicsEffect(shadow)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Program to find number of ways to arrange n rooks so that they cannot attack each other in Python

Suppose we have a number n representing a chessboard of size n x n. We have to find the
number of ways we can place n rooks, such that they cannot attack each other. Here two ways
will be considered different if in one of the ways, some cell of the chessboard is occupied, and
another way, the cell is not occupied. (We know that rooks can attack each other if they are
either on the same row or on the same column).
So, if the input is like 3, then the output will be 6
To solve this, we will follow these steps −
f = factorial of n
return f
Let us see the following implementation to get better understanding −
 Live Demo
import math
class Solution:
   def solve(self, n):
      return math.factorial(n)
ob = Solution()
print(ob.solve(3))
3
6
Java program to calculate the factorial of a given number using while loop

A factorial of a particular number (n) is the product of all the numbers from 0 to n (including n) i.e. Factorial of the number 5 will be 1*2*3*4*5 = 120.
 To find the factorial of a given number.
 Create a variable factorial initialize it with 1.
 start while loop with condition i (initial value 1) less than the given number.
 In the loop, multiple factorials with i and assign it to factorial and increment i.
 Finally, print the value of factorial.
import java.util.Scanner;
public class FactorialWithWhileLoop {
   public static void main(String args[]){
      int i =1, factorial=1, number;
      System.out.println("Enter the number to which you need to find the factorial:");
      Scanner sc = new Scanner(System.in);
      number = sc.nextInt();

      while(i <=number) {
         factorial = factorial * i;
         i++;
      }
      System.out.println("Factorial of the given number is:: "+factorial);
   }
}
Enter the number to which you need to find the factorial:
5
Factorial of the given number is:: 120
How to increase the size of points on a scatterplot if the points are drawn based on another sequence using ggplot2 in R?

When we draw a scatterplot using ggplot2 with points based on a sequence of values then the size of the points might be very small for the small values. As a result, it becomes a little difficult to view the points. Therefore, we might want to increase the size of those points. It can be done by using scale_size_continuous function in which we can set a range for the points size.
Consider the below data frame −
 Live Demo
x<-rnorm(10,1)
y<-rnorm(10,2)
Pair<-1:10
df<-data.frame(x,y,Pair)
df
      x       y         Pair
1 0.2722750 0.7855144    1
2 0.6708724 2.8385502    2
3 1.6939261 1.7415868    3
4 0.5773440 2.1596557    4
5 0.1965571 0.7356820    5
6 0.3368027 1.4774414    6
7 0.8248820 2.8211750    7
8 -0.3364834 2.5258274   8
9 -0.3229903 1.1579749   9
10 -1.1594988 1.0636472  10
Loading ggplot2 package and creating a scatterplot with points size based on Pair column −
library(ggplot2)
ggplot(df,aes(x,y,size=Pair))+geom_point()
Creating the scatterplot with a range of point size −
ggplot(df,aes(x,y,size=Pair))+geom_point()+scale_size_continuous(range = c(2,5))
How to change display mode with Java Swings

To change display mode with Java Swings, use the setDisplayMode() method. Here, we have set the Display mode as:
new DisplayMode(800, 600, 32, 60));
Now, when you will run the program, the frame would be visible in a different resolution than the actual set resolution of your system.
The following is an example to change display mode with Java Swings:
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setSize(800, 600);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      GraphicsDevice graphics = GraphicsEnvironment.getLocalGraphicsEnvironment()
         .getDefaultScreenDevice();
      graphics.setFullScreenWindow(frame);
      graphics.setDisplayMode(new DisplayMode(800, 600, 32, 60));
      frame.setVisible(true);
   }
}
The output is as follows displaying a new display mode. Current mode of the system is 1366x768 and we have set 800x600 for the frame:
\vphantom - Tex Command

\vphantom - vertical phantom.
{ \vphantom #1 }
The box created by \vphantom has the height and depth of its argument, but its width is zero (so it doesn't contribute to any horizontal spacing issues). In other words, \hphantom  creates vertical space equal to that produced by its argument, but doesn't create any horizontal space.

\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c

(abc)(ab?c)



\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c

(abc)(ab?c)


\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c

    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
C++ List Library - sort() Function

The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison.
Following is the declaration for std::list::sort() function form std::list header.
void sort();

None
None
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::list::sort() function.
#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l = {1, 4, 2, 5, 3};

   cout << "Contents of list before sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   l.sort();

   cout << "Contents of list after sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Contents of list before sort operation
1
4
2
5
3
Contents of list after sort operation
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
How to create file of particular size in Python?

To create a file of a particular size, just seek to the byte number(size) you want to create the file of and write a byte there.
with open('my_file', 'wb') as f:
    f.seek(1024 * 1024 * 1024) # One GB
    f.write('0')
This creates a sparse file by not actually taking up all that space. To create a full file, you should write the whole file:
with open('my_file', 'wb') as f:
    num_chars = 1024 * 1024 * 1024
    f.write('0' * num_chars)
Python program to sort a list according to the second element in the sublist.

List is given, our task is to sort a list according to the second element in the sublist. Here we apply simple bubble sort.
Input : [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]]
Output : [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
Step 1: Given a list.
Step 2: We have tried to access the second element of the sublists using the nested loops.
Step 3: Traverse through all array elements.
Step 4: Last i elements are already in place.
Step 5: traverse the array from 0 to n-i-1.
Step 6: Swap if the element found is greater than the next element.
# Python program to sort the lists using the second element of sublist
# In place way to sort, use of third variable.
def sortlist(A):
   l = len(A)
   for i in range(0, l):
   for j in range(0, l-i-1):
   if (A[j][1] > A[j + 1][1]):
      tempo = A[j]
      A[j]= A[j + 1]
      A[j + 1]= tempo
      return A

   # Driver Code
A = [['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]]
print(sortlist(A))
[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
Lagrange Interpolation

For constructing new data points within a range of a discrete set of given data point, the interpolation technique is used. Lagrange interpolation technique is one of them. When the given data points are not evenly distributed, we can use this interpolation method to find the solution. For the Lagrange interpolation, we have to follow this equation.
Input:
List of x and f(x) values. find f(3.25)
x: {0,1,2,3,4,5,6}
f(x): {0,1,8,27,64,125,216}
Output:
Result after Lagrange interpolation f(3.25) = 34.3281
largrangeInterpolation(x: array, fx: array, x1)
Input − x array and fx array for getting previously known data, and point x1.
Output: The value of f(x1).
Begin
   res := 0 and tempSum := 0
   for i := 1 to n, do
      tempProd := 1
      for j := 1 to n, do
         if i ≠ j, then
            tempProf := tempProd * (x1 – x[j])/(x[i] – x[j])
      done

      tempPord := tempProd * fx[i]
      res := res + tempProd
   done
   return res
End
#include<iostream>
#define N 6
using namespace std;

double lagrange(double x[], double fx[], double x1) {
   double res = 0, tempSum = 0;

   for(int i = 1; i<=N; i++) {
      double tempProd = 1;         //for each iteration initialize temp product
      for(int j = 1; j<=N; j++) {
         if(i != j) {                 //if i = j, then denominator will be 0
            tempProd *= (x1 - x[j])/(x[i] - x[j]);     //multiply each term using formula
         }
      }
      tempProd *= fx[i];                //multiply f(xi)
      res += tempProd;
   }
   return res;
}

main() {
   double x[N+1] = {0,1,2,3,4,5,6};
   double y[N+1] = {0,1,8,27,64,125,216};
   double x1 = 3.25;
   cout << "Result after lagrange interpolation f("<<x1<<") = " << lagrange(x, y, x1);
}
Result after lagrange interpolation f(3.25) = 34.3281
Delete Tree Nodes in C++

Suppose we have a tree, this tree is rooted at node 0, this is given as follows −
Number of nodes is nodesValue of ith node is value[i]Parent of ith node is parent[i]
Number of nodes is nodes
Value of ith node is value[i]
Parent of ith node is parent[i]
We have to remove every subtree whose sum of values of nodes is 0, after doing that return the number of nodes remaining in the tree. So if the tree is like −
There are 7 nodes, the output will be 2
To solve this, we will follow these steps −
Create a map called children
define a method called dfs(), this will take node, an array value and graph
temp := a pair (value[node], 1)
for i in range 0 to size of graph[node]temp2 := dfs(graph[node, i], value, graph)increase first by first of temp2, increase second by second of temp2
temp2 := dfs(graph[node, i], value, graph)
increase first by first of temp2, increase second by second of temp2
if first of temp is 0, then ans := ans – second of temp, set second of temp := 0
return temp
From the main method, it will take nodes, parents array and values array
n := number of values present in values array
ans := n
define an array graph of size n + 1
for i in range 1 to n – 1insert i into graph[parent[i]]
insert i into graph[parent[i]]
dfs(0, value, graph)
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   map <int, int> children;
   int ans;
   pair <int, int> dfs(int node, vector<int>& value, vector <int> graph[]){
      pair <int, int> temp = {value[node], 1};
      for(int i = 0; i < graph[node].size(); i++){
         pair <int, int> temp2 = dfs(graph[node][i], value, graph);
         temp.first += temp2.first;
         temp.second += temp2.second;
      }
      if(temp.first == 0){
         ans -= temp.second;
         temp.second = 0;
      }
      return temp;
   }
   int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {
      int n = value.size();
      ans = n;
      children.clear();
      vector < int > graph[n + 1];
      for(int i = 1; i < n; i++){
         graph[parent[i]].push_back(i);
      }
      dfs(0, value, graph);
      return ans;
   }
};
main(){
   vector<int> v1 = {-1,0,0,1,2,2,2};
   vector<int> v2 = {1,-2,4,0,-2,-1,-1};
   Solution ob;
   cout << (ob.deleteTreeNodes(7,v1, v2));
}
7
[-1,0,0,1,2,2,2]
[1,-2,4,0,-2,-1,-1]
2
Bitwise Operators in C++

There are 3 bitwise operators available in c++. These are the bitwise AND(&), bitwise OR(|) and the bitwise XOR(^).
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive AND operator must be of integral types. For example,
#include <iostream>  
using namespace std;  
int main() {  
   unsigned short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xAAAA;      // pattern 1010 ...  
   cout << hex << ( a & b ) << endl;
}
This gives the output −
0
The bitwise OR operator (|) compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive OR operator must be of integral types. For example,
#include <iostream>  
using namespace std;  
int main() {  
   unsigned short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xAAAA;      // pattern 1010 ...  
   cout << hex << ( a | b ) << endl;
}
This gives the output −
ffff
The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise exclusive OR operator must be of integral types. For example,
#include <iostream>  
using namespace std;  
int main() {  
   short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xFFFF;      // pattern 1111 ...  
   cout  << hex << ( a ^ b ) << endl;
}
This gives the output −
aaaa
Which represents the pattern 1010...
AWT TextListener Interface

The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method. 
Following is the declaration for java.awt.event.TextListener interface:
public interface TextListener
   extends EventListener
void textValueChanged(TextEvent e) 
Invoked when the value of the text has changed.
This interface inherits methods from the following interfaces:
java.awt.EventListener
java.awt.EventListener
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private TextField textField;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showTextListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextListenerDemo(){
      headerLabel.setText("Listener in action: TextListener");      

      textField  = new TextField(10);

      textField.addTextListener(new CustomTextListener());
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " 
            + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }

   class CustomTextListener implements TextListener {
      public void textValueChanged(TextEvent e) {
         statusLabel.setText("Entered text: " + textField.getText());               
      }
   }
}
Compile the program using command prompt. Go to D:/ > AWT  and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
Verify the following output

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page