code-rag-bench/online-tutorials huggingface dataset:
How to make background image transparent using Python?

24 Jan, 2021
In this article, the task is to create a background transparent of the image in Python
Library Required :
First Install pillow library on your Python Application before going ahead. Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many image file formats. Pillow library is necessary for this mentioned program. You can install pillow library in Python using the code
pip install pillow
Method :
Read the image.Convert the image into RGBA format.Change the white pixels of the image into a transparent formSave the newly edited image
Read the image.
Convert the image into RGBA format.
Change the white pixels of the image into a transparent form
Save the newly edited image
Example :
Python3
from PIL import Image  def convertImage():    img = Image.open("./image.png")    img = img.convert("RGBA")      datas = img.getdata()      newData = []      for items in datas:        if item[0] == 255 and item[1] == 255 and item[2] == 255:            newData.append((255, 255, 255, 0))        else:            newData.append(item)      img.putdata(newData)    img.save("./New.png", "PNG")    print("Successful")  convertImage()
Output:
Image-Processing
Picked
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
Iterate over a list in Python
Introduction To PYTHON
numpy.mean() in Python

28 Nov, 2018
numpy.mean(arr, axis = None) : Compute the arithmetic mean (average) of the given data (array elements) along the specified axis.
Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the arithmetic mean. Otherwise, it will consider arr to be flattened(works on allthe axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional]Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing mean.
Results : Arithmetic mean of the array (a scalar value if axis is none) or array with mean values along specified axis.
Code #1:
# Python Program illustrating # numpy.mean() method import numpy as np    # 1D array arr = [20, 2, 7, 1, 34]  print("arr : ", arr) print("mean of arr : ", np.mean(arr))   
Output :
arr :  [20, 2, 7, 1, 34]
mean of arr :  12.8

 Code #2:
# Python Program illustrating # numpy.mean() method   import numpy as np      # 2D array arr = [[14, 17, 12, 33, 44],         [15, 6, 27, 8, 19],        [23, 2, 54, 1, 4, ]]     # mean of the flattened array print("\nmean of arr, axis = None : ", np.mean(arr))     # mean along the axis = 0 print("\nmean of arr, axis = 0 : ", np.mean(arr, axis = 0))    # mean along the axis = 1 print("\nmean of arr, axis = 1 : ", np.mean(arr, axis = 1))  out_arr = np.arange(3)print("\nout_arr : ", out_arr) print("mean of arr, axis = 1 : ",       np.mean(arr, axis = 1, out = out_arr))
Output :
mean of arr, axis = None :  18.6

mean of arr, axis = 0 :  [17.33333333  8.33333333 31.         14.         22.33333333]

mean of arr, axis = 1 :  [24.  15.  16.8]

out_arr :  [0 1 2]
mean of arr, axis = 1 :  [24 15 16]

Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IntStream range() in Java

06 Dec, 2018
IntStream range(int startInclusive, int endExclusive) returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
Syntax :
static IntStream range(int startInclusive,   int endExclusive)

Parameters :
IntStream : A sequence of primitive int-valued elements.
startInclusive : The inclusive initial value.
endExclusive : The exclusive upper bound.
Return Value : A sequential IntStream for the range of int elements.
Example :
// Implementation of IntStream range// (int startInclusive, int endExclusive)import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(6, 10);          // Displaying the elements in range        // including the lower bound but        // excluding the upper bound        stream.forEach(System.out::println);    }}
6
7
8
9

