code-rag-bench/online-tutorials huggingface dataset:
Top Hat and Black Hat Transform using Python-OpenCV

08 Jun, 2020
In morphology and digital image processing, top-hat and black-hat transform are operations that are used to extract small elements and details from given images. These two types of transforms in which, the top-hat transform is defined as the difference between the input image and its opening by some structuring element, while the black-hat transform is defined as the difference between the closing and the input image. These transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others.
Here we will use Opening and Closing morphological operations.
The top-hat filter is used to enhance bright objects of interest in a dark background. The black-hat operation is used to do the opposite, enhance dark objects of interest in a bright background.Example 1: Top-Hat Transform
Image used:
# Importing OpenCV import cv2    # Getting the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT,                                    filterSize)  # Reading the image named 'input.jpg'input_image = cv2.imread("testing.jpg")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)  # Applying the Top-Hat operationtophat_img = cv2.morphologyEx(input_image,                               cv2.MORPH_TOPHAT,                              kernel)  cv2.imshow("original", input_image)cv2.imshow("tophat", tophat_img)cv2.waitKey(5000)
Output:
As you can observe in the above image, the very small details are enhanced and taken out using the Top-Hat operation. Hence, it is useful in observing the minor details of the inputs when are present as light pixels on a dark background.
Example 2: Black Hat transform
Input Image:
# Importing OpenCV and numpyimport cv2  # Defining the kernel to be used in Top-HatfilterSize =(3, 3)kernel = cv2.getStructuringElement(cv2.MORPH_RECT,                                   filterSize)  # Reading the image named 'input.jpg'input_image = cv2.imread("testing.jpg")input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)  # Applying the Black-Hat operationtophat_img = cv2.morphologyEx(input_image,                               cv2.MORPH_BLACKHAT,                              kernel)  cv2.imshow("original", input_image)cv2.imshow("tophat", tophat_img)cv2.waitKey(5000)
Output:
Here in this image, all the objects which are white on a dark background are highlighted due to the Black Hat transformation applied to the input image.
Image-Processing
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
RTTI (Run-Time Type Information) in C++

18 May, 2022
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.
Runtime Casts
The runtime cast, which checks that the cast is valid, is the simplest approach to ascertain the runtime type of an object using a pointer or reference. This is especially beneficial when we need to cast a pointer from a base class to a derived type. When dealing with the inheritance hierarchy of classes, the casting of an object is usually required. There are two types of casting: 
Upcasting: When a pointer or a reference of a derived class object is treated as a base class pointer.
Downcasting: When a base class pointer or reference is converted to a derived class pointer.
Using ‘dynamic_cast‘: In an inheritance hierarchy, it is used for downcasting a base class pointer to a child class. On successful casting, it returns a pointer of the converted type and, however, it fails if we try to cast an invalid type such as an object pointer that is not of the type of the desired subclass.
For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.
CPP
// C++ program to demonstrate// Run Time Type Identification(RTTI)// but without virtual function #include <iostream>using namespace std; // initialization of base classclass B {}; // initialization of derived classclass D : public B {}; // Driver Codeint main(){    B* b = new D; // Base class pointer    D* d = dynamic_cast<D*>(b); // Derived class pointer    if (d != NULL)        cout << "works";    else        cout << "cannot cast B* to D*";    getchar(); // to get the next character    return 0;}
 Adding a virtual function to the base class B makes it work.
CPP
// C++ program to demonstrate// Run Time Type Identification successfully// With virtual function #include <iostream>using namespace std; // Initialization of base classclass B {    virtual void fun() {}}; // Initialization of Derived classclass D : public B {}; // Driver Codeint main(){    B* b = new D; // Base class pointer    D* d = dynamic_cast<D*>(b); // Derived class pointer    if (d != NULL)        cout << "works";    else        cout << "cannot cast B* to D*";    getchar();    return 0;}
works
anshikajain26
harsh_shokeen
rkbhola5
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C++ programs | Set 43 (Decision and Control Statements)

