code-rag-bench/online-tutorials huggingface dataset:
Moving balls in Tkinter Canvas

Tkinter is a standard Python library which is used to create GUI-based applications. To create a simple moving ball application, we can use the Canvas widget which allows the user to add images, draw shapes, and animating objects. The application has the following components,
A Canvas widget to draw the oval or ball in the window.
A Canvas widget to draw the oval or ball in the window.
To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom).
To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom).
To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration.
To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration.
Finally, execute the code to run the application.
Finally, execute the code to run the application.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Make the window size fixed
win.resizable(False,False)

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()

# Create an oval or ball in the canvas widget
ball=canvas.create_oval(10,10,50,50, fill="green3")

# Move the ball
xspeed=yspeed=3

def move_ball():
   global xspeed, yspeed

   canvas.move(ball, xspeed, yspeed)
   (leftpos, toppos, rightpos, bottompos)=canvas.coords(ball)
   if leftpos <=0 or rightpos>=700:
      xspeed=-xspeed

   if toppos <=0 or bottompos >=350:
      yspeed=-yspeed

   canvas.after(30,move_ball)

canvas.after(30, move_ball)

win.mainloop()
Running the above code will display an application window that will have a movable ball in the canvas.
How to calculate power of three using C#?

For power of 3, se the power as 3 and apply a recursive code like the following snippet −
if (p!=0) {
return (n * power(n, p - 1));
}
Let’s say the number is 5, then the iterations would be −
power(5, 3 - 1)); // 25
power (5,2-1): // 5
The above would return5*25 i.e 125 as shown below −
 Live Demo
using System;
using System.IO;

public class Demo {
   public static void Main(string[] args) {
      int n = 5;
      int p = 3;
      long res;
      res = power(n, p);
      Console.WriteLine(res);
   }
   static long power (int n, int p) {
      if (p!=0) {
         return (n * power(n, p - 1));
      }
      return 1;
   }
}
125
Why would we call cin.clear() and cin.ignore() after reading input in C++?

In C++ the cin is used to take input from user. Sometimes for some reasons some error flags are set. In that time the cin does not take any input. Sometimes it takes some other characters. So if we clear the cin, then the error flags are reset. Then we can use getline(), get() etc. functions.
The ignore() function is another stream input function. If we write the function like this
cin.ignore(1000, ‘\n’)
Then it will ignore next 1000 characters, otherwise ignore lines until ‘\n’ is found.
Cypress - Architecture and Environment Setup

Cypress architecture is illustrated in the below diagram −
The source of the above diagram is https://www.tutorialspoint.com/cypress-architecturetest-automation
Automation tools like Selenium work by running outside the browser. However, the Cypress has a different architecture. It runs within the browser. Cypress is basically based on the server - Node.js.
There is a continued interaction of Cypress with the Node.js and they work in coordination with each other. As a result, Cypress can be utilised for testing both the front and backend of the application.
Cypress is thus, capable of handling the tasks performed at a real time on the UI and simultaneously can also perform the actions outside of the browser.
The basic differences between Cypress and Selenium are listed below −
For Cypress environment setup, visit the link −https://nodejs.org/en/download/. The screen that will appear is given below −
There shall be both Windows and macOS Installer. We have to get the package as per the local operating system.
For a 64- bit Windows configuration, the following pop-up comes up to save the installer.
Once the installation is done, a nodejs file gets created in the Program files. The path of this file should be noted. Then, enter environment variables from the Start, as shown below −
In the System Properties pop-up, move to Advanced, click on Environment Variables. Then click on OK.
In the Environment Variables pop-up, move to the System variables section and click on New.
Enter NODE_HOME and the node.js path (noted earlier) in the Variable name and the Variable value fields respectively in the New System Variable pop-up.
Once the path of the node.js file is set, we shall create an empty folder (say cypressautomation) in any desired location.
Next, we need to have a JavaScript editor to write the code for Cypress. For this, we can download Visual Studio Code from the link https://code.visualstudio.com/
As per the local operating system, choose the correct package −
Once the executable file is downloaded, and all the installation steps are completed, the Visual Studio Code gets launched.
Select the option Open Folder from the File menu. Then, add the CypressAutomation folder (that we have created before) to the Visual Studio Code.
We need to create the package.json file with the below command from terminal −
We have to enter details like the package name, description, and so on, as mentioned in the image given below −
npm init

Once done, the package.json file gets created within the project folder with the information we have provided.
Once done, the package.json file gets created within the project folder with the information we have provided.
Finally, to install Cypress run the command given below −
npm install cypress --save-dev

You will get the following output −

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
Find smallest number with given number of digits and sum of digits in C++