Note : IntStream range(int startInclusive, int endExclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as :
for (int i = startInclusive; i < endExclusive ; i++) 
{
 ...
 ...
 ...
}

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Insertion and Deletion in Heaps in Data Sturcture

Here we will see how to insert and delete elements from binary heap data structures. Suppose the initial tree is like below −
insert(heap, n, item):
Begin
   if heap is full, then exit
   else
      n := n + 1
      for i := n, i > 1, set i := i / 2 in each iteration, do
         if item <= heap[i/2], then break
         heap[i] = heap[i/2]
      done
   end if
   heap[i] := item
End
Suppose we want to insert 30 into the heap −
delete(heap, n):
Begin
   if heap is empty, then exit
   else
      item := heap[1]
      last := heap[n]
      n := n – 1
      for i := 1, j := 2, j <= n, set i := j and j := j * 2, do
         if j < n, then
            if heap[j] < heap[j + 1], then j := j + 1
         end if
         if last >= heap[j], then break
         heap[i] := heap[j]
      done
   end if
   heap[i] := last
End
Suppose we want to delete 30 from the final heap −
How to add JTable to Panel in Java Swing?

To add JTabel to Panel, let us first crerate a panel −
JPanel panel = new JPanel();
Now, create JTable and add rows and columns with the records −
String[][] rec = {
   { "1", "Steve", "AUS" },
   { "2", "Virat", "IND" },
   { "3", "Kane", "NZ" },
   { "4", "David", "AUS" },
   { "5", "Ben", "ENG" },
   { "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
JTable table = new JTable(rec, header);
Add the above created table to panel −
panel.add(new JScrollPane(table));
The following is an example to add JTabel to Panel in Java Swing −
package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
         panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
This will produce the following output −
Removing strings from tuple in Python

When it is required to remove the strings froma  tuple, the list comprehension and the 'type' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
The 'type' method returns the class of the iterable passed to it as an argument.
Below is a demonstration for the same −
Live Demo
my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]

print("The list is : ")
print(my_list)

my_result = [tuple([j for j in i if type(j) != str])
   for i in my_list]
print("The list of tuple after removing the string is : ")
print(my_result)
The list is :
[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
The list of tuple after removing the string is :
[(45, 67), (45, 32), (59, 13)]
A list of tuple is defined, and is displayed on the console.
It is iterated over, using list comprehension.
It is checked to see for not being a string.
It is then converted to a tuple, and then to a list again.
This operation's data is stored in a variable.
This variable is the output that is displayed on the console.
Routing requests in Node.js

Routing http requests is important because we want to execute different business rules based on request url and the responses will be different for each routes.
Earlier we saw, we can get the url by request.url in node. Simple example of user name input with routes is shown below −
const http = require('http');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST">
      <input type="text" name="user"/>
      <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
});
server.listen(3000);
Run it on terminal: node App.js
Open browser and navigate to localhost:3000/ you will see below output −
We checked if url is matching with ‘/’, then only sending a response to display a input box with submit button to client. Here in code, we used return res.end() to avoid any change in response object once end() function is called.
If the url is different than just ‘/’ then we can display other messages. We used form action ‘/username’ and method is post. Also we have input box with name attribute as user. This name attribute will be passed in the post request for further use.
Complete App.js file is −
const http = require('http');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/>       <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
});
server.listen(3000);
The outputs screen once username is entered and send is clicked −
We can see here, the url is changed to /username, it is because we added form action in earlier response.
In the second res.end(), we have not added a return statement because there is no code after that so we don’t need to bother about it.
With url /username, our code does not execute the if block containing code for form input but instead will execute the code below the if block.
How to change the list item bg-color individually using ngFor in Angular 2+ ? - GeeksforGeeks

07 Sep, 2020
Introduction:We can solve this using *ngFor directive and attribute binding for binding the background colour.
Approach:Using *ngFor directive iterate through a list of items in .html file.By using attribute binding, bind the background color for every item in the list.By default use an array which consists of false boolean value in .ts file.Use a on click event handler to toggle the background color of the item in the list.Once the implementation is done then serve the project using below command.ng serve --open
Using *ngFor directive iterate through a list of items in .html file.
By using attribute binding, bind the background color for every item in the list.
By default use an array which consists of false boolean value in .ts file.
Use a on click event handler to toggle the background color of the item in the list.
Once the implementation is done then serve the project using below command.ng serve --open
ng serve --open
Implementation by code:app.component.html: 
<ul>                                                                                          <li  (click)="changeColor[i]=!changeColor[i]"  // we are toggling the background // colour on click event handler   [style.background-color] = "changeColor[i]  ? 'red' : 'green'"    *ngFor="let item of list ; let i = index">      {{item.name}}    </li>    </ul>
app.component.ts: 
import { Component } from '@angular/core';  @Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {  changeColor= [false, false, false];  list = [    { name : 'GeeksForGeeks' },    { name : 'Google' },    { name : 'HackerRank'}  ];}
Output:Before clicking on any item:
After clicking on any item:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
SQL Query to Check Given Format of a Date - GeeksforGeeks