05 Sep, 2017
Decision and Loops & Control StatementsQUE.1 What is the output of this program ?
#include <iostream>using namespace std;int main (){    int n;    for (n = 5; n > 0; n--)    {        cout << n;        if (n == 3)            break;    }    return 0;}
OPTIONa) 543b) 54c) 5432d) 53
Answer: a
Explanation : In this program, we are printing the numbers in reverse order and by using break statement we stopped printing on 3.
QUE.2 What is the output of this program?
#include <iostream>using namespace std;int main(){    int a = 10;    if (a < 15)    {        time:        cout << a;        goto time;    }    break;    return 0;}
OPTIONa) 1010b) 10c) infinitely print 10d) compile time error
Answer:  d
Explanation: Because the break statement needs to be presented inside a loop or a switch statement.
QUE. 3 What is the output of this program ?
#include <iostream>using namespace std;int main(){    int n = 15;    for ( ; ; )    cout << n;    return 0;}
OPTIONa) errorb) 15c) infinite times of printing nd) none of the mentioned
Answer: c
Explanation: There is no condition in the for loop, So it will loop continuously.
QUE.4 What is the output?
#include <iostream>using namespace std;int main(){    int i;    for (i = 0; i < 10; i++);    {        cout << i;    }    return 0;}
OPTIONa) 0123456789b) 10c) 012345678910d) compile time error
Answer: b
Explanation: for loop with a semicolon is called as body less for loop. It is used only for incrementing the variable values. So, in this program the value is incremented and printed as 10.
QUE.5 what is output of this program?
#include <iostream>int i = 30;using namespace std;int main(){    int i = 10;    for (i = 0; i < 5; i++)    {        int i = 20;        cout << i <<" ";    }    return 0;}
OPTIONa) 0 1 2 3 4b) 10 10 10 10 10c) 20 20 20 20 20d) Compile Errors
Answer: c
Explanation: int i = 20 is initialized in the body of loop so it considers the value i = 20 inside loop only. For loop control, the i declared outside is used and loop runs 5 times and print 20 five times.
This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to convert unix timestamp string to readable date

31 Oct, 2021
In this article, we are going to see the conversion of the Unix timestamp string to a readable date. This can be done with the help of fromtimestamp() and strftime() functions.
fromtimestamp(): The fromtimestamp() function is used to return the date and time corresponding to a specified timestamp.
Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method.
Syntax:  @classmethod fromtimestamp(timestamp)
Parameters: This function accepts a parameter which is illustrated below:
timestamp: This is the specified timestamp for which the date is going to be returned.
Return values: This function returns the date and time corresponding to a specified timestamp.
strftime(): The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation.
Syntax: strftime(format)
Parameter: This function accepts a single parameter which is illustrated below:
format: This is the specified date and time object.
Return Values: It returns the string representation of the date or time object.
Example 1: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamp # Calling the strftime() function to convert# the extracted datetime into its string formatprint(datetime.datetime.fromtimestamp(int("1294113662"))      .strftime('%Y-%m-%d %H:%M:%S'))
Output:
2011-01-04 04:01:02
Example 2: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date # Importing datetime moduleimport datetime # Calling the fromtimestamp() function to# extract datetime from the given timestamptimestamp = datetime.datetime.fromtimestamp(1200001234) # Calling the strftime() function to convert# the extracted datetime into its string formatprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2008-01-10 21:40:34
rajeev0719singh
clintra
anikakapoor
Picked
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect the browser language preference using JavaScript ?

23 Sep, 2020
Detecting the language preference of users can be very important for Websites or Web Apps for increasing user interaction. By using JavaScript, this task can be easily done by using:
Languages property is available for the navigator interface, which returns the most preferred / user preferred language set in the web browser. This property is read-only.
Syntax:
navigator.languages 

// Or

navigator.language

Return Value: 
The navigator.languages property will return an array which stores the languages in an order in which language most preferred by the user will be the first element.
The navigator.language property will return the first element of the array which is returned by the navigator.languages property i.e. the most preferred user language.
Note: Language property is a read-only property, thus it is only possible for us to get the value, we cannot make changes to the user preferred language.
Example 1: Getting the most preferred language.
HTML
<!DOCTYPE html><html>   <body>     <h1 align="left">GeekforGeeks</h1>     <script>         var usrlang = navigator.language                 || navigator.userLanguage;        document.write(            "User's preferred language is: "            + usrlang);    </script> </body> </html>
Output:
Example 2: Getting the preferred language array.
HTML
<!DOCTYPE html><html>     <body>     <h1 align="left">GeekforGeeks</h1>          <script>         var usrlang = navigator.languages;        console.log(usrlang);    </script> </body> </html>
Output:
Supported Browsers:
Google Chrome
Mozilla Firefox
Edge
Opera
Internet Explorer
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
How to read a JSON response from a link in Python?

