code-rag-bench/online-tutorials huggingface dataset:
How to fix number of visible items in HTML dropdown and allow multiple selections ? - GeeksforGeeks

24 Aug, 2020
Drop down menu provides a list of options to choose from. The HTML <select> tag is used to create a drop down list.
When the number of options in a drop-down list is large, fixing the number of visible items may be useful. This can be done by using the “size” attribute of <select> tag.  
In the following example, 2 items are visible at a time because the value of the size attribute is set to 2.
Example 1:
<!DOCTYPE html><html>    <body>   Choose a language:<br>   <select id="language" size="2" >       <option value="C">C</option>       <option value="C++">C++</option>       <option value="Java">Java</option>       <option value="Python">Python</option>       <option value="R">R</option>       <option value="HTML">HTML</option>       <option value="JavaScript">JavaScript</option>   </select></body>  </html>
Output:
In the above example, only one item can be selected from the list. To enable multiple selections, a “multiple” attribute is used. In the following example, multiple options can be selected by holding the Ctrl button (Windows) or Command (Mac):
Example 2:
<!DOCTYPE html><html>  <body>   Choose a language:<br>     <select id="language" size="4" multiple>       <option value="C">C</option>       <option value="C++">C++</option>       <option value="Java">Java</option>       <option value="Python">Python</option>       <option value="R">R</option>       <option value="HTML">HTML</option>       <option value="JavaScript">JavaScript</option>     </select>     <p>       Hold ctrl (windows) or Command        (Mac) to select multiple option   </p>    </body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
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 ?
Difference between var, let and const keywords in JavaScript
GATE | GATE-CS-2004 | Question 22 - GeeksforGeeks

14 Feb, 2018
How many 8-bit characters can be transmitted per second over a 9600 baud serial communication link using asynchronous mode of transmission with one start bit, eight data bits, two stop bits, and one parity bit ?(A) 600(B) 800(C) 876(D) 1200Answer: (B)Explanation:  Background required – Physical Layer in OSI Stack
In serial Communications, information is transferred in or out one bit at a time.The baud rate specifies how fast data is sent over a serial line. It’s usually expressed in units of bits-per-second (bps). Each block (usually a byte) of data transmitted is actually sent in a packet or frame of bits. Frames are created by appending synchronization and parity bits to our data.
"9600 baud" means that the serial port is capable of transferring a 
maximum of 9600 bits per second.

Total Data To send = 1 bit(start) + 8 bits(char size) + 1 bit(Parity) + 2 bits(Stop) 

= 12 bits.

Number of 8-bit characters that can be transmitted per second  = 9600/12 = 800.

This explanation is contributed by Pranjul Ahuja.
Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Matplotlib.figure.Figure.add_subplot() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The add_subplot() method figure module of matplotlib library is used to add an Axes to the figure as part of a subplot arrangement.
Syntax: add_subplot(self, *args, **kwargs)
Parameters: This accept the following parameters that are described below:
projection : This parameter is the projection type of the Axes.
sharex, sharey : These parameters share the x or y axis with sharex and/or sharey.
label : This parameter is the label for the returned axes.
Returns: This method return the axes of the subplot.
Below examples illustrate the matplotlib.figure.Figure.add_subplot() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom mpl_toolkits.axisartist.axislines import Subplot     fig = plt.figure(figsize =(4, 4))   ax = Subplot(fig, 111)fig.add_subplot(ax)   ax.axis["left"].set_visible(False)ax.axis["bottom"].set_visible(False)  fig.suptitle('matplotlib.figure.Figure.add_subplot() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np     np.random.seed(19680801)  xdata = np.random.random([2, 10])  xdata1 = xdata[0, :]xdata2 = xdata[1, :]  ydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3   fig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange')   ax.set_xlim([0, 1])ax.set_ylim([0, 1])fig.suptitle('matplotlib.figure.Figure.add_subplot() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
HTML | <td>colspan Attribute

29 Apr, 2019
The HTML <td> colspan Attribute is used to specify the number of columns a table should span.
Syntax:
<td colspan="number"> 
Attribute Values: It contains the numeric value which specifies the number of columns a cell should span.
Example: This Example illustrates the use of colspan attribute in Tabledata Element.
<!DOCTYPE html><html>  <head>    <title>      HTML <td>colspan Attribute  </title>    <style>        table,        th,        td {            border: 1px solid black;            border-collapse: collapse;            padding: 6px;        }    </style></head>  <body>    <h1 style="color: green;">      GeeksforGeeks  </h1>    <h2>      HTML <td>colspan      Attribute  </h2>    <table>        <tr>            <th>Name</th>            <th>Expense</th>        </tr>        <tr>            <td>Arun</td>            <td>₹10</td>        </tr>        <tr>            <td>Priya</td>            <td>₹8</td>        </tr>          <!-- The last row -->        <tr>            <!-- This td will span                 two columns, that is                 a single column will                 take up the space of 2 -->            <td colspan="2">              Sum: ₹18          </td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <td>colspan Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Java Program to add minutes to current time using Calendar.add() method

Import the following package for Calendar class in Java.
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time.
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the minutes using the calendar.add() method and Calendar.HOUR_OF_DAY constant.
calendar.add(Calendar.MINUTE, 10);
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Add 10 minutes to current date
      calendar.add(Calendar.MINUTE, 10);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}