11 Aug, 2021
Here, we are going to see how to find the SQL Query to check whether the date passed to query is the date of the given format or not. In this article, we will be making use of the Microsoft SQL Server as our database.
Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table.
Creating Database:
CREATE DATABASE geeks;
Using the Database:
USE geeks;
Table Definition:
We have the following table named as department in our geeks database.
CREATE TABLE department
(
    ID int,
    SALARY int,
    NAME Varchar(20),
    JoinDate datetime 
);
Adding value into the table:
INSERT INTO department VALUES (1, 34000, 'Neha', '09-24-2013')
INSERT INTO department VALUES (2, 33000, 'Hema', '02-02-2015')
INSERT INTO department VALUES (3, 36000, 'Jaya', '09-09-2017')
INSERT INTO department VALUES (4, 35000, 'Priya', '05-18-2018')
INSERT INTO department VALUES (5, 34000, 'Ketan', '02-25-2019')
To verify the contents of the table use the following SQL query:
SELECT * FROM department;
Checking whether the date passed to query is the date of the given format or not:
SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false).
Syntax:
SELECT ISDATE(‘Date’) AS “Format”;
OR
SELECT *, ISDATE(‘ColumnName’) AS “Format” FROM TABLENAME ;
Example: 
SELECT TOP 1000 [ID]
     ,[SALARY]
     ,[NAME]
     ,[JoinDate], ISDATE(JoinDate) as Format 
 FROM [department]
kk773572498
Picked
SQL-Query
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?
SQL | Subquery
What is Temporary Table in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
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?
How to Select Data Between Two Dates and Times in SQL Server?
Tensorflow.js tf.data.Dataset.skip() Method - GeeksforGeeks

21 Jun, 2021
Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The tf.data.Dataset.skip() method is used to create a dataset that skips count initial elements from this dataset.
Syntax:
skip(count)
Parameters: This method has as single parameter as mentioned above and described below:
count: It is a tensor input where the number of element of this dataset that should be skipped to form the new dataset. When the count is greater than the size of this dataset, the new dataset will contain no elements. When the count is undefined or negative, it skips the entire dataset.
Return Value: It returns the tf.data.Dataset.
The below examples demonstrate the tf.data.Dataset.skip() method:
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Defining input elementsconst a =   tf.data.array([4, 5, 6, 7, 8, 9]).skip(3);await a.forEachAsync(e => console.log(e));
Output:
7
8
9
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Defining input elementsconst a =   tf.data.array([4, 5, 6, 7, 8, 9]).skip(4);await a.forEachAsync(e => console.log(e));
Output:
8
9
Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.skip
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
MongoDB | Delete Database using MongoShell - GeeksforGeeks

19 Nov, 2019
Prerequisite : MongoDB Introduction
Short Description : A MongoDB Database is a container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made of fields similar to a tuple in RDBMS, but it has a dynamic schema here.Example of a Document :
{
        "Name" : "Aman",
        Age : 24,
        Gender : "Male"    
}

Example of a Collection :
[    
    {
        "Name" : "Aman",
        Age : 24,
        Gender : "Male"    
    },
    {
        "Name" : "Suraj",
        Age : 32,
        Gender : "Male"    
    },
    {
        "Name" : "Joyita",
        "Age" : 21,
        "Gender" : "Female"
    }
]