In this problem, we are given two values that are the sum (denoting the sum
of digits) and digit (denoting the number of digits). Our task is to find the
smallest number with a given number of digits and sum of digits.
Let’s take an example to understand the problem,
sum = 15, dgiti = 2
69
All 2 digits numbers with sum 15 are : 69, 78, 87, 96.
A simple solution to the problem is by considering all the numbers with digit
count as digit and find the smallest number whose sum of digit is equal to
the sum.
An efficient solution is using the greedy approach. We will create the
number by filling the elements from the last digit i.e. the LSB of the number.
We will consider the largest possible element for LSB and then go for the
next position.
We will try to keep the LSB as large as possible and MSB as small as possible.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
void findSmallestNumWithSum(int digit, int sum) {
   if (sum == 0) {
      if(digit == 1)
         cout<<"Smallest number is 0";
      else
         cout<<"Smallest number with sum cannot be found";
      return ;
   }
   if (sum > 9*digit) {
      cout<<"Smallest number with sum cannot be found";
      return ;
   }
   int number[digit];
   sum -= 1;
   for (int i = digit-1; i>0; i--) {
      if (sum > 9) {
         number[i] = 9;
         sum -= 9;
      } else {
         number[i] = sum;
         sum = 0;
      }
   }
   number[0] = sum + 1;
   cout<<"Smallest number is ";
   for (int i=0; i<digit; i++)
      cout<<number[i];
}
int main() {
   int sum = 15, digit = 3;
   findSmallestNumWithSum(digit, sum);
   return 0;
}
Smallest number is 159
Copy from clipboard using Python and Tkinter

To copy from clipboard, we can use the clipboard_get() method of Tkinter. Let's take an example and see how to get the data from the clipboard and display it on a Tkinter window.
Import the tkinter library and create an instance of tkinter frame.
Import the tkinter library and create an instance of tkinter frame.
Set the size of the frame using geometry method.
Set the size of the frame using geometry method.
Next, call clipboard_get() to get the text from the clipboard and store the data in a variable "cliptext".
Next, call clipboard_get() to get the text from the clipboard and store the data in a variable "cliptext".
Create a label to the display the clipboard text. Pass cliptext as text, "text=cliptext".
Create a label to the display the clipboard text. Pass cliptext as text, "text=cliptext".
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the tkinter library
from tkinter import *

# Instance of tkinter canvas
win = Tk()
win.geometry("700x250")
win.title("Data from Clipboard")

# Get the data from the clipboard
cliptext = win.clipboard_get()

# Label to print clipboard text
lab=Label(win, text = cliptext, font=("Calibri",15,"bold"))
lab.pack(padx=20, pady=50)

# Run the mainloop
win.mainloop()
It will produce the following output −
It will display the contents of the clipboard on the window.
Char.IsDigit() Method in C#

The Char.IsDigit() method in C# indicates whether the specified Unicode character is categorized as a decimal digit.
Following is the syntax −
public static bool IsDigit (char ch);
Above, the parameter ch is the Unicode character to evaluate.
Let us now see an example to implement the Char.IsDigit() method −
using System;
public class Demo {
   public static void Main(){
      bool res;
      char val = 'g';
      Console.WriteLine("Value = "+val);
      res = Char.IsDigit(val);
      Console.WriteLine("Is the value a digit? = "+res);
   }
}
This will produce the following output −
Value = g
Is the value a digit? = False
Let us now see another example −
using System;
public class Demo {
   public static void Main(){
      bool res;
      char val = '2';
      Console.WriteLine("Value = "+val);
      res = Char.IsDigit(val);
      Console.WriteLine("Is the value a digit? = "+res);
   }
}
This will produce the following output −
Value = 2
Is the value a digit? = True
Java - String charAt() Method

This method returns the character located at the String's specified index. The string indexes start from zero.
Here is the syntax of this method −
public char charAt(int index)

Here is the detail of parameters −
index − Index of the character to be returned.
index − Index of the character to be returned.
This method returns a char at the specified index.
public class Test {

   public static void main(String args[]) {
      String s = "Strings are immutable";
      char result = s.charAt(8);
      System.out.println(result);
   }
}
This will produce the following result −
a


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
MongoDB - GridFS