Current Date = Thu Nov 22 16:24:27 UTC 2018
Updated Date = Thu Nov 22 16:34:27 UTC 2018
How to manage image resolution of a graph in Matplotlib

An Image contains a 2-D matrix RGB data points which can be defined by the dots point per inch [ DPI ] of the image. The resolution of the image is important because a hi-resolution image will have much more clarity.
We have a method ‘plt.savefig()’ in Matplotlib which determines the size of the image in terms of its pixels. Ideally it is having an ‘dpi’ parameter.
Let’s see how we can manage the resolution of a graph in Matplotlib.
import matplotlib.pyplot as plt
import numpy as np

#Prepare the data for histogram
np.random.seed(1961)
nd = np.random.normal(13, 5, 1000)

#Define the size of the plot
plt.figure(figsize=(8,6))
plt.hist(nd)
plt.grid()

#set the dpi value to 300
plt.savefig('histogram_img.png', dpi=300)
plt.show()
plt.figure(figsize=(18,12))
plt.hist(nd)
plt.grid()

#Set the dpi value to 150
plt.savefig('histogram_100.png', dpi=150)
plt.show()
Running the above code will generate the output as,
Memory Organisation in Computer Architecture

13 Feb, 2020
The memory is organized in the form of a cell, each cell is able to be identified with a unique number called address. Each cell is able to recognize control signals such as “read” and “write”, generated by CPU when it wants to read or write address. Whenever CPU executes the program there is a need to transfer the instruction from the memory to CPU because the program is available in memory. To access the instruction CPU generates the memory request.
Memory Request:Memory request contains the address along with the control signals. For Example, When inserting data into the stack, each block consumes memory (RAM) and the number of memory cells can be determined by the capacity of a memory chip.
Example: Find the total number of cells in 64k*8 memory chip.
Size of each cell = 8
Number of bytes in 64k = (2^6)*(2^10)

Therefore, 
the total number of cells = 2^16 cells 
With the number of cells, the number of address lines required to enable one cell can be determined.
Word Size:It is the maximum number of bits that a CPU can process at a time and it depends upon the processor. Word size is a fixed size piece of data handled as a unit by the instruction set or the hardware of a processor.
Word size varies as per the processor architectures because of generation and the present technology, it could be low as 4-bits or high as 64-bits depending on what a particular processor can handle. Word size is used for a number of concepts like Addresses, Registers, Fixed-point numbers, Floating-point numbers.
Technical Scripter 2019
Computer Organization & Architecture
GATE CS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Computer Architecture | Flynn's taxonomy
I2C Communication Protocol
Architecture of Distributed Shared Memory(DSM)
ARM processor and its Features
Direct Access Media (DMA) Controller in Computer Architecture
Layers of OSI Model
Three address code in Compiler
Types of Operating Systems
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Remove duplicates from a string using STL in C++

28 May, 2019
Given a string S, remove duplicates in this string using STL in C++
Examples:
Input: Geeks for geeks
Output: Gefgkors

Input: aaaaabbbbbb
Output: ab