MongoShell : The mongo shell is an interactive JavaScript interface to query and update data as well as perform administrative operations in MongoDB. Detailed explanation about the Mongo shell is given on this site.
Drop a Database : In MongoDB, databases hold collections of documents. On a single MongoDB server, we can run multiple databases. when you install MongoDB some databases are automatically generated to use. many times you need to delete some database when the database is no longer used.
db.dropDatabase() the command is used to drop an existing database. This command will delete the currently selected database. If you have not selected any database, then it will delete the default ‘test’ database.
Syntax :
 db.dropDatabase()
Example : The below screenshot is showing the use of “db.dropDatabase()” command for a newly created database name userDB.
How to delete a database which is not currently used : You can check currently selected database, using the command “db“. Then you can use “show dbs” command for checking the list of Databases. Then select the database you want to delete using command “use databasename“. Then execute db.dropDatabase() command to drop an existing database.
Example : In below example we were using a database name userDB and we want to delete a different database name adminDB. so first we are going to select adminDB database then we will delete this database.
References:https://docs.mongodb.com/manual/core/databases-and-collections/#databases
Akanksha_Rai
shubham_singh
MongoDB
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ?
How to remove a specific line or curve in Matplotlib?

To remove a specific line or curve in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Plot line1 and line2 using plot() method.
Pop the second line and remove it.
To display the figure, use show() method.
from matplotlib import pyplot as plt, image as mimg

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

line_1 = plt.plot([1, 2, 3])
line_2 = plt.plot([2, 4, 6])

line = line_2.pop(0)
line.remove()

plt.show()
Find the Number of 1 Bits in a large Binary Number in C++

Given a 32-bit Unsigned Binary Number, the task is to count the set bits, i.e., '1's present in it.
For Example
Input:
N = 00000000000000100111
Output:
4
Explanation: Total set bits present in the given unsigned number is 4, thus we will return the output as '4'.
We have given an unsigned 32-bit binary number. The task is to count how many '1's present in it.
To count the number of '1's present in the given binary number, we can use the inbuilt STL function '__builin_popcount(n)' which takes a binary number as the input parameter.
Take a binary number N as the input.
A function count1Bit(uint32_t n) takes a 32-bit binary number as the input and returns the count of '1' present in the binary number.
The inbuilt function __builtin_popcount(n) takes the input of 'n' as a parameter and returns the count.
Live Demo
#include<bits/stdc++.h>
using namespace std;
int count1bits(uint32_t n) {
   return bitset < 32 > (n).count();
}
int main() {
   uint32_t N = 0000000010100000011;
   cout << count1bits(N) << endl;
   return 0;
}
Running the above code will generate the output as,
4
In the given number, there are 4 set bits or '1s' present in it. So, the output is '4'.
Online Java Formatter

Editable Java Code
1234567891011121314151617181920212223242526import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexMatches{public static void main( String args[] ){// String to be scanned to find the pattern.String line = "This order was placed for QT3000! OK?";String pattern = "(.*)(\\d+)(.*)";// Create a Pattern objectPattern r = Pattern.compile(pattern);// Now create matcher object.Matcher m = r.matcher(line);if (m.find( )) {System.out.println("Found value: " + m.group(0) );System.out.println("Found value: " + m.group(1) );System.out.println("Found value: " + m.group(2) );} else {System.out.println("NO MATCH");}}}X
Privacy Policy
Cookies Policy
Terms of Use
Renaming column names – Python Pandas

We can use the rename() method to rename column names. Let’s say the following is our Pandas DataFrame with 3 columns −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)
We will rename two columns i.e. “Car” to “Car Names” and “Reg_Price” to “Registration Cost”:
dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})

Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame

# Renaming columns
res = dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})

print"\nUpdated DataFrame with renamed column names...\n",res


This will produce the following output −
DataFrame ...
        Car   Reg_Price   Units
0       BMW        7000      90
1     Lexus        1500     120
2     Tesla        5000     100
3   Mustang        8000     150
4  Mercedes        9000     200
5    Jaguar        6000     130

Updated DataFrame with renamed column names...
  Car Names   Registration Cost   Units
0       BMW                7000      90
1     Lexus                1500     120
2     Tesla                5000     100
3   Mustang                8000     150
4  Mercedes                9000     200
5    Jaguar                6000     130
How to use year input type in HTML?