GridFS is the MongoDB specification for storing and retrieving large files such as images, audio files, video files, etc. It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB.
GridFS divides a file into chunks and stores each chunk of data in a separate document, each of maximum size 255k.
GridFS by default uses two collections fs.files and fs.chunks to store the file's metadata and the chunks. Each chunk is identified by its unique _id ObjectId field. The fs.files serves as a parent document. The files_id field in the fs.chunks document links the chunk to its parent.
Following is a sample document of fs.files collection −
{
   "filename": "test.txt",
   "chunkSize": NumberInt(261120),
   "uploadDate": ISODate("2014-04-13T11:32:33.557Z"),
   "md5": "7b762939321e146569b07f72c62cca4f",
   "length": NumberInt(646)
}
The document specifies the file name, chunk size, uploaded date, and length.
Following is a sample document of fs.chunks document −
{
   "files_id": ObjectId("534a75d19f54bfec8a2fe44b"),
   "n": NumberInt(0),
   "data": "Mongo Binary Data"
}
Now, we will store an mp3 file using GridFS using the put command. For this, we will use the mongofiles.exe utility present in the bin folder of the MongoDB installation folder.
Open your command prompt, navigate to the mongofiles.exe in the bin folder of MongoDB installation folder and type the following code −
>mongofiles.exe -d gridfs put song.mp3
Here, gridfs is the name of the database in which the file will be stored. If the database is not present, MongoDB will automatically create a new document on the fly. Song.mp3 is the name of the file uploaded. To see the file's document in database, you can use find query −
>db.fs.files.find()
The above command returned the following document −
{
   _id: ObjectId('534a811bf8b4aa4d33fdf94d'), 
   filename: "song.mp3", 
   chunkSize: 261120, 
   uploadDate: new Date(1397391643474), md5: "e4f53379c909f7bed2e9d631e15c1c41",
   length: 10401959 
}
We can also see all the chunks present in fs.chunks collection related to the stored file with the following code, using the document id returned in the previous query −
>db.fs.chunks.find({files_id:ObjectId('534a811bf8b4aa4d33fdf94d')})
In my case, the query returned 40 documents meaning that the whole mp3 document was divided in 40 chunks of data.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Convert string to datetime in Python with timezone - GeeksforGeeks

14 Sep, 2021
Prerequisite: Datetime module
In this article, we will learn how to get datetime object from time string using Python.
To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. 
Syntax : datetime.strptime(date_string, format)
Parameters :
date_string : Specified time string containing of which datetime object is required. **Required
format : Abbreviation format of date_string
Returns : Returns the datetime object of given date_string
List of the acceptable format that can be passed to strptime():
Example 1: Converting datetime string to datetime
Python3
# Python3 code to demonstrate# Getting datetime object using a date_string  # importing datetime moduleimport datetime  # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05.004573 +0530'print("string datetime: ")print(date_string)print("datestring class is :", type(date_string))  # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(    date_string, '%Y-%m-%d %H:%M:%S.%f %z')  print("converted to datetime:")  # Printing datetimeprint(datetime_obj)  # Checking class of datetime_obj.print("datetime_obj class is :", type(datetime_obj))
Output:
string datetime: 
2021-09-01 15:27:05.004573 +0530
datestring class is : <class 'str'>
converted to datetime:
2021-09-01 15:27:05.004573+05:30
datetime_obj class is : <class 'datetime.datetime'>
Example 2: Converting datetime string to datetime
Python3
# Python3 code to demonstrate# Getting datetime object using a date_string  # importing datetime moduleimport datetime  # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05'  # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')  # Printing datetimeprint(datetime_obj)
Output:
2021-09-01 15:27:05
In this example, microseconds and time zone parts are removed from first example, so we need to remove microseconds and time zone abbreviations also from format string
Example 3: Converting datetime string to datetime
Python3
# Python3 code to demonstrate# Getting datetime object using a date_string  # importing datetime moduleimport datetime  # datestring for which datetime_obj requireddate_string = 'Sep 01 2021 03:27:05 PM'  # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%b %d %Y %I:%M:%S %p')  # Printing datetimeprint(datetime_obj)
Output:
2021-09-01 15:27:05
Picked
Python datetime-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.7

Tryit: Canvas with a text
Java Examples - Display Time in different Country's format

How to display time in different country's format?
Following example uses Locale class & DateFormat class to display date in different Country's format.
import java.text.DateFormat;
import java.util.*;

public class Main {
   public static void main(String[] args) throws Exception {
      Date d1 = new Date();
      System.out.println("today is "+ d1.toString());    
      Locale locItalian = new Locale("it","ch");
      DateFormat df = DateFormat.getDateInstance (DateFormat.FULL, locItalian);
      System.out.println("today is in Italian Language  in Switzerland Format : "+ df.format(d1));
   }
}
The above code sample will produce the following result.
today is Mon Jun 22 02:37:06 IST 2009
today is in Italian Language in Switzerland Format : sabato, 22. febbraio 2014

 Print
 Add Notes
 Bookmark this page
Convert a Queue to a List in Java

In order to convert a Queue to a List in Java, we can create an LinkedList and pass the Queue as an argument in the parameterized constructor of an ArrayList. This can be done as follows −
Queue q = new LinkedList();
List l = new ArrayList(q);
The quickest way is used to LinkedList in the first place which can be used both as a List and a Queue. This can be done as follows −
Queue q = new LinkedList();
List l = (List) q;
Let us see a program to convert a queue to a list −
 Live Demo
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Example {
   public static void main(String[] args) {
      Queue q = new LinkedList();
      q.add("Good");
      q.add("Morning");
      List l = (List) q;
      System.out.println(l);
   }
}
[Good, Morning]
How to find duplicates in an array using set() and filter() methods in JavaScript?