Approach:The consecutive duplicates of the string can be removed using the unique() function provided in STL.
Below is the implementation of the above approach.
#include <bits/stdc++.h>using namespace std;  int main(){    string str = "aaaaabbbbbb";    sort(str.begin(), str.end());      // Using unique() method    auto res = unique(str.begin(), str.end());      cout << string(str.begin(), res)         << endl;}
ab

cpp-strings
STL
C++
cpp-strings
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Inheritance in C++
vector erase() and clear() in C++
Substring in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
int() function in Python

21 Sep, 2021
Python int() function returns an integer from a given object or converts a number in a given base to decimal.
int(string, base)
string : consists of 1’s and 0’s
base : (integer value) base of the number.
Returns an integer value, which is equivalent of binary string in the given base. 
TypeError : Returns TypeError when any data type other than string or integer is passed in its equivalent position.
Python3
# Python3 program for implementation# of int() functionnum = 13 String = '187' # Stores the result value of# binary "187" and num additionresult_1 = int(String) + numprint("int('187') + 13 = ", result_1, "\n") # Example_2str = '100' print("int('100') with base 2 = ", int(str, 2))print("int('100') with base 4 = ", int(str, 4))print("int('100') with base 8 = ", int(str, 8))print("int('100') with base 16 = ", int(str, 16))
Output : 
int('187') + 13 =  200 

int('100') with base 2 =  4
int('100') with base 4 =  16
int('100') with base 8 =  64
int('100') with base 16 =  256
Python3
# Python3 program for implementation# of int() function # "111" taken as the binary stringbinaryString = "111" # Stores the equivalent decimal# value of binary "111"Decimal = int(binaryString, 2) print("Decimal equivalent of binary 111 is", Decimal) # "101" taken as the octal stringoctalString = "101" # Stores the equivalent decimal# value of binary "101"Octal = int(octalString, 8) print("Decimal equivalent of octal 101 is", Octal)
Output : 
Decimal equivalent of binary 111 is 7
Decimal equivalent of octal 101 is 65
Python3
# Python3 program to demonstrate# error of int() function  # when the binary number is not# stored in as stringbinaryString = 111 # it returns an error for passing an# integer in place of stringdecimal = int(binaryString, 2) print(decimal)
Output : 
TypeError: int() can't convert non-string with explicit base
Python3
try:    var = "Geeks"    print(int(var))except ValueError as e:    print(e)
Output:
invalid literal for int() with base 10: ‘Geeks’
It is used in all the standard conversions. For example conversion of binary to decimal, octal to decimal, hexadecimal to decimal.
rajatrj20
kumar_satyam
Python-Built-in-functions
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to add Slider in Next.js ?

15 Nov, 2021
In this article, we are going to learn how we can add File Dropper in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Approach: To add our Slider we are going to use the react-range package. The react-range package helps us to integrate sliders anywhere in our app. So first, we will install the react-range package and then we will add a slider on our homepage.
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
Install the required package: Now we will install the react-range package using the below command:
npm i react-range
Project Structure: It will look like this.
Adding the Slider: After installing the react-range package we can easily add Slider in our app. For this example, we are going to add a slider to our homepage.
Add the below content in the index.js file:
Javascript
import * as React from 'react';import { Range } from 'react-range';  export default class Slider extends React.Component {  state = { values: [50] };  render() {    return (      <>      <h3>GeeksforGeeks- Slider</h3>      <Range        step={0.1}        min={0}        max={100}        values={this.state.values}        onChange={(values) => this.setState({ values })}        renderTrack={({ props, children }) => (          <div            {...props}            style={{              ...props.style,              height: '6px',              width: '100%',              backgroundColor: '#ccc'            }}          >            {children}          </div>        )}        renderThumb={({ props }) => (          <div            {...props}            style={{              ...props.style,              height: '42px',              width: '42px',              backgroundColor: '#999'            }}          />        )}      />      </>    );  }}
Explanation: In the above example first, we are importing our Range component from the installed package. After that, we are creating a state to store the starting value. Then, we are adding our Range component. In the range component, we are setting the minimum value, maximum value, onChange function, and current Value.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Next.js
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nice and Renice Command in Linux with Examples