The month input type is used in HTML using the <input type = "month">. Using this, allow the users to select month and year. But, what if you only want to show the year popup? Well, year input type isn’t available.
To use year input type, we will be using jQuery to add datepicker. It is used with the text input type. On running the program, only the year will be visible.
You can try to run the following code to learn how to use input type to set a year
Live Demo
<html>
   <head>
      <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
      </script>
      <script type="text/javascript">
         $(function() {
            $( "#date" ).datepicker({dateFormat: 'yy'});
         });
      </script>
   </head>
   <body>
      <form action = "" method = "get">
         Details:<br> <br>
         Student Name <br> <input type="name" name="sname"> <br>
         Year of Birth <br> <input type="text" id="date"> <br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
How to use the Entry widget in Tkinter?

The Entry widget is a single-line text widget defined in Tcl/Tk toolkit. We can use the Entry widget to accept and display single-line user input.
In order to use the Entry widget, you have to first create an Entry widget using the constructor Entry(parent, width, **options). Once we've defined our Entry widget, we can configure its properties such as font-properties, color, width, etc., using the configure() method.
Let use create an Entry widget to accept the username and display it in the window.
# Import the required libraries
from tkinter import *

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

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

def show_name():
   # Create a Label widget
   label = Label(win, text="Hello " + str(entry.get()) + "👋", font=('Calibri 25')).pack(pady=20)
   entry.delete(0, END)

# Create a Label
Label(win, text="Enter Your Name").pack()

# Create an Entry widget
entry = Entry(win, width=25)
entry.pack(pady=20)

Button(win, text="Submit", command=show_name).pack()

win.mainloop()
When you run the above code, it will display a window with an Entry widget and a button. Type your name in the given Entry widget and click the button to show the message on the window.
Background and foreground thread in C#

A thread is defined as the execution path of a program. Each thread defines a unique flow of control
When the foreground threads will close, the background threads will be terminated.
The property used for background thread is IsBackground that gets or sets a value indicating whether a thread is a background thread. The default value of this property would be false because the default threads created are Foreground Threads.
To create a background thread −
Thread bgThread = new Thread(tStart);
bgThread.IsBackground = true;
bgThread.Start();
Foreground threads continue to run until the last foreground thread is terminated.
When all the foreground threads are stopped, the application is closed. The default threads that are created are foreground threads.
GATE | GATE CS 2018 | Question 57 - GeeksforGeeks

09 Mar, 2018
The number of possible min-heaps containing each value from {1, 2, 3, 4, 5, 6, 7} exactly once is _______.
Note –This was Numerical Type question.(A) 80(B) 8(C) 20(D) 210Answer: (A)Explanation: Set minimum element as root (i.e 1), now 6 are remaining and left subtree will have 3 elements, each left subtree combination can be permuted in 2! ways.
Total ways to design min-heap with 7-elements =  *2! * 2! = 20*2*2 = 80
Alternative approach – Total number of min or max heap tree with 1 to N elements are using recurrence relation:
T(N) =(N-1)Ck * T(k) * T(N-k-1), where k = number of nodes on left subtree

T(1) = 1
T(2) = 1
T(3) = 2
T(4) = 3C2 * T(2) * T(1) = 3
T(5) = 4C3 * T(3) * T(1) = 8
T(6) = 5C3 * T(3) * T(2) = 20
T(7) = 5C3 * T(3) * T(3) = 80

So, answer is 80.
Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to set the margins of an element with JavaScript?

Use the margin property in JavaScript, to set the margins. You can try to run the following code to set the margins of an element with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button type="button" onclick="display()">Set all four margins</button>
      <p id="myID">This is demo text.</p>
      <script>
         function display() {
            document.getElementById("myID").style.margin = "30px 20px 40px 40px";
         }
      </script>
   </body>
</html>
How to create an ArrayList from an Array in Java?

The asList() method is used to convert an array to list.
Example:
import java.util.Arrays;
import java.util.List;