To remove duplicates in an array we have many logical methods, but advanced javascript has provided some methods so that the task of removing duplicates has become very simple. Some of those methods are set() and filter(). For better understanding lets' discuss each method individually.
The important use of the set() method is that it only allows unique values. In other words, it will automatically remove duplicates and makes the task easy for us. The Set() method won't take any logical approach in removing duplicates.
In the following example, the duplicates in the provided array have been removed without any logical approach by using set() method. 
Live Demo
<html>
<body>
<script>
   var dupNames = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];
   var uniArr = [...new Set(dupNames)];
   document.write("Before removing :" +" "+ dupNames);
   document.write("</br>");
   document.write("After using set() method :" +" "+ uniArr);
</script>
</body>
</html>
Before removing : John,Ram,Rahim,Remo,Ram,Rahim
After using set() method : John,Ram,Rahim,Remo
In the following example, using filter() method each element is scrutinized whether it is repeated two or more times. If any element found repeated two or more times then only one of its value is permitted and displayed as shown in the output.
Live Demo
<html>
<body>
<script>
   var dupnam = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];
   var x = (dupname) => dupname.filter((v,i) => dupname.indexOf(v) === i)
   document.write("Before removing : " +" "+ dupname);  
   document.write("</br>");
   document.write("After filter() method :" +" "+x(dupname));
</script>
</body>
</html>
Before removing : John,Ram,Rahim,Remo,Ram,Rahim
After filter() method : John,Ram,Rahim,Remo
Python - Move a column to the first position in Pandas DataFrame?

Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns −
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6]
   }
)


Move column "Roll Number" to 1st position by first popping the column out −
shiftPos = dataFrame.pop("Roll Number")
Insert column on the 1st position −
dataFrame.insert(0, "Roll Number", shiftPos)

Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6]
   }
)

print"DataFrame ...\n",dataFrame

# move column "Roll Number" to 1st position
shiftPos = dataFrame.pop("Roll Number")

# insert column on the 1st position
dataFrame.insert(0, "Roll Number", shiftPos)

print"\nUpdated DataFrame after moving a column to the first position...\n",dataFrame
This will produce the following output −
DataFrame ...
   Result   Roll Number   Student
0    Pass             5      Jack
1    Fail            10     Robin
2    Pass             3       Ted
3    Fail             8      Marc
4    Pass             2  Scarlett
5    Pass             9       Kat
6    Pass             6      John

Updated DataFrame after moving a column to the first position...
   Roll Number   Result   Student
0            5     Pass      Jack
1           10     Fail     Robin
2            3     Pass       Ted
3            8     Fail      Marc
4            2     Pass  Scarlett
5            9     Pass       Kat
6            6     Pass      John
How to use shapiro wilk test to check normality of an R data frame column?

To apply shapiro wilk test for normality on vectors, we just simply name the vector inside shapiro.test function but if we want to do the same for an R data frame column then the column will have to specify the column in a proper way. For example, if the data frame name is df and the column name is x then the function will work as shapiro.test(df$x).
 Live Demo
x1<-rnorm(1000,1.5)
df1<-data.frame(x1)
shapiro.test(df1$x1)
   Shapiro-Wilk normality test
data: df1$x1
W = 0.99886, p-value = 0.792
 Live Demo
x2<-runif(1000,2,10)
df2<-data.frame(x2)
shapiro.test(df2$x2)
   Shapiro-Wilk normality test
data: df2$x2
W = 0.9581, p-value = 2.562e-16
 Live Demo
x3<-rpois(4000,2)
df3<-data.frame(x3)
shapiro.test(df3$x3)
   Shapiro-Wilk normality test
data: df3$x3
W = 0.91894, p-value < 2.2e-16
 Live Demo
x4<-rpois(4000,5)
df4<-data.frame(x4)
shapiro.test(df4$x4)
   Shapiro-Wilk normality test
data: df4$x4
W = 0.97092, p-value < 2.2e-16
 Live Demo
x5<-sample(1:5,5000,replace=TRUE)
df5<-data.frame(x5)
shapiro.test(df5$x5)
   Shapiro-Wilk normality test
data: df5$x5
W = 0.88902, p-value < 2.2e-16
 Live Demo
x6<-sample(1:10,5000,replace=TRUE)
df6<-data.frame(x6)
shapiro.test(df6$x6)
   Shapiro-Wilk normality test
data: df6$x6
W = 0.93373, p-value < 2.2e-16
 Live Demo
x7<-sample(1:100,5000,replace=TRUE)
df7<-data.frame(x7)
shapiro.test(df7$x7)
   Shapiro-Wilk normality test