29 Aug, 2021
nice command in Linux helps in execution of a program/process with modified scheduling priority. It launches a process with a user-defined scheduling priority. In this, if we give a process a higher priority, then Kernel will allocate more CPU time to that process. Whereas the renice command allows you to change and modify the scheduling priority of an already running process. Linux Kernel schedules the process and allocates CPU time accordingly for each of them.  
1. To check the nice value of a process.  
ps -el | grep terminal
 
The eight highlighted value is the nice value of the process. 
2. To set the priority of a process 
 
nice -10 gnome-terminal
This will set the nice value of the mentioned process. 
3. To set the negative priority for a process  
nice --10 gnome-terminal
 
This will set the negative priority for the process. 
4.changing priority of the running process.  
sudo renice -n 15 -p 77982
 
This will change the priority of the process with pid 77982. 
5. To change the priority of all programs of a specific group. 
 
renice -n 10 -g 4
 
This command will set all the processes of gid 4 priority to 10. 
6. To change the priority of all programs of a specific user.  
sudo renice -n 10 -u 2
 
This will set all the processes of user 2 to 10. 
adnanirshad158
simmytarika5
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
TCP Server-Client implementation in C
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
Python – Print the last word in a sentence

23 Nov, 2021
Given a string, the task is to write a Python program to print the last word in that string.
Examples:
Input: sky is blue in color
Output: color
Explanation: color is last word in the sentence.
Input: Learn algorithms at geeksforgeeks
Output: geeksforgeeks
Explanation: color is last word in the sentence.
Approach #1: Using For loop + String Concatenation
Scan the sentence
Take an empty string, newstring.
Traverse the string in reverse order and add character to newstring using string concatenation.
Break the loop till we get first space character.
Reverse newstring and return it (it is the last word in the sentence).
Below is the implementation of the above approach:
Python3
# Function which returns last worddef lastWord(string):       # taking empty string    newstring = ""         # calculating length of string    length = len(string)         # traversing from last    for i in range(length-1, 0, -1):               # if space is occurred then return        if(string[i] == " "):                       # return reverse of newstring            return newstring[::-1]        else:            newstring = newstring + string[i]  # Driver codestring = "Learn algorithms at geeksforgeeks"print(lastWord(string))
Output:
geeksforgeeks
Approach #2: Using split() method
As all the words in a sentence are separated by spaces.
We have to split the sentence by spaces using split().
We split all the words by spaces and store them in a list.
The last element in the list is the answer
Below is the implementation of the above approach:
Python3
# Function which returns last worddef lastWord(string):       # split by space and converting    # string to list and    lis = list(string.split(" "))         # length of list    length = len(lis)         # returning last element in list    return lis[length-1]  # Driver codestring = "Learn algorithms at geeksforgeeks"print(lastWord(string))
Output:
geeksforgeeks
adnanirshad158
Python string-programs
Python
Python Programs
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
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Comments in Ruby - GeeksforGeeks

25 Jan, 2022
Statements that are not executed by the compiler and interpreter are called Comments. During coding proper use of comments makes maintenance easier and finding bugs easily.In Ruby, there are two types of comments:  
Single – line comments.Multi – line comments.
Single – line comments.
Multi – line comments.
Here, we are going to explain both types of comment with their syntax and example: 
It is represented by # sign. It is used to denote single line comment in Ruby. Its the most easiest typed comments. When we need only one line of a comment in Ruby then we can use the characters ‘#’ preceding the comment. Example :  
Ruby
# Ruby program to show single line comments #!/usr/bin/ruby -w # This is a single line comment.puts "Single line comment above"
Output:  
Single line comment above
 
If our comment is extending in more than one line than we can use a multiline comment.In Ruby, Multi- Line Comment started by using =begin and ended by using =end syntax.Syntax :  
=begin
continues
continues
.
.
.
Comment ends
=end
Example :  
Ruby
# Ruby program to show multi line comments#!/usr/bin/ruby -w puts "Multi line comments below" =beginComment line 1Comment line 2 Comment line 3=end
Output:  
Multi line comments below
We can also execute single line comments by using the above syntax as shown below:  
=begin Comment line 1 =end
 