public class ArrayToList {
   public static void main(String args[]){
      Integer[] myArray = {23, 93, 56, 92, 39};
      List list = Arrays.asList(myArray);
      System.out.println(list);
   }
}
Output:
[23, 93, 56, 92, 39]
How to access elements of nested lists in R?

Sometimes the lists are contained in another list but we want to access the nested list’s elements. Since these elements are part of a list then cannot be directly accessed, first we need to access the broader list and then the list that contains the element to reach the actual element.
Consider the lists x1, x2, x3, x4, and x4 and the Total_List that contains these lists −
> x1<-c(list(1:5),list(6:10),list(11:15))
> x2<-c(list(letters[1:5]),list(letters[6:10], list(letters[11:15])))
> x3<-c(list(c("India","Australia"),list("Canada"),list(c("Russia","Malaysia"))))
> x4<-c(list("Europe"),list(c("Asia","America"),list(c("Africa","Antartica"))))
> x5<-c(list("Red"),list("Green"),list("Yellow"),list(c("White","Pink")))
> Total_Lists<-list(x1,x2,x3,x4,x5)
Printing the Total_Lists −
> Total_Lists
[[1]]
[[1]][[1]]
[1] 1 2 3 4 5
[[1]][[2]]
[1] 6 7 8 9 10
[[1]][[3]]
[1] 11 12 13 14 15
[[2]]
[[2]][[1]]
[1] "a" "b" "c" "d" "e"
[[2]][[2]]
[1] "f" "g" "h" "i" "j"
[[2]][[3]]
[[2]][[3]][[1]]
[1] "k" "l" "m" "n" "o"
[[3]]
[[3]][[1]]
[1] "India" "Australia"
[[3]][[2]]
[[3]][[2]][[1]]
[1] "Canada"
[[3]][[3]]
[[3]][[3]][[1]]
[1] "Russia" "Malaysia"
[[4]]
[[4]][[1]]
[1] "Europe"
[[4]][[2]]
[1] "Asia" "America"
[[4]][[3]]
[[4]][[3]][[1]]
[1] "Africa" "Antartica"
[[5]]
[[5]][[1]]
[1] "Red"
[[5]][[2]]
[1] "Green"
[[5]][[3]]
[1] "Yellow"
[[5]][[4]]
[1] "White" "Pink"
Now to access the first element in each of x1, x2, x3, x4, and x4 we can use the following code −
> lapply(Total_Lists,'[[',1)
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b" "c" "d" "e"
[[3]]
[1] "India" "Australia"
[[4]]
[1] "Europe"
[[5]]
[1] "Red"
Similarly, to access the third element in each of x1, x2, x3, x4, and x4 we just need to change 1 to 3 as shown below −
> lapply(Total_Lists,'[[',3)
[[1]]
[1] 11 12 13 14 15
[[2]]
[[2]][[1]]
[1] "k" "l" "m" "n" "o"
[[3]]
[[3]][[1]]
[1] "Russia" "Malaysia"
[[4]]
[[4]][[1]]
[1] "Africa" "Antartica"
[[5]]
[1] "Yellow"
Ruby on Rails - Render

Usually the view template with the same name as the controller method is used to render the results.
# The default. Does not need to be specified 
# in a controller method called "some_action"

render :action => 'some_action'   
render :action => 'another_action', :layout => false
render :action => 'some_action', :layout => 'another_layout'
Partials are stored in files called "_subformname" ( _error, _subform, _listitem).
render :partial => 'subform'
render :partial => 'error', :status => 500
render :partial => 'subform', :locals => { :variable => @other_variable }
render :partial => 'listitem', :collection => @list
render :partial => 'listitem', :collection => @list, :spacer_template => 'list_divider'
Like rendering an action, but finds the template based on the template root (app/views).
# renders app/views/weblog/show
render :template => 'weblog/show' 
render :file => '/path/to/some/file.html.erb'
render :file => '/path/to/some/filenotfound.html.erb', 
   status => 404, :layout => true