data: df7$x7
W = 0.9556, p-value < 2.2e-16
 Live Demo
x8<-sample(2500:3500,5000,replace=TRUE)
df8<-data.frame(x8)
shapiro.test(df8$x8)
   Shapiro-Wilk normality test
data: df8$x8
W = 0.95117, p-value < 2.2e-16
 Live Demo
x9<-rbinom(5000,10,0.5)
df9<-data.frame(x9)
hapiro.test(df9$x9)
   Shapiro-Wilk normality test
data: df9$x9
W = 0.96629, p-value < 2.2e-16
 Live Demo
x10<-rbinom(5000,1000,0.5)
df10<-data.frame(x10)
shapiro.test(df10$x10)
   Shapiro-Wilk normality test
data: df10$x10
W = 0.9993, p-value = 0.04748
What does colon ':' operator do in Python?

The : symbol is used for more than one purpose in Python
As slice operator with sequence −
The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default. If second is omitted, it is set to end of sequence.
>>> a=[1,2,3,4,5]
>>> a[1:3]
[2, 3]
>>> a[:3]
[1, 2, 3]
>>> a[2:]
[3, 4, 5]
>>> s='computer'
>>> s[:3]
'com'
>>> s[3:6]
'put'
The − symbol is also used to start an indent suite of statements in case of if, while, for, def and class statements
if expr:
   stmt
while expr:
   stmt1
   stmt2
for x in sequence:
   stmt1
   stmt2
def  function1():
   stmt1
   stmt2
What is the difference between static classes and non-static inner classes in Java?

Following are the notable differences between inner classes and static inner classes.
The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class.
public class Outer {
   int num = 234;
   static int data = 300;
   public static class Inner{
      public static void main(String args[]){
         Outer obj = new Outer();
         System.out.println(obj.num);
         System.out.println(data);
      }
   }
}
234
300
The non inner class can access the members of its outer class (both instance and static) directly without instantiation.
Live Demo
public class Outer2 {
   int num = 234;
   static int data =300;
   public class Inner{
      public void main(){
         System.out.println(num);
         System.out.println(data);
      }
   }
   public static void main(String args[]){
      new Outer2().new Inner().main();
   }
}
234
300
You cannot have members of a non-static inner class static. Static methods are allowed only in top-level classes and static inner classes.
PyQt5 - Create a digital clock - GeeksforGeeks

22 Apr, 2020
In this article we will see how to create a digital clock using PyQt5, this digital clock will basically tells the current time in the 24 hour format.
In order to create a digital clock we have to do the following:
1. Create a vertical layout2. Create label to show the current time and put it in the layout and align it to the center.3. Create a QTimer object4. Add action to the QTimer object such that after every 1sec action method get called.5. Inside the action method get the current time and show that time with the help of label.
Below is the implementation –
# importing required librarieimport sysfrom PyQt5.QtWidgets import QApplication, QWidgetfrom PyQt5.QtWidgets import QVBoxLayout, QLabelfrom PyQt5.QtGui import QFontfrom PyQt5.QtCore import QTimer, QTime, Qt    class Window(QWidget):      def __init__(self):        super().__init__()          # setting geometry of main window        self.setGeometry(100, 100, 800, 400)          # creating a vertical layout        layout = QVBoxLayout()          # creating font object        font = QFont('Arial', 120, QFont.Bold)          # creating a label object        self.label = QLabel()          # setting centre alignment to the label        self.label.setAlignment(Qt.AlignCenter)          # setting font to the label        self.label.setFont(font)          # adding label to the layout        layout.addWidget(self.label)          # setting the layout to main window        self.setLayout(layout)          # creating a timer object        timer = QTimer(self)          # adding action to timer        timer.timeout.connect(self.showTime)          # update the timer every second        timer.start(1000)      # method called by timer    def showTime(self):          # getting current time        current_time = QTime.currentTime()          # converting QTime object to string        label_time = current_time.toString('hh:mm:ss')          # showing it to the label        self.label.setText(label_time)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # showing all the widgetswindow.show()  # start the appApp.exit(App.exec_())
Output :
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
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Difference between OpenSUSE and Fedora

28 Jun, 2022
1. OpenSUSE : OpenSUSE is a Linux distribution developed by The openSUSE Project. It was initially released on October 2005. It was developed for creating usable open-source tools for software developers and system administrators and it also provides a user-friendly environment and feature-rich server environment. 
2. Fedora : Fedora OS is a Linux based open-source operating system developed by Red Hat. It is open-source and it is freely available for use. It uses the DNF package manager and gnome environment along with anaconda installer. It supports 3 platforms, which are Workstation Fedora designed for Personal Computers, Fedora Server designed for servers and Fedora Atomic designed for cloud computing.  
Difference between OpenSUSE and Fedora :
raj2002
Difference Between
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2020 | Question 23