sumitgumber28
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
How to Make a Custom Array of Hashes in Ruby?
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | String concat Method
Ruby | pop() function
Ruby For Beginners
Ruby | String empty? Method
Ruby | Array shift() function
Ruby | Class Method and Variables
Ruby on Rails Introduction
Fix for java.math.BigInteger cannot be cast to java.lang.Integer?

You can typecast with the help of method intValue(). The syntax is as follows −
Integer yourVariableName=((BigInteger) yourBigIntegerValue).intValue();
Here is the Java code to convert java.math.BigInteger cast to java.lang.Integer. The code is as follows −
 Live Demo
import java.math.BigInteger;
public class BigIntegerToInteger {
   public static void main(String []args) {
      BigInteger bigValue [] = new BigInteger[5];
      bigValue[0] = new BigInteger("6464764");
      bigValue[1] = new BigInteger("212112221122");
      bigValue[2] = new BigInteger("76475");
      bigValue[3] = new BigInteger("94874747");
      bigValue[4] = new BigInteger("2635474");
      for(int i = 0; i< bigValue.length; i++) {
         Integer value = ((BigInteger) bigValue[i]).intValue();
         System.out.println("Integer value is:"+value);
      }
   }
}
Here is the sample output −
Integer value is:6464764
Integer value is:1658823618
Integer value is:76475
Integer value is:94874747
Integer value is:2635474
SQLAlchemy ORM - Adding Objects

In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table.
We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object.
c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
session.add(c1)
Note that this transaction is pending until the same is flushed using commit() method.
session.commit()
Following is the complete script to add a record in customers table −
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Customers(Base):
   __tablename__ = 'customers'
   
   id = Column(Integer, primary_key=True)
   name = Column(String)
   address = Column(String)
   email = Column(String)
   
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()

c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')