24 Feb, 2021
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which helps to open the URL from the web and read the data.
To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json.loads() method returns JSON object. Below is the process by which we can read the JSON response from a link or URL in python.
Import required modules.
Assign URL.
Get the response of the URL using urlopen().
Convert it to a JSON response using json.loads().
Display the generated JSON response.
Implementation:
Python3
# import urllib libraryfrom urllib.request import urlopen  # import jsonimport json# store the URL in url as # parameter for urlopenurl = "https://api.github.com"  # store the response of URLresponse = urlopen(url)  # storing the JSON response # from url in datadata_json = json.loads(response.read())  # print the json responseprint(data_json)
Output:
In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json.loads() to convert the response into a JSON object.
Picked
Python-json
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating Pandas dataframe using list of lists

22 Jun, 2021
Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object.Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe using list of lists.
Code #1: 
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['Geeks', 10], ['for', 15], ['geeks', 20]] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe.print(df )
Name  Age
0  Geeks   10
1    for   15
2  geeks   20
 
  Code #2:
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7],        ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks']) # print dataframe.print(df )
Category         Name  Marks
0       DS  Linked_list     10
1       DS        Stack      9
2       DS        Queue      7
3     Algo       Greedy      8
4     Algo           DP      6
5     Algo    BackTrack      5
 
  Code #3: Doing some operation of dataframe. 
Python3
# Import pandas libraryimport pandas as pd # initialize list of listsdata = [[1, 5, 10], [2, 6, 9], [3, 7, 8]] # Create the pandas DataFramedf = pd.DataFrame(data) # specifying column namesdf.columns = ['Col_1', 'Col_2', 'Col_3'] # print dataframe.print(df, "\n") # transpose of dataframedf = df.transpose()print("Transpose of above dataframe is-\n", df)
Col_1  Col_2  Col_3
0      1      5     10
1      2      6      9
2      3      7      8 

Transpose of above dataframe is-
         0  1  2
Col_1   1  2  3
Col_2   5  6  7
Col_3  10  9  8
 
surinderdawra388
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
primary_key – Django Built-in Field Validation

19 Feb, 2021
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. primary_key=True will make the field PRIMARY KEY for that table (model).If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.
Note: primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.
Syntax
field_name = models.Field(primary_key = True)
Illustration of primary_key=True using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using IntegerField for experimenting for primary_key.
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.IntegerField(primary_key = True)
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,
Python manage.py shell
Now let us try to create instance of GeeksModel using None.
# importing required modelfrom geeks.models import GeeksModel  # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = 12)  # saving current model instances.save()
Let us check in admin interface if the instance of model is created.Therefore, primary_key=True modifies the field to as PRIMARY KEY for that table. To know more about Primary key, visit here.
The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.
NaveenArora
AmitYadav27
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.mode() function in Python

06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set turtle-mode (‘standard’, ‘logo’ or ‘world’) and perform reset. 
Syntax : turtle.mode(mode=None)
Parameter: 
mode: one of the strings ‘standard’, ‘logo’ or ‘world’
Mode ‘standard’ is compatible with turtle.py.
Mode ‘logo’ is compatible with most Logo-Turtle-Graphics.
Mode ‘world’ uses userdefined ‘worldcoordinates’.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle  # check by default valueprint(turtle.mode())
Output :
standard

Example 2 :
Python3
# importing packageimport turtle  # motion with default mode (standard)# default direction of turtle head # is north in standard modeturtle.forward(180)  # set mode to 'logo' modeturtle.mode(mode='logo')  # do some motion# default direction of turtle head # is east in logo modeturtle.forward(120)  # set mode to 'world' modeturtle.mode(mode='world')  # do some motionturtle.forward(100)  # set coordinates of the turtle # mode (world) by choice of userturtle.setworldcoordinates(-500,-500,500,500)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Word Break Problem