render :text => "Hello World"
render :text => "This is an error", :status => 500
render :text => "Let's use a layout", :layout => true
render :text => 'Specific layout', :layout => 'special'
Uses ERb to render the "miniature" template
render :inline => "<%= 'hello , ' * 3 + 'again' %>"
render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" }
render :nothing
render :nothing, :status => 403    # forbidden
def refresh
   
   render :update do |page|
      page.replace_html  'user_list', :partial => 'user', :collection => @users
      page.visual_effect :highlight, 'user_list'
   end
   
end
Change the content-type −
render :action => "atom.rxml", :content_type => "application/atom+xml"
 Print
 Add Notes
 Bookmark this page
How do I get current URL in Selenium Webdriver 2 Python?

We can get the current URL of a page with Selenium webdriver. The method current_url is available which obtains the present page URL and then we can print the result in the console.
s = driver.current_url
Let us find the URL of the page presently navigated and we shall get https://www.tutorialspoint.com/index.htm as the output.
 
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
#identify current URL with current_url
l= driver.current_url
print(Current URL is: " + l)
driver.close()
C++ Program to Add Two Numbers

Addition is a basic arithmetic operation. The program to add two numbers performs addition of two numbers and prints their sum on screen.
A program that demonstrates addition of two numbers is given as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int num1=15 ,num2=10, sum;
   sum = num1 + num2;
   cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;
   return 0;
}
Sum of 15 and 10 is 25
In the above program the sum of two numbers i.e. 15 and 10 is stored in variable sum.
sum = num1 + num2;
After that it is displayed on screen using the cout object.
cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;
A program that uses an array to store two numbers and their sum as well is given as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a[3];
   a[0]=7;
   a[1]=5;
   a[2]=a[0] + a[1];
   cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}
Sum of 7 and 5 is 12
In the above program, the numbers to be added are stored in the 0 and 1 index of the array.
a[0]=7;
a[1]=5;
After that, the sum is stored in the 2 index of the array.
a[2]=a[0] + a[1];
The sum is displayed on screen using the cout object.
cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
How to create a Password Entry Field in Tkinter?

Suppose you are creating a Login Form for a Tkinter application. In many cases, an ideal login requires a standard format of username, password, and other details of the user. Users can enter the password in the Entry field with any combination of alphanumeric characters. Generally, to establish a secure bridge between the user and the application, the password fields store the input in the form of "*" characters. In order to create a field that accepts the input in the form of "*," we have to use show="*" attribute in the Entry widget.
The following example will have an Entry widget that accepts the password in hidden form. If we click "Show Password", it will show the password on the screen.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

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

# Define a function to show the entered password
def show():
   p = password.get()
   ttk.Label(win, text="Your Password is: " + str(p)).pack()

password = StringVar()

# Add an Entry widget for accepting User Password
entry = Entry(win, width=25, textvariable=password, show="*")
entry.pack(pady=10)

# Add a Button to reveal the password
ttk.Button(win, text="Show Password", command=show).pack()

win.mainloop()
Running the above code will display a password field and a button to reveal the password on the screen.
Now, click the "Show Password" button to reveal the password on the screen.
Create a contiguous flattened NumPy array - GeeksforGeeks

19 Aug, 2020
Let us see how to create a contiguous array in NumPy.The contiguous flattened array is a two-dimensional and multi-dimensional array that is stored as a one-dimensional array. We will be using the ravel() method to perform this task.
Syntax : numpy.ravel(array, order = ‘C’)Parameters :
array : Input array.
order : C-contiguous, F-contiguous, A-contiguous; optional
Returns : Flattened array having same type as the Input array and and order as per choice.
Example 1 : Flattening a 2D array.
Python3
# Importing librariesimport numpy as np  # Creating 2D arrayarr = np.array([[5, 6, 7], [8, 9, 10]])print("Original array:\n", arr)  # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array)
Output :
Original array:
 [[ 5  6  7]
 [ 8  9 10]]
New flattened array:
 [ 5  6  7  8  9 10]

Example 2 : Flattening a 3D array.
Python3
# Importing librariesimport numpy as np  # Creating 3D arrayarr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])print("Original array:\n", arr)  # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array)
Output :
Original array:
 [[[3 4]
  [5 6]]

 [[7 8]
  [9 0]]]