session.add(c1)
session.commit()
To add multiple records, we can use add_all() method of the session class.
session.add_all([
   Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'), 
   Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'), 
   Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')]
)

session.commit()
Table view of SQLiteStudio shows that the records are persistently added in customers table. The following image shows the result −

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
How do I set a minimum window size in Tkinter?

A Tkinter window can be initialized after running the application. Generally, the width and the height of the window is resizable which can be minimized.
In order to set the window size to its minimum value, assign the value of width and height in minsize(height, width) method. The method can be invoked with the window or frame object.
#Import the required libraries
from tkinter import *

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

#Minimize the window
win.minsize(150, 100)

#Create a text label
Label(win, text= "Window Size is minimized to 150x100",font=('Helvetica bold',20)).pack(pady=20)

win.mainloop()
Running the above code will set the window size to its minimum.
HashSet clone() Method in Java - GeeksforGeeks

26 Nov, 2018
The Java.util.HashSet.clone() method is used to return a shallow copy of the mentioned hash set. It just creates a copy of the set.
Syntax:
Hash_Set.clone()
Parameters: The method does not take any parameters.
Return Value: The method just returns a copy of the HashSet.
Below program illustrate the Java.util.HashSet.clone() method:
// Java code to illustrate clone()import java.io.*;import java.util.HashSet;  public class Hash_Set_Demo {    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<String> set = new HashSet<String>();          // Use add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the HashSet        System.out.println("HashSet: " + set);          // Creating a new cloned set        HashSet cloned_set = new HashSet();          // Cloning the set using clone() method        cloned_set = (HashSet)set.clone();          // Displaying the new Set after Cloning;        System.out.println("The new set: " + cloned_set);    }}
HashSet: [4, Geeks, Welcome, To]
The new set: [Geeks, Welcome, To, 4]

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Overriding in Java
LinkedList in Java
Collections in Java
Queue Interface In Java
Multithreading in Java
Set in Java
Crystal Reports - Apply Boolean Formulas

There are different Boolean operators that can be used in formula in Crystal Reports. They are −
AND
OR
NOT
Eqv
Imp
XOR
All these operators are used to pass multiple conditions in formulas −
AND operator is used when you want both the conditions in the formula to be true. Other Boolean operators and their meaning is as mentioned in the above snapshot.
Using Boolean Operators ‘AND’ −
If {CUSTOMER.CUSTOMER_NAME} [1 to 2] = "AN" and

ToText({CUSTOMER.CUSTOMER ID}) [2] = "4" then

"TRUE"

Else

"FALSE"
Using Boolean Operators ‘AND’ and ‘OR’ −
If ({CUSTOMER.CUSTOMER_NAME} [1 to 2] = "AN" and

ToText({CUSTOMER.CUSTOMER ID}) [1] = "4") or

({CUSTOMER.CUSTOMER_NAME} [1 to 2] = "Ja" and

ToText({CUSTOMER.CUSTOMER ID}) [1] = "2") then

"Five star rating CUSTOMER"

Else

"1 star rating CUSTOMER"

    37 Lectures 
     2 hours 

 Neha Gupta

    61 Lectures 
     4.5 hours 

 Sasha Miller

    31 Lectures 
     32 mins

 Prof Krishna N Sharma

    35 Lectures 
     2 hours 

 Prof Krishna N Sharma

    24 Lectures 
     2 hours 

 Prof Krishna N Sharma
 Print
 Add Notes
 Bookmark this page
Java program to calculate the average of numbers in Java

An average of a set of numbers is their sum divided by their quantity. It can be defined as −
average = sum of all values / number of values
Here we shall learn how to programmatically calculate average.
1. Collect integer values in an array A of size N.
2. Add all values of A.
3. Divide the output of Step 2 with N.
4. Display the output of Step 3 as average.
Live Demo
public class AverageOfNNumbers {
   public static void main(String args[]){
      int i,total;
      int a[] = {0,6,9,2,7};
      int n = 5;
      total = 0;

      for(i=0; i<n; i++) {
         total += a[i];
      }
      System.out.println("Average ::"+ total/(float)n);
   }
}
Average ::4.8
How to create a unique temporary file name using Python?

You can use the tempfile module to create a unique temporary file in the most secure manner possible. There are no race conditions in the file’s creation. The file is readable and writable only by the creating user ID. Note that the user of mkstemp() is responsible for deleting the temporary file when done with it. To create a new temporary file, use it as follows −
import tempfile
_, temp_file_path = tempfile.mkstemp()
print("File path: " + temp_file_path)
Note that you need to manually delete this file after you're done with it.
Python program to split the string and convert it to dictionary - GeeksforGeeks

11 Jan, 2022
Given a delimiter (denoted as delim in code) separated string, order the splits in form of dictionary.
Examples :
Input : test_str = ‘gfg*is*best*for*geeks’, delim = “*” Output : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}  
Input : test_str = ‘gfg*is*best’, delim = “*” Output : {0: ‘gfg’, 1: ‘is’, 2: ‘best’}  
Method 1 : Using split() + loop
This is a brute way in which this task can be performed. In this, the split sections are stored in a temporary list using split() and then the new dictionary is created from the temporary list.
Python3
# Using split() + loop # initializing stringtest_str = 'gfg_is_best_for_geeks' # printing original stringprint("The original string is : "      + str(test_str)) # initializing delimdelim = "_" # splitting using split()temp = test_str.split(delim) res = dict() # using loop to reform dictionary with splitsfor idx, ele in enumerate(temp):    res[idx] = ele # printing resultprint("Dictionary after splits ordering : "      + str(res))
Output:
The original string is : gfg_is_best_for_geeks Dictionary after splits ordering : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}
Method 2 : Using dictionary comprehension + split() + enumerate()
This is a shorthand method with the help of which this task can be performed. In this, we perform the task of dictionary reconstruction using one-liner dictionary(dictionary comprehension) and enumerate() is used to help in ordering.
Python3
# Using dictionary comprehension + split() + enumerate() # initializing stringtest_str = 'gfg_is_best_for_geeks' # printing original stringprint("The original string is : "      + str(test_str)) # initializing delimdelim = "_" # using one liner to rearrange dictionaryres = {idx: ele for idx, ele in       enumerate(test_str.split(delim))} # printing resultprint("Dictionary after splits ordering : "      + str(res))
Output:
The original string is : gfg_is_best_for_geeks Dictionary after splits ordering : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}
rajeev0719singh
Python dictionary-programs
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 ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Best way to test if a row exists in a MySQL table

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition
can be used with subquery. It returns true when row exists in the table, otherwise false is
returned. True is represented in the form of 1 and false is represented as 0.
For better understanding, firstly we will create a table with the help of CREATE command.
The following is the query to create a table −
mysql> CREATE table ExistsRowDemo
-> (
-> ExistId int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
After creating the table successfully, we will insert some records with the help of INSERT
command. The query to insert records into the table −
mysql> INSERT into ExistsRowDemo values(100,'John');
Query OK, 1 row affected (0.16 sec)

mysql> INSERT into ExistsRowDemo values(101,'Bob');
Query OK, 1 row affected (0.17 sec)

mysql> INSERT into ExistsRowDemo values(103,'Carol');
Query OK, 1 row affected (0.20 sec)

mysql> INSERT into ExistsRowDemo values(104,'David');
Query OK, 1 row affected (0.13 sec)
After inserting all the records, we can display them with the help of SELECT command, which is
as follows −
mysql> SELECT * from ExistsRowDemo;

The following is the output −
+---------+-------+
| ExistId | Name  |
+---------+-------+
| 100     | John  |
| 101     | Bob   |
| 103     | Carol |
| 104     | David |
+---------+-------+
4 rows in set (0.00 sec)
We added some records into the table. The syntax to check whether a row exists in a table or
not with the help of EXISTS condition is as follows −
SELECT EXISTS(SELECT * FROM yourTableName WHERE yourCondition);

I am applying the above query to get the result −
Note: Firstly, I am considering the condition when row exists in the table. After that, the
condition will be mentioned when a row does not exist.
In this case, I am giving a condition when row exists. Let us apply the the above syntax to test
whether row exists or not.
mysql> SELECT EXISTS(SELECT * from ExistsRowDemo WHERE ExistId=104);

The following is the output −
+------------------------------------------------------+
| EXISTS(SELECT * from ExistsRowDemo WHERE ExistId=104)|
+------------------------------------------------------+
| 1                                                    |
+------------------------------------------------------+
1 row in set (0.00 sec)
From the above sample output, it is clear that row exists, since the value we got is 1. This
means TRUE!
In this case, I am explaining the condition when row does not exist.
Applying the above query.
mysql> SELECT EXISTS(SELECT * from ExistsRowDemo WHERE ExistId=105);

The following is the output −
+------------------------------------------------------+
| EXISTS(SELECT * from ExistsRowDemo WHERE ExistId=105)|
+------------------------------------------------------+
| 0                                                    |
+------------------------------------------------------+
1 row in set (0.00 sec)
From the above output, we can see the output is 0 i.e. false (row does not exist).
Database INSERT Operation in Perl

Perl INSERT operation is required when you want to create some records into a table. Here we are using table TEST_TABLE to create our records. So once our database connection is established, we are ready to create records into TEST_TABLE. Following is the procedure to create single record into TEST_TABLE. You can create as many as records you like using the same concept.
Record creation takes the following steps −
Preparing SQL statement with INSERT statement. This will be done using prepare() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Releasing Stattement handle. This will be done using finish() API.
If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections.
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
   (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
   values
   ('john', 'poul', 'M', 30, 13000)");
$sth->execute() or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
There may be a case when values to be entered is not given in advance. So you can use bind variables which will take the required values at run time. Perl DBI modules make use of a question mark in place of actual value and then actual values are passed through execute() API at the run time. Following is the example −
my $first_name = "john";
my $last_name = "poul";
my $sex = "M";
my $income = 13000;
my $age = 30;
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
   (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
   values
   (?,?,?,?)");
$sth->execute($first_name,$last_name,$sex, $age, $income)
or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
As HTTP is a stateless then how to maintain the session between web browser and web server?

HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Let us now discuss a few options to maintain the session between the Web Client and the Web Server −
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.
Loop through a Dictionary in Javascript

Here we'll implement a for each function in our class and accept a callback that we can call on every key-value pair. Let's see how we can implement such a function − 
forEach(callback) {
   for (let prop in this.container) {
      // Call the callback as: callback(key, value)
      callback(prop, this.container[prop]);
   }
}
You can test this using − 
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

myMap.forEach((k, v) => console.log(`Key is ${k} and value is ${v}`));
This will give the output −
Key is key1 and value is value1
Key is key2 and value is value2
ES6 Maps also have a prototype method forEach that you can use similar to how we've used it here. For example,
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
 
myMap.forEach((k, v) => console.log(`Key is ${k} and value is ${v}`));
This will give the output −
Key is key1 and value is value1
Key is key2 and value is value2
PyQt5 - QInputDialog Widget

This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter.
The user input can be a number, a string or an item from the list. A label prompting the user what he should do is also displayed.
The QInputDialog class has the following static methods to accept input from the user −
getInt()
Creates a spinner box for integer number
getDouble()
Spinner box with floating point number can be input
getText()
A simple line edit field to type text
getItem()
A combo box from which user can choose item
The following example implements the input dialog functionality. The top level window has three buttons. Their clicked() signal pops up InputDialog through connected slots.
items = ("C", "C++", "Java", "Python")
item, ok = QInputDialog.getItem(
   self, "select input dialog", "list of languages", items, 0, False
)
   if ok and item:
      self.le.setText(item)
		
   def gettext(self):
      text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
      if ok:
         self.le1.setText(str(text))
			
   def getint(self):
      num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
		
      if ok:
         self.le2.setText(str(num))
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class inputdialogdemo(QWidget):
   def __init__(self, parent = None):
      super(inputdialogdemo, self).__init__(parent)
		
      layout = QFormLayout()
      self.btn = QPushButton("Choose from list")
      self.btn.clicked.connect(self.getItem)
		
      self.le = QLineEdit()
      layout.addRow(self.btn,self.le)
      self.btn1 = QPushButton("get name")
      self.btn1.clicked.connect(self.gettext)
		
      self.le1 = QLineEdit()
      layout.addRow(self.btn1,self.le1)
      self.btn2 = QPushButton("Enter an integer")
      self.btn2.clicked.connect(self.getint)
		
      self.le2 = QLineEdit()
      layout.addRow(self.btn2,self.le2)
      self.setLayout(layout)
      self.setWindowTitle("Input Dialog demo")
		
   def getItem(self):
      items = ("C", "C++", "Java", "Python")
		
      item, ok = QInputDialog.getItem(
         self, "select input dialog", "list of languages", items, 0, False
      )
			
      if ok and item:
         self.le.setText(item)
			
   def gettext(self):
      text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
		
      if ok:
         self.le1.setText(str(text))
			
   def getint(self):
      num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
		
      if ok:
         self.le2.setText(str(num))
			
def main(): 
   app = QApplication(sys.argv)
   ex = inputdialogdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
Get and Set the stack size of thread attribute in C

To get and set the stack size of thread attribute in C, we use the following thread attributes:
Use for get threads stack size. The stacksize attribute gives the minimum stack size allocated to threads stack. In case of a successful run, then it gives 0 otherwise gives any value.
It takes two arguments −
pthread_attr_getstacksize(pthread_attr_t *attr, size_t *stacksize)
First one for pthread attribute.
Second one for giving the size of the thread attribute.
Used for set new threads stack size. The stacksize attribute gives the minimum stack size allocated to threads stack. In case of a successful run, then it gives 0 otherwise it gives any value.
It takes two arguments −
pthread_attr_setstacksize(pthread_attr_t *attr, size_t *stacksize)
First one for pthread attribute.
Second one for give the size of the new stack in bytes.
Begin
   Declare stack size and declare pthread attribute a.
   Gets the current stacksize by pthread_attr_getstacksize() and print it.
   Set the new stack size by pthread_attr_setstacksize() and get the stack size pthread_attr_getstacksize() and print it.
End
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int main() {
   size_t stacksize;
   pthread_attr_t a;
   pthread_attr_getstacksize(&a, &stacksize);
   printf("Current stack size = %d\n", stacksize);
   pthread_attr_setstacksize(&a, 67626);
   pthread_attr_getstacksize(&a, &stacksize);
   printf("New stack size= %d\n", stacksize);
   return 0;
}
Current stack size = 50
New stack size= 67626
Font Awesome - Web Application Icons

This chapter explains the usage of Font Awesome Web Application icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">

      <style>
         i.custom {font-size: 2em; color: gray;}
      </style>
		
   </head>
	
   <body>
      <i class = "fa fa-adjust custom"></i>
   </body>
	
</html>
The following table shows the usage and the results of Font Awesome Web Application icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page