In the input of this problem, one sentence is given without spaces, another dictionary is also provided of some valid English words. We have to find the possible ways to break the sentence in individual dictionary words.
We will try to search from the left of the string to find a valid word when a valid word is found, we will search for words in the next part of that string.
Input:
A set of valid words as dictionary, and a string where different words are placed without spaces.
Dictionary: {mobile, sam, sung, man, mango, icecream, and, go, i, love, ice, cream}
Given String: “ilovemangoicecream”
Output:
All possible ways to break the string into given words.
i love man go ice cream
i love man go icecream
i love mango ice cream
i love mango icecream
wordBreak(string, n, result)
Input − Given string, length of the string, the separated strings.
Output − Separate string using a dictionary.
Begin
   for i := 0 to n, do
      subStr := substring of given string from (0..i)
      if subStr is in dictionary, then
         if i = n, then
            result := result + subStr
            display the result
            return
         wordBreak(substring from (i..n-i), n-i, result, subStr, ‘space’)
   done
End
#include <iostream>
#define N 13
using namespace std;

string dictionary[N] = {"mobile","samsung","sam","sung","man","mango", "icecream","and",
                        "go","i","love","ice","cream"};

int isInDict(string word){    //check whether the word is in dictionary or not
   for (int i = 0; i < N; i++)
      if (dictionary[i].compare(word) == 0)
         return true;
   return false;
}

void wordBreak(string str, int n, string result) {
   for (int i=1; i<=n; i++) {
      string subStr = str.substr(0, i);       //get string from 0 to ith location of the string
      if (isInDict(subStr)) {       //if subStr is found in the dictionary
         if (i == n) {
            result += subStr; //add substring in the result.
            cout << result << endl;
            return;
         }
         wordBreak(str.substr(i, n-i), n-i, result + subStr + " ");    //otherwise break rest part
      }
   }
}

int main() {
   string str="iloveicecreamandmango";
   wordBreak(str, str.size(),"");
}
i love man go ice cream
i love man go icecream
i love mango ice cream
i love mango icecream
Python – Sum elements matching condition

17 Dec, 2021
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals sum that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved.
Method #1 : Using loop This is brute force method to perform this particular task. In this, we iterate list, find elements that match a particular condition and take sum.
Python3
# Python 3 code to demonstrate # Sum elements matching condition# using loop   # initializing listtest_list = [3, 5, 1, 6, 7, 9]   # printing original listprint ("The original list is : " + str(test_list))   # using loop# Sum elements matching condition# checks for oddres = 0for ele in test_list:    if ele % 2 != 0:        res = res + ele            # printing resultprint ("The sum of odd elements: " + str(res))
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
 
 Method #2 : Using sum() + generator expression This method uses the trick of adding element to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of numbers matching a condition is returned.
Python3
# Python 3 code to demonstrate # Sum elements matching condition# using sum() + generator expression   # initializing listtest_list = [3, 5, 1, 6, 7, 9]   # printing original listprint ("The original list is : " + str(test_list))   # using sum() + generator expression# Sum elements matching condition# checks for oddres = sum(i for i in test_list if i % 2 != 0)   # printing resultprint ("The sum of odd elements: " + str(res))
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
 
arorakashish0911
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo or Remainder Operator in Java

23 Feb, 2022
Modulo or Remainder Operator returns the remainder of the two numbers after division. If you are provided with two numbers, say A and B, A is the dividend and B is the divisor, A mod B is there a remainder of the division of A and B. Modulo operator is an arithmetical operator which is denoted by %.
NOTE:    If numerator is less than denominator then % will give output as the numerator only.
Syntax:
A % B
Where A is the dividend and B is divisor
Example:
Input : a = 15, b = 6 // 15%6 means when we divide 15(numerator) by 6(denominator) we get remainder 3// Output: 3Input : a = 16, b = 4 Output: 0
Approach:
Take Dividend and Divisor from the user.Create an integer variable and assign it with A % B expression.Print that variable.
Take Dividend and Divisor from the user.
Create an integer variable and assign it with A % B expression.
Print that variable.
Below is the implementation of the above approach:
Java
// Implementation of Modulo or Remainder Operator in Javaimport java.io.*;import java.util.*; class GFG {    public static void main(String[] args)    {        // Dividend        int a = 15;         // Divisor        int b = 8;         // Mod        int k = a % b;        System.out.println(k);    }}
7
Time Complexity : 
Modular function usually takes Constant time / O(1) time like other arithmetic operations. 
jyoti369
singhaditya2608
Java-Operators
Picked
Java
Java Programs
Java-Operators
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
How to make a Tkinter widget invisible?