26 May, 2021
Consider a relational database containing the following schemas.
The primary key of each table is indicated by underlining the constituent fields.
SELECT s.sno, s.sname
FROM Suppliers s, Catalogue c
WHERE s.sno=c.sno AND
    cost > (SELECT AVG (cost)
            FROM Catalogue
            WHERE pno = ‘P4’
            GROUP BY pno) ; 
The number of rows returned by the above SQL query is(A) 4(B) 5(C) 0(D) 2Answer: (A)Explanation: The resultant table after the execution of the above query will be:
Result of the inner query will be 225(avg(200,250)) and subsequently every such tuple which has s.sno=c.sno and cost>225 will get selected from the Cartesian product of supplier and catalogue table.
Option (A) is correct.Quiz of this Question
parthbanathia
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP program to print the number pattern

To print the number pattern in PHP, the code is as follows −
 Live Demo
<?php
function num_pattern($val)
{
   $num = 1;
   for ($m = 0; $m < $val; $m++)
   {
      for ($n = 0; $n <= $m; $n++ )
      {
         echo $num." ";
      }
      $num = $num + 1;
      echo "\n";
   }
}
$val = 6;
num_pattern($val);
?>
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
This is similar to generating a star pattern, the only difference being, numbers are generated instead of stars. The function ‘num_pattern’ is defined that takes the limit as a parameter. The limit value is iterated over and the number is printed and relevant line breaks are also generated in between. The function is called by passing this limit value and the relevant output is generated on the console.
Pairwise Software Testing

20 Jun, 2019
Pairwise Testing is a type of software testing in which permutation and combination method is used to test the software. Pairwise testing is used to test all the possible discrete combinations of the parameters involved.
Pairwise testing is a P&C based method, in which to test a system or an application, for each pair of input parameters of a system, all possible discrete combinations of the parameters are tested. By using the conventional or exhaustive testing approach it may be hard to test the system but by using the permutation and combination method it can be easily done.
Example:Suppose there is a software to be tested which has 20 inputs and 20 possible settings for each input so in that case there are total 20^20 possible inputs to be tested. Therefore in this case, exhaustive testing is impossible even all combinations are tried to be tested.
Graphical Representation of Pairwise Testing:
Generalized form of Pairwise Testing:The generalized form of pairwise testing is N-wise testing. Basically sorting is applied to the set,
X = n{i}, 
so that P = P{i} gets ordered too. 
Let the sorted set be a N tuple:
P{s} = { P{i} } ;  i  |R(P{i})| < |R(P{j})|
Now take the set X(2) = { P{N-1}, P{N-2} } 
And call it the pairwise testing. Generalizing further take the set
X(3) = { P{N-1}, P{N-2}, P{N-3} }
And call it the 3-wise testing. Similarly, we can say,
X(K) = { P{N-1}, P{N-2}, ..., P{N-K} } 
K-wise testing.The N-wise testing is all possible combinations from the above formula.
Advantages of Pairwise Testing:The advantages of pairwise testing are:
Pairwise testing reduces the number of execution of test cases.
Pairwise testing increases the test coverage almost up to hundred percentage.
Pairwise testing increases the defect detection ratio.
Pairwise testing takes less time to complete the execution of the test suite.
Pairwise testing reduces the overall testing budget for a project.
Disadvantages of Pairwise Testing:The disadvantages of pairwise testing are:
Pairwise testing is not beneficial if the values of the variables are inappropriate.
In pairwise testing it is possible to miss the highly probable combination while selecting the test data.
In pairwise testing, defect yield ratio may be reduced if a combination is missed.
Pairwise testing is not useful if combinations of variables are not understood correctly.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modify the default font in Python Tkinter

In order to change the default behavior of tkinter widgets, we generally override the option_add() method. The properties and values passed to option_add() method will reflect the changes in all the widgets in the application. Thus, changing the default font will affect the font for all the widgets defined in the application.
Here we will pass two parameters into the option_add() method, i.e., option_add("*font", "font-family font-size font-style font-orientation").
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("600x400")

#Change the default Font that will affect in all the widgets
win.option_add( "*font", "lucida 20 bold italic" )
win.resizable(False, False)

#Create a Label
Label(win, text="This is a New Line").pack()
Button(win, text="Button-1", width=10).pack()

win.mainloop()
Running the above code will set the default font as "lucida 20 bold italic" for all the widgets that uses textual information.
Now, go back to the program, remove the following line, and run it again.
win.option_add( "*font", "lucida 20 bold italic" )
The text will now appear in the default font −
MySQL | AES_ENCRYPT ( ) Function