New flattened array:
 [3 4 5 6 7 8 9 0]

Python numpy-arrayManipulation
Python-numpy
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()
How to convert an integer to a character in Python?

Python's built-in function chr() returns a sunicode character equivalent of an integer between 0 to 0x10ffff.
>>> chr(a)
'd'
>>> chr(300)
'Ĭ'
>>> chr(65)
'A'
SQL - SELECT Database, USE Statement

When you have multiple databases in your SQL Schema, then before starting your operation, you would need to select a database where all the operations would be performed.
The SQL USE statement is used to select any existing database in the SQL schema.
The basic syntax of the USE statement is as shown below −
USE DatabaseName;

Always the database name should be unique within the RDBMS.
You can check the available databases as shown below −
SQL> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| AMROOD             |
| TUTORIALSPOINT     |
| mysql              |
| orig               |
| test               |
+--------------------+
6 rows in set (0.00 sec)
Now, if you want to work with the AMROOD database, then you can execute the following SQL command and start working with the AMROOD database.
SQL> USE AMROOD;

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
SQL Tryit Editor v1.6

SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Python program to find Maximum and minimum element’s position in a list?

In python is very easy to find out maximum, minimum element and their position also. Python provides different inbuilt function. min() is used for find out minimum value in an array, max() is used for find out maximum value in an array. index() is used for finding the index of the element.
maxminposition(A, n)
/* A is a user input list and n is the size of the list.*/
Step 1: use inbuilt function for finding the position of minimum element.
            A.index(min(A))
Step 2: use inbuilt function for finding the position of a maximum element.
            A.index(max(A))

# Function to find minimum and maximum position in list
def maxminposition(A, n):
   # inbuilt function to find the position of minimum 
   minposition = A.index(min(A))
   # inbuilt function to find the position of maximum 
   maxposition = A.index(max(A)) 
   print ("The maximum is at position::", maxposition + 1) 
   print ("The minimum is at position::", minposition + 1)
# Driver code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
maxminposition(A,n)
Enter the size of the List ::4
Enter the Element::
12
34
1
66
The maximum is at position:: 4
The minimum is at position:: 3
Python program to check if a string has at least one letter and one number - GeeksforGeeks

07 Dec, 2021
Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string full fill above condition else return “False” (without quotes).Examples: 
Input: welcome2ourcountry34
Output: True

Input: stringwithoutnum
Output: False
Approach: The approach is simple we will use loop and two flags for letter and number. These flags will check whether the string contains letter and number. In the end, we will take AND of both flags to check if both are true or not. Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.
Python3
def checkString(str):       # initializing flag variable    flag_l = False    flag_n = False         # checking for letter and numbers in    # given string    for i in str:               # if string has letter        if i.isalpha():            flag_l = True         # if string has number        if i.isdigit():            flag_n = True         # returning and of flag    # for checking required condition    return flag_l and flag_n  # driver codeprint(checkString('thishasboth29'))print(checkString('geeksforgeeks'))
Output:
True
False
simranarora5sos
Python string-programs
python-string
Python-string-functions
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Python 3 - String isalpha() Method

The isalpha() method checks whether the string consists of alphabetic characters only.
Following is the syntax for islpha() method −
str.isalpha()

NA
This method returns true if all the characters in the string are alphabetic and there is at least one character, false otherwise.
The following example shows the usage of isalpha() method.
#!/usr/bin/python3

str = "this";  # No space & digit in this string
print (str.isalpha())

str = "this is string example....wow!!!"
print (str.isalpha())
When we run above program, it produces the following result −
True
False


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Modulo / Remainder in Arduino

The modulo operator in Arduino is exactly the same as in C language, or most other languages for that matter. The operator is %. The syntax is: a % b and it returns the remainder when a is divided by b.
The following example illustrates the use of this operator −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   Serial.println(10%3);
   Serial.println(4%2);
   Serial.println(50%9);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below. You can work out the remainders yourself and verify that the output is correct.