To make a tkinter widget invisible, we can use the pack_forget() method. It is generally used to unmap the widgets from the window.
In the following example, we will create a label text and a button that can be used to trigger the invisible event on the label text widget.
#Import the required libraries
from tkinter import *

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

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

#Set the resizable property False
win.resizable(False, False)

#Make the widgets Invisible
def make_invisible(widget):
   widget.pack_forget()

#Create a label for the window or frame
label=Label(win, text="Hello World!", font=('Helvetica bold',20),
anchor="center")
label.pack(pady=20)

#Create a button to make the widgets invisible
btn=Button(win, text="Click", font= ('Helvetica bold', 10), command=lambda:
make_invisible(label))
btn.pack(pady=20)

win.mainloop()
Running the above code will produce the following window −
Now click the “Click” Button to make the text label invisible.
StDev() and StDevP() Function in MS Access

15 Sep, 2020
1. StDev() Function :StDev() Function in MS Access is used to estimate the standard deviation for a population sample.
Syntax :
StDev (expr)
Parameter : This method accept one parameter as mentioned above and described below :
expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function.
Returns : It calculates standard deviation for a population sample.Note : If the underlying query contains fewer than two records or no records then it returns a Null value which indicates that a standard deviation cannot be calculated.
Table – ProcuctDetails
Example1 :The standard deviation for the product price.
SELECT stDev(Product_Price) AS StDEV_Value FROM ProcuctDetails;
Output :
Example2 :The standard deviation for only one record.
SELECT stDev(100) AS StDEV_Value ;
Output :
So, we can see it cannot be calculated.2. StDevP () Function :StDevP() Function in MS Access is used to estimate the standard deviation for a population. The main difference between the StDevP() function and StDev() function is StDevP evaluates a population, and the StDev evaluates a population sample.
Syntax :
StDevP (expr)
Parameter : This method accept one parameter as mentioned above and described below :
expr : It represents a string expression identifying the field that contains the numeric data which we want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function.
Returns : It calculates standard deviation for a population.
Note : If the underlying query contains fewer than two records then it returns a Null value which indicates that a standard deviation cannot be calculated.
Table – Products
Example-1 :
SELECT stDevP(P_Price) AS StDEVp_Value FROM Procucts;
Output :
Example-2 :
SELECT stDevP(10) AS StDEVp_Value;
Output :
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
turtle.towards() function in Python

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the angle, between the line from turtle-position to the position specified by x, y, and the turtle’s start orientation.
Syntax :
turtle.towards(x, y=None)

Parameters:
Below is the implementation of the above method with an example :
Python3
# import packageimport turtle  # go towards eastang=turtle.towards(100,0)  # print angleprint(ang)  # go towards northang=turtle.towards(0,100)  # print angleprint(ang)  # go towards westang=turtle.towards(-100,0)  # print angleprint(ang)  # go towards southang=turtle.towards(0,-100)  # print angleprint(ang)
Output :
0.0
90.0
180.0
270.0

Here we can see that one can easily get an angle towards any coordinate point without going to that point. In the above example turtle remain on (0,0) i.e. home and get all angles to the specified position without any movement.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | sys.setrecursionlimit() method

07 Aug, 2019
This sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It provides information about constants, functions and methods of python interpreter. It can be used for manipulating Python runtime environment.
sys.setrecursionlimit() method is used to set the maximum depth of the Python interpreter stack to the required limit. This limit prevents any program from getting into infinite recursion, Otherwise infinite recursion will lead to overflow of the C stack and crash the Python.
Note: The highest possible limit is platform-dependent. This should be done with care because too-high limit can lead to crash.
Syntax: sys.setrecursionlimit(limit)
Parameter:limit: It the value of integer type that denotes the new limit of python interpreter stack.
Return Value: This method returns nothing.
Example #1 :
# Python program to explain sys.setrecursionlimit() method       # Importing sys module import sys   # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit()  # Print the current limit print('Before changing, limit of stack =', limit)   # New limitNewlimit = 500  # Using sys.setrecursionlimit() method sys.setrecursionlimit(Newlimit)   # Using sys.getrecursionlimit() method # to find the current recursion limitlimit = sys.getrecursionlimit()  # Print the current limit print('After changing, limit of stack =', limit)   
Before changing, limit of stack = 1000
After changing, limit of stack = 500