25 Aug, 2021
The MySQL AES_ENCRYPT function is used for encrypting a string using Advanced Encryption Standard (AES) algorithm. The MySQL AES_ENCRYPT function encodes the data with 128 bits key length but it can be extended up to 256 bits key length. It encrypts a string and returns a binary string. 
The value returned by the AES_ENCRYPT function is a binary string or NULL if the argument in NULL. The AES_ENCRYPT function accepts two parameters which are the encrypted string and a key string used to encrypt the string. 
Syntax:  
AES_ENCRYPT(str, key_str)
Parameters Used:  
str – It is used to specify the plain string.
key_str – It is used to specify the String which is used to encrypt the str.
Return Value: The AES_ENCRYPT function in MySQL returns a binary string. 
Supported Versions of MySQL:  
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing AES_ENCRYPT function on a string.  
SELECT
AES_ENCRYPT('ABC', 'key'); 
Output:  
\\YJ??f&K?M?q?* 
Example-2: Implementing AES_ENCRYPT function on a bigger string.  
SELECT 
AES_ENCRYPT('geeksforgeeks', 'key'); 
Output:  
2G???B?????*?? 
Example-3: Implementing AES_ENCRYPT function on a NULL string.  
SELECT  
(AES_ENCRYPT(NULL, 'key'); 
Output: 
NULL 
abhishek0719kadiyan
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL Correlated Subqueries
Difference between DELETE and TRUNCATE
SQL | Sub queries in From Clause
MySQL | Regular expressions (Regexp)
PHP | Classes

25 Mar, 2018
Like C++ and Java, PHP also supports object oriented programming
Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.Class is a programmer-defined data type, which includes local methods and local variables.Class is a collection of objects. Object has properties and behavior.
Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.
Class is a programmer-defined data type, which includes local methods and local variables.
Class is a collection of objects. Object has properties and behavior.
Syntax: We define our own class by starting with the keyword ‘class’ followed by the name you want to give your new class.
<?php 
    class person {
 
    }
?>
Note: We enclose a class using curly braces ( { } ) ... just like you do with functions.
Given below are the programs to elaborate the use of class in Object Oriented Programming in PHP.The programs will illustrate the examples given in the article.
Program 1:
<?phpclass GeeksforGeeks{    // Constructor    public function __construct(){        echo 'The class "' . __CLASS__ . '" was initiated!<br>';    }      }   // Create a new object$obj = new GeeksforGeeks;?>
Output:
The class "GeeksforGeeks" was initiated.
Program 2:
<?phpclass GeeksforGeeks{    // Destructor    public function __destruct(){        echo 'The class "' . __CLASS__ . '" was destroyed!';    }      }   // Create a new object$obj = new GeeksforGeeks;?>
Output:
The class "GeeksforGeeks" was destroyed.

Reference:Classes in PHP
PHP-OOP
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Data type of case labels of switch statement in C++?

12 Aug, 2021
In C++ switch statement, the expression of each case label must be an integer constant expression. For example, the following program fails in compilation.  
CPP
/* Using non-const in case label */#include<stdio.h>int main(){  int i = 10;  int c = 10;  switch(c)  {    case i: // not a "const int" expression         printf("Value of c = %d", c);         break;    /*Some more cases */                      }  return 0;}
Putting const before i makes the above program work. 
CPP
#include<stdio.h>int main(){  const int i = 10;  int c = 10;  switch(c)  {    case i:  // Works fine         printf("Value of c = %d", c);         break;    /*Some more cases */                      }  return 0;}
Note : The above fact is only for C++. In C, both programs produce an error. In C, using an integer literal does not cause an error.Program to find the largest number between two numbers using switch case: 
C
#include<stdio.h>int main(){  int n1=10,n2=11;   // n1 > n2 (10 > 11) is false so using   // logical operator '>', n1 > n2 produces 0  // (0 means false, 1 means true) So, case 0  // is executed as 10 > 11 is false. Here we  // have used type cast to convert boolean to int,  // to avoid warning.   switch((int)(n1 > n2))  {    case 0:          printf("%d is the largest\n", n2);         break;    default:         printf("%d is the largest\n", n1);  }   // n1 < n2 (10 < 11) is true so using logical  // operator '<', n1 < n2 produces 1 (1 means true,  // 0 means false) So, default is executed as we  // don't have case 1 to be executed.   switch((int)(n1 < n2))  {    case 0:          printf("%d is the largest\n", n1);         break;    default:         printf("%d is the largest\n", n2);  }   return 0;}//This code is contributed by Santanu
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
SantanuBasak
HanishGupta1
imohitagrawal
C-Loops & Control Statements
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Storage Classes in C
Ways to copy a vector in C++
Understanding "extern" keyword in C
What does intern() method in java?

The intern() method of the String method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.
For any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
 Live Demo
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "This is TutorialsPoint";
      // returns canonical representation for the string object
      String str2 = str1.intern();
     
      // prints the string str2
      System.out.println(str2);
     
      // check if str1 and str2 are equal or not
      System.out.println("Is str1 equal to str2 ? = " + (str1 == str2));
   }
}
This is TutorialsPoint
Is str1 equal to str2 ? = true
Find the value of ln(N!) using Recursion - GeeksforGeeks

14 May, 2021
Given a number N, the task is to find the log value of the factorial of N i.e. log(N!).Note: ln means log with base e.Examples:  
Input: N = 2
Output: 0.693147

Input:  N = 3
Output: 1.791759
 
Approach:Method -1: Calculate n! first, then take its log value.Method -2: By using the property of log, i.e. take the sum of log values of n, n-1, n-2 ...1.  
ln(n!) = ln(n*n-1*n-2*.....*2*1) = ln(n)+ln(n-1)+......+ln(2)+ln(1)  
Below is the implementation of the Method-2:  
C++
C
Java
Python
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the valuedouble fact(int n){    if (n == 1)        return 0;    return fact(n - 1) + log(n);}// Driver codeint main(){    int N = 3;    cout << fact(N) << "\n";    return 0;}
// C implementation of the above approach#include <math.h>#include <stdio.h> long double fact(int n){    if (n == 1)        return 0;    return fact(n - 1) + log(n);} // Driver codeint main(){    int n = 3;    printf("%Lf", fact(n));    return 0;}
// Java implementation of the above approachimport java.util.*;import java.io.*;class logfact {    public static double fact(int n)    {        if (n == 1)            return 0;        return fact(n - 1) + Math.log(n);    }     public static void main(String[] args)    {         int N = 3;        System.out.println(fact(N));    }}
# Python implementation of the above approachimport mathdef fact(n):    if (n == 1):        return 0    else:        return fact(n-1) + math.log(n)N = 3print(fact(N))
// C# implementation of the above approachusing System; class GFG{    public static double fact(int n)    {        if (n == 1)            return 0;        return fact(n - 1) + Math.Log(n);    }     // Driver code    public static void Main()    {        int N = 3;        Console.WriteLine(fact(N));    }} // This code is contributed by ihritik
<?php //PHP implementation of the above approach function fact($n){    if ($n == 1)        return 0;    return fact($n - 1) + log($n);} // Driver code$n = 3;echo fact($n); // This code is contributed by ihritik?>
<script> // Javascript implementation of the above approach // Function to calculate the valuefunction fact(n){    if (n == 1)        return 0;    return fact(n - 1) + Math.log(n);}// Driver codevar N = 3;document.write( fact(N).toFixed(6) + "<br>"); </script>
1.791759
 
ihritik
rutvik_56
maths-log
Mathematical
Recursion
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
Check if a number is Palindrome
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Program for Sum of the digits of a given number
How can MySQL COALESCE() function be used with MySQL SUM() function to customize the output?

When MySQL SUM() function got a column, having no values, an argument then it will return NULL, rather than 0, as output. But if we want to customize this output to show 0 as output then we can use MySQL COALESCE() function which accepts two arguments and returns the second argument if the first argument is NULL, otherwise, it returns the first argument. To illustrate it, we are taking the example of ‘Tender’ table having the following data −
mysql> Select * from tender;

+----+---------------+--------------+
| Sr | CompanyName   | Tender_value |
+----+---------------+--------------+
| 1  | Abc Corp.     | 250.369003   |
| 2  | Khaitan Corp. | 265.588989   |
| 3  | Singla group. | 220.255997   |
| 4  | Hero group.   | 221.253006   |
| 5  | Honda group   | NULL         |
+----+---------------+--------------+

5 rows in set (0.00 sec)
MySQL SUM() function returns NULL when we try to find the total tender value quoted by ‘Honda Group’ because it is having no value in the column.
mysql> Select SUM(Tender_value) From Tender Where CompanyName = 'Honda Group';

+-------------------+
| SUM(Tender_value) |
+-------------------+
|              NULL |
+-------------------+

1 row in set (0.00 sec)
But, suppose if we want to customize this output from NULL to 0 then we can use COALESCE function with SUM() to find the total tender value quoted by ‘Honda Group’.
mysql> Select COALESCE(SUM(Tender_value),0) From Tender Where CompanyName = 'Honda Group';

+-------------------------------+
| COALESCE(SUM(Tender_value),0) |
+-------------------------------+
|                      0.000000 |
+-------------------------------+

1 row in set (0.00 sec)
Now, MySQL SUM() function returns 0 when we use COALESCE function with SUM() to find the total number of pages typed by ‘Mohan’, the name which is not in the ‘Name’ column −
mysql> SELECT COALESCE(SUM(daily_typing_pages),0) FROM employee_tbl WHERE Name = ‘Mohan’;

+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
|                       0 |
+-------------------------+

1 row in set (0.00 sec)
From the above result sets, it is clear that MySQL SUM() function will return NULL if there would be no values in the column irrespective of its data type.