python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
C++ program to overload addition operator to add two complex numbers

Suppose we have a complex number class with real and imaginary part. We shall have to overload the addition (+) operator to add two complex number. We also have to define a function to return complex number in proper representation.
So, if the input is like c1 = 8 - 5i, c2 = 2 + 3i, then the output will be 10 - 2i.
To solve this, we will follow these steps −
Overload the + operator and take another complex number c2 as argument
Overload the + operator and take another complex number c2 as argument
define a complex number called ret whose real and imag are 0
define a complex number called ret whose real and imag are 0
real of ret := own real + real of c2
real of ret := own real + real of c2
imag of ret := own imag + imag of c2
imag of ret := own imag + imag of c2
return ret
return ret
Let us see the following implementation to get better understanding −
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
    private:
        int real, imag;
    public:
    Complex(){
        real = imag = 0;    
    }
    Complex (int r, int i){
        real = r;
        imag = i;
    }
    string to_string(){
        stringstream ss;
        if(imag >= 0)
            ss << "(" << real << " + " << imag << "i)";
        else
            ss << "(" << real << " - " << abs(imag) << "i)";
        return ss.str();
    }
    Complex operator+(Complex c2){
        Complex ret;
        ret.real = real + c2.real;
        ret.imag = imag + c2.imag;
        return ret;
    }
};
int main(){
    Complex c1(8,-5), c2(2,3);
    Complex res = c1 + c2;
    cout << res.to_string();
}

c1(8,-5), c2(2,3)
(10 - 2i)
How to Install Python Scrapy on Windows? - GeeksforGeeks

09 Sep, 2021
Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scraped the data then it decides whether to:
Keep the data.
Drop the data or items.
stop and store the processed data items.
In this article, we will look into the process of installing the Scrapy module on Windows.
The only thing that you need for installing the Scrapy module on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, you can use the below command:
conda install scrapy
Type y for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Users who prefer to use pip can use the below command to install the Scrapy package on Windows:
pip install scrapy
You will get a similar message once the installation is complete:
To verify if Scrapy has been successfully installed in your system run the below code in a python IDE of your choice:
Python3
import scrapyscrapy.__version__
If successfully installed you will get the following output.
Blogathon-2021
how-to-install
Picked
Python-Scrapy
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Numpy on MacOS?
Dart - Null Aware Operators
Format Dates in Flutter
How to Install Tkinter in Windows?
Designing algorithm to solve Ball Sort Puzzle
How to Install PIP on Windows ?
How to Install FFmpeg on Windows?
How to Use Terminal in Sublime Text Editor ?
Different Ways to Connect One Computer to Another Computer
How to Install Numpy on MacOS?
Difference between pointer to an array and array of pointers - GeeksforGeeks

13 Jun, 2019
Pointer to an array:
Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array.
  int a[3] = {3, 4, 5 }; 
  int *ptr = a; 

We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the array.Syntax:
data type (*var name)[size of array];
Declaration of the pointer to an array:
// pointer to an array of five numbers
 int (* ptr)[5] = NULL;     
The above declaration is the pointer to an array of five integers. We use parenthesis to pronounce pointer to an array. Since subscript has higher priority than indirection, it is crucial to encase the indirection operator and pointer name inside brackets.
Example:
// C program to demonstrate// pointer to an array.  #include <stdio.h>  int main(){      // Pointer to an array of five numbers    int(*a)[5];      int b[5] = { 1, 2, 3, 4, 5 };      int i = 0;      // Points to the whole array b      a = &b;      for (i = 0; i < 5; i++)          printf("%d\n", *(*a + i));      return 0;}
1
2
3
4
5

Array of pointers:
“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
 int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values.
Example:
// C program to demonstrate// example of array of pointers.  #include <stdio.h>  const int SIZE = 3;  void main(){      // creating an array    int arr[] = { 1, 2, 3 };      // we can make an integer pointer array to    // storing the address of array elements    int i, *ptr[SIZE];      for (i = 0; i < SIZE; i++) {          // assigning the address of integer.        ptr[i] = &arr[i];    }      // printing values using pointer    for (i = 0; i < SIZE; i++) {          printf("Value of arr[%d] = %d\n", i, *ptr[i]);    }}
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

Example: We can likewise make an array of pointers to the character to store a list of strings.
#include <stdio.h>  const int size = 4;  void main(){      // array of pointers to a character    // to store a list of strings    char* names[] = {        "amit",        "amar",        "ankit",        "akhil"    };      int i = 0;      for (i = 0; i < size; i++) {        printf("%s\n", names[i]);    }}
amit
amar
ankit
akhil

Arrays
Pointers
C Language
Difference Between
Arrays
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java
C Program for Tower of Hanoi

The tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules−
Only one disk can be moved at a time.
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
No disk may be placed on top of a smaller disk.
Input  − 3
Output   − A to B 
              A to C 
             B to C 
            A to B 
            C to A 
            C to B 
A to B  Explanation − uses recursive function & solves the tower of Hanoi.
#include<stdio.h>
void TOH(int n,char x,char y,char z) {
   if(n>0) {
      TOH(n-1,x,z,y);
      printf("\n%c to %c",x,y);
      TOH(n-1,z,y,x);
   }
}
int main() {
   int n=3;
   TOH(n,'A','B','C');
}
A to B
A to C
B to C
A to B
C to A
C to B
A to B
Pandas - Plotting

Pandas uses the plot() method to create 
diagrams.
We can use Pyplot, a submodule of the Matplotlib library to visualize the 
diagram on the screen.
Read more about Matplotlib in our Matplotlib Tutorial.
Import pyplot from Matplotlib and visualize our DataFrame:
The examples in this page uses a CSV file called: 'data.csv'.
Download data.csv or Open 
data.csv
Specify that you want a scatter plot with the 
kind argument:
kind = 'scatter'
A scatter plot needs an x- and a y-axis.
In the example below we will use "Duration" for the x-axis
and "Calories" for the y-axis.
Include the x and y arguments like this:
x = 'Duration', y = 'Calories'

Remember:
    In the previous example, we learned that the correlation between "Duration" and "Calories"
    was 0.922721, and we conluded with the fact that
    higher duration means more calories burned.
By looking at the scatterplot, I will agree.  
Let's create another scatterplot, where there is a bad relationship between the columns, like "Duration" and "Maxpulse", with the correlation 0.009403:
A scatterplot where there are no relationship between the columns:
Use the 
kind argument 
to specify that you want a histogram:
kind = 'hist'
A histogram needs only one column.
A histogram shows us the frequency of each interval, e.g. how many workouts lasted between 50 and 60 minutes?
In the example below we will use the "Duration" column to create the histogram:

Note:
    The histogram tells us that there were over 100 workouts that lasted between 50 and 60 minutes.
Insert a correct syntax for visualize the data in DataFrame as a diagram (plotting).
df.()

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Program to print its script name as output in Python

In this tutorial, we are going to write a program that prints the name of the Python script file. We can find the script name using the sys module.
The sys module will store all the command line arguments of python command in the sys.argv list. The first element in the list is the script name. We can extract it from that list. Python makes it easy.
Let's see the steps involved in the program.
Import the sys module.
Import the sys module.
Now, print the first element of the sys.argv list.
Now, print the first element of the sys.argv list.
That's it. You got the script name.
That's it. You got the script name.
Let's see it practically.
 Live Demo
# importing the sys module
import sys
# importing os module for absolute path
import os
# printing the script name
# first element of sys.argv list
print(os.path.abspath(sys.argv[0]))
If you run the above code, you will get the absolute path of your Python script.
C:\Users\hafeezulkareem\Desktop\sample\tutorialspoint.py
If you have any doubts in the tutorial, mention them in the comment section.
Google Guice - Optional Injection

Injection is a process of injecting dependeny into an object. Optional injection means injecting the dependency if exists. Method and Field injections may be optionally dependent and should have some default value if dependency is not present. See the example below.
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck();
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor( SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   } 
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {} 
}

@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   private String dbUrl = "jdbc:mysql://localhost:5326/emp";

   public SpellCheckerImpl(){}
   
   @Inject(optional=true)
   public void setDbUrl(@Named("JDBC") String dbUrl){
      this.dbUrl = dbUrl;
   }

   @Override
   public void checkSpelling() { 
      System.out.println("Inside checkSpelling." );
      System.out.println(dbUrl); 
   }
}
Compile and run the file, you will see the following output.
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp


    27 Lectures 
     1.5 hours 

 Lemuel Ogbunude
 Print
 Add Notes
 Bookmark this page