code-rag-bench/online-tutorials huggingface dataset:
ProgressDialog in Android using Kotlin?

This example demonstrates how to show a progress dialog in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Progress bar using Kotlin"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.app.ProgressDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val progressDialog = ProgressDialog(this@MainActivity)
      progressDialog.setTitle("Kotlin Progress Bar")
      progressDialog.setMessage("Application is loading, please wait")
      progressDialog.show()
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Practice questions on Arrays in C++

Array is a data structure that store data in the contagious memory location.
Declaring arrays
Declaring arrays is done by the following syntax :
int 1D[] - for 1-D array
int 2D[][] - for 2-D array
If you initialize an array with lesser number of elements, rest are initialized with 0.
Memory address of elements of the array
1-D array : address[i] = baseAddress + i*size
2-D array (row major) : address[i][j] = baseAddress + (i*n + j) * size
Now, let’s see some practice problem
Predict the output of the following code snippet
int arr[5] = {6, 9};
for(int i = 0; i<5; i++)
   cout<<arr[i]<<" ";
6 9 0 0 0
The array is initialized with two values and the rest of the values are initialized as 0 which is reflected in the output.
int arr[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout<<arr[1][2];
6
Find the address of the given element of the integer array. If base address is 1420.
1D array : arr[43]
address = 1420 + 43*2 = 1506
2D array of size arr[10][10] : arr[5][4], stored as row major
address = 1420 + (5*10 + 4)*2 = 1420 + (54)*2 = 1528.
MySQL - SUM rows with same ID?

To sum rows with same ID, use the GROUP BY HAVING clause.
Let us create a table −
mysql> create table demo84
   -> (
   -> id int,
   -> price int
   -> )
   -> ;
Query OK, 0 rows affected (0.60
Insert some records into the table with the help of insert command −
mysql> insert into demo84 values(1,2000);
Query OK, 1 row affected (0.08

mysql> insert into demo84 values(1,2000);
Query OK, 1 row affected (0.14

mysql> insert into demo84 values(2,1800);
Query OK, 1 row affected (0.14

mysql> insert into demo84 values(2,2200);
Query OK, 1 row affected (0.14

mysql> insert into demo84 values(3,1700);
Query OK, 1 row affected (0.12
Display records from the table using select statement −
mysql> select *from demo84;
This will produce the following output −
+------+-------+| id   | price |
+------+-------+|    1 |  2000 |
|    1 |  2000 ||    2 |  1800 ||    2 |  2200 |
|    3 |  1700 |+------+-------+
5 rows in set (0.00 sec)
+------+-------+
+------+-------+
|    1 |  2000 |
|    2 |  1800 |
|    3 |  1700 |
5 rows in set (0.00 sec)
Following is the query to sum rows with same id −
mysql> select id,sum(price) as Total from demo84
   -> group by id
   -> having sum(demo84.price) >=2000;
This will produce the following output −
+------+-------+| id   | Total |
+------+-------+|    1 |  4000 |
|    2 |  4000 |+------+-------+
2 rows in set (0.00 sec)
+------+-------+
+------+-------+
|    2 |  4000 |
2 rows in set (0.00 sec)
CoffeeScript - Conditionals

While programming, we encounter some scenarios where we have to choose a path from a given set of paths. In such situations, we need conditional statements. Conditional statements help us take decisions and perform right actions.
Following is the general form of a typical decision-making structure found in most of the programming languages.
JavaScript supports the if statement (including its variants) and switch statement. In addition to the conditionals available in JavaScript, CoffeeScript includes the unless statement, the negation of if, and even more.
Following are the conditional statements provided by CoffeeScript.
An if statement consists of a Boolean expression followed by one or more statements. These statements execute when the given Boolean expression is true.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
An unless statement is similar to if with a Boolean expression followed by one or more statements except. These statements execute when a given Boolean expression is false.
An unless statement can be followed by an optional else statement, which executes when a Boolean expression is true.
A switch statement allows a variable to be tested for equality against a list of values.
The if and unless statements are block statements that are written in multiple lines. CoffeeScript provides the then keyword using which we can write the if and the unless statements in a single line.
Following are the statements in CoffeeScript that are written using then keyword.
Using the if-then statement we can write the if statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is true.
The if-then statement can be followed by an optional else statement, which executes when the Boolean expression is false. Using if-then...else statement, we can write the if...else statement in a single line.
Using the unless-then statement, we can write the unless statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is false.
The unless-then statement can be followed by an optional else statement, which executes when the Boolean expression is true. Using unless-then...else statement, we can write the unless...else statement in a single line.
In CoffeeScript, you can also write the if and unless statements having a code block first followed by if or unless keyword as shown below. This is the postfix form of those statements. It comes handy while writing programs in CoffeeScript.
#Postfix if
Statements to be executed if expression

#Postfix unless
Statements to be executed unless expression

show example
 Print
 Add Notes
 Bookmark this page
Program to find minimum swaps needed to group all 1s together in Python

Suppose we have a binary string, we have to find the minimum number of swaps needed to group all 1’s together in any place in the string. So if the input is like "10101001101", then the output will be 3, as possible solution is "00000111111".
To solve this, we will follow these steps −
data := a list of bits from the given string
data := a list of bits from the given string
set one := 0, n:= length of data array
set one := 0, n:= length of data array
make an array summ of size n, and fill this with 0, set summ[0] := data[0]
make an array summ of size n, and fill this with 0, set summ[0] := data[0]
one := one + data[0]
one := one + data[0]
for i in range 1 to n – 1summ[i] := summ[i - 1] + data[i]one := one + data[i]
for i in range 1 to n – 1
summ[i] := summ[i - 1] + data[i]
summ[i] := summ[i - 1] + data[i]
one := one + data[i]
one := one + data[i]
ans := one
ans := one
left := 0, right := one – 1
left := 0, right := one – 1
while right < nif left is 0, then temp := summ[right], otherwise temp := summ[right] –summ[left - 1]ans := minimum of ans, one – tempincrease right and left by 1
while right < n
if left is 0, then temp := summ[right], otherwise temp := summ[right] –
if left is 0, then temp := summ[right], otherwise temp := summ[right] –
summ[left - 1]
ans := minimum of ans, one – temp
ans := minimum of ans, one – temp
increase right and left by 1
increase right and left by 1
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def solve(self, data):
      data = list(map(int, list(data)))
      one = 0
      n = len(data)
      summ=[0 for i in range(n)]
      summ[0] = data[0]
      one += data[0]
      for i in range(1,n):
         summ[i] += summ[i-1]+data[i]
         one += data[i]
      ans = one
      left = 0
      right = one-1
      while right <n:
         if left == 0:
            temp = summ[right]
         else:
            temp = summ[right] - summ[left-1]
         ans = min(ans,one-temp)
         right+=1
         left+=1
         return ans
ob = Solution()
print(ob.solve("10101001101"))
"10101001101"
3
How to make textarea 100% without overflow when padding is present ?

14 Jan, 2022
If we have given an HTML document containing <textarea> element and its parent element contains some padding then how to make textarea width to 100%. textarea contains. The idea is to create a div with the class name “wrapper”. Inside that <div> element, we create a text area with a certain number of columns and rows. In this case, it is 30 and 15 respectively. After that, we set the width property to 100% to make a textarea width 100%.
HTML Code: The HTML code contains a <textarea> element that holds rows and columns values.
html
<!DOCTYPE html><html> <head>    <title>        How to make 100% tetxarea        without overflowing when        padding is present?    </title></head> <body>    <div class="wrapper">        <textarea cols="30" rows="15"></textarea>    </div></body> </html>
CSS Code: The CSS code contains the wrapper class that holds padding, margin, and background-color property. The textarea element contains the width property.
CSS
<style>    .wrapper {        padding: 20px;        margin:15px 0;        background-color: #0f9d58;    }         textarea {        font-size:20px;        width:100%;    }</style>
Complete Code: In this section, we will combine the above two sections to make the width of <textarea> element 100% without overflowing when padding is present.
html
<!DOCTYPE html><html> <head>    <title>        How to make 100% tetxarea        without overflowing when        padding is present?    </title>     <style>        .wrapper {            padding: 20px;            margin: 15px 0;            background-color: #0f9d58;        }         textarea {            font-size: 20px;            width: 100%;        }    </style></head> <body>    <div class="wrapper">        <textarea cols="30" rows="15"></textarea>    </div></body> </html>
Output:  
 
tiagorangel2011
sumitgumber28
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Javascript | Math.sign( ) Function

09 Feb, 2022
The Math.sign() is a builtin function in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.
Syntax:
Math.sign(number)
Parameters: This function accepts a single parameter number which represents the number whose sign you want to know.
Return Value: The Math.sign() function returns five different values as described below:
It returns 1 if the argument passed is a positive number.It returns -1 if the argument passed is a negative number.It returns 0 if the argument passed is a positive zero.It returns -0 if the argument passed is a negative zero.If none of the above cases match,it returns Nan.
It returns 1 if the argument passed is a positive number.
It returns -1 if the argument passed is a negative number.
It returns 0 if the argument passed is a positive zero.
It returns -0 if the argument passed is a negative zero.
If none of the above cases match,it returns Nan.
Examples:
Input  : Math.sign(2)
Output : 1
     
Input  : Math.sign(-2)
Output : -1

Input  : Math.sign(0)
Output : 0

Input  : Math.sign(-0)
Output : -0

Input  : Math.sign(haa)
Output  : NaN

Below programs illustrates the Math.sign() function in JavaScript:
Example 1: When a positive number is passed as an argument.<script type="text/javascript">   document.write(Math.sign(2));          </script>Output:1
<script type="text/javascript">   document.write(Math.sign(2));          </script>
Output:
1
Example 2: When a negative number is passed as an argument:<script type="text/javascript">   document.write(Math.sign(-2));          </script>Output:-1
<script type="text/javascript">   document.write(Math.sign(-2));          </script>
Output:
-1
Example 3: When a positive zero is passed as an argument:<script type="text/javascript">   document.write(Math.sign(0));          </script>Output:0
<script type="text/javascript">   document.write(Math.sign(0));          </script>
Output:
0
Example 4: When a negative zero is passed as an argument:   <script type="text/javascript">    document.write(Math.sign(-0));           </script>Output:-0
   <script type="text/javascript">    document.write(Math.sign(-0));           </script>
Output:
-0
Example 5: When an invalid number is passed as an argument:<script type="text/javascript">   document.write(Math.sign(haa));          </script>Output:NaN
<script type="text/javascript">   document.write(Math.sign(haa));          </script>
Output:
NaN
Supported Browsers: The browsers supported by Javascript Math.sign( ) Function are listed below:
Google Chrome 38 and above
Firefox 25 and above
Opera 25 and above
Safari 9 and above
Edge 12 and above
ysachin2314
javascript-math
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the levels of factor of a given vector in R

23 May, 2021
Factors are the objects which are used to categorize the data and display the data as levels. The objects can be integer, character. They can be used to find the unique values in the given vector. The resulting data is known as levels. Factors are useful in statistical analysis in analyzing the categorical data. It is used to find the levels of the given vector. In this article, we are going to find the levels of factor in the given vector in R. 
Example:
Input:
data=[female,female,male,male,other]
Output:
factor=female,male,other.
We can convert the vector data into factor by using factor() function, with this we can get levels() of the given vector
Syntax:
factor(vector_name)
Result is factor levels.
Example:
R
# create a vector with subjects datadata=c("java","sql","python","java",       "security","python")  print(data)  # apply factora=factor(data)  print(a)
Output:
Example2: 
R
# create a vector with numeric datadata=c(1,2,3,4,5,3,4,5,6,2,7,8,6)  print(data)  # apply factora=factor(data)  print(a)
Output:
Example 3:
R
# create a vector with all type of datadata=c(1,2,3,4,5,3,4,"male","female","male",       "other",4.5,6.7,4.5)  print(data)  # apply factora=factor(data)  print(a)
Output:
Picked
R Factor-Programs
R-Factors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Left pad an integer in Java with zeros

Let us see an example first to understand how an integer looks with left padding −
888 //left padding with spaces
0000000999 //left padding with 7 zeros
Let us see an example to left pad a number with zero −
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val = 9899;
      System.out.println(String.format("%05d",val));
   }
}
09899
Let us see another example that pads a greater number of zeros −
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val = 9899;
      System.out.println(String.format("%010d", val));
   }
}
0000009899
How to save a plot in Seaborn with Python (Matplotlib)?

To save a plot in Seaborn, we can use the savefig() method.
Set the figure size and adjust the padding between and around the subplots.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Plot pairwise relationships in a dataset.
Save the plot into a file using savefig() method.
To display the figure, use show() method.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

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

df = pd.DataFrame(np.random.random((5, 5)), columns=["a", "b", "c", "d", "e"])
sns_pp = sns.pairplot(df)
sns_pp.savefig("sns-heatmap.png")
When we execute the code, it will create the following plot and save it as "sns-heatmap.png" in
the project folder.
Reloading modules in Python?

The reload() - reloads a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have mades changes to the code. In that scenario we need to make sure that modules are reloaded.
The argument passed to the reload() must be a module object which is successfully imported before.
import importlib
importlib.reload(sys)
>>> import sys
>>> import importlib
>>> importlib.reload(sys)
<module 'sys' (built-in)>
However, if you are trying to reload a module which is not imported before, you might get an Error.
>>> import importlib
>>> importlib.reload(sys)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
importlib.reload(sys)
NameError: name 'sys' is not defined
Few points to understand, when reload() is executed -
Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. However, the init function of the modules is not loaded again
Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. However, the init function of the modules is not loaded again
The old objects are only reclaimed after their reference counts comes down to zero.
The old objects are only reclaimed after their reference counts comes down to zero.
The names in the module namespace is changed to new object if any.
The names in the module namespace is changed to new object if any.
Other references of the old objects (like names external to the module) are not necessarily refers to the new objects and must be updated in each namespace where they occur if that is required.
Other references of the old objects (like names external to the module) are not necessarily refers to the new objects and must be updated in each namespace where they occur if that is required.
java.util.regex.Matcher.quoteReplacement()

The java.time.Matcher.quoteReplacement(String s) method returns a literal replacement String for the specified String.
Following is the declaration for java.time.Matcher.quoteReplacement(String s) method.
public static String quoteReplacement(String s)

s − The string to be literalized.
s − The string to be literalized.
A literal string replacement.
The following example shows the usage of java.time.Matcher.quoteReplacement(String s) method.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat$";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      
      try{
         //Below line will throw exception
         INPUT = matcher.replaceAll(REPLACE);
      } catch(Exception e){
         System.out.println("Exception: "+ e.getMessage());
      }
      INPUT = matcher.replaceAll(matcher.quoteReplacement(REPLACE));
      System.out.println(INPUT);
   }
}
Let us compile and run the above program, this will produce the following result −
Exception: Illegal group reference: group index is missing
The cat$ says meow All cat$s say meow.

 Print
 Add Notes
 Bookmark this page
Apache Commons IO - IOUtils

IOUtils provide utility methods for reading, writing and copying files. The methods work with InputStream, OutputStream, Reader and Writer.
Following is the declaration for org.apache.commons.io.IOUtils Class −
public class IOUtils
   extends Object

The features of IOUtils are given below −
Provides static utility methods for input/output operations.
Provides static utility methods for input/output operations.
toXXX() − reads data from a stream.
toXXX() − reads data from a stream.
write() − write data to a stream.
write() − write data to a stream.
copy() − copy all data to a stream to another stream.
copy() − copy all data to a stream to another stream.
contentEquals − compare the contents of two streams.
contentEquals − compare the contents of two streams.
Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
public class IOTester {
   public static void main(String[] args) {
      try {
         //Using BufferedReader
         readUsingTraditionalWay();
         //Using IOUtils
         readUsingIOUtils();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }
   //reading a file using buffered reader line by line
   public static void readUsingTraditionalWay() throws IOException {
      try(BufferedReader bufferReader = new BufferedReader( new InputStreamReader(
      new FileInputStream("input.txt") ) )) {
         String line;
         while( ( line = bufferReader.readLine() ) != null ) {
            System.out.println( line );
         }
      }
   }
   //reading a file using IOUtils in one go
   public static void readUsingIOUtils() throws  IOException {
      try(InputStream in = new FileInputStream("input.txt")) {
         System.out.println( IOUtils.toString( in , "UTF-8") );
      }
   }
}
It will print the following result −
Welcome to TutorialsPoint. Simply Easy Learning.
Welcome to TutorialsPoint. Simply Easy Learning.

 Print
 Add Notes
 Bookmark this page
How to work with document.head in JavaScript?

Use the document.head property in JavaScript to get the id of the <head> tag of the document. You can try to run the following code to implement document.head property in JavaScript −
 Live Demo
<!DOCTYPE html>
<html>
   <head id = "myid">
      <title>JavaScript Example</title>
   </head>
   <body>
      <h1>Employee Information</h1>
      <form>
         Name: <input type = "text" name = "name" value = "Amit"><br>
         Subject: <input type = "text" name = "sub" value = "Java">
      </form>
      <script>
         var a = document.head.id;
         document.write("<br>Head element id? "+a);
      </script>
   </body>
</html>
Rexx - pull

This is used to pull input from the stack or from the default stream.
Pull variable 

Variable − The variable to which the input value will be assigned to.
Variable − The variable to which the input value will be assigned to.
None
/* Main program */ 
options arexx_bifs 
pull input 
say input 
When you run the above program, you need to enter some input. If you enter the input value of ‘Tutorial’, the program will return the word ‘TUTORIAL’.
 Print
 Add Notes
 Bookmark this page
Python PostgreSQL - Create Table

You can create a new table in a database in PostgreSQL using the CREATE TABLE statement. While executing this you need to specify the name of the table, column names and their data types.
Following is the syntax of the CREATE TABLE statement in PostgreSQL.
CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

Following example creates a table with name CRICKETERS in PostgreSQL.
postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age INT,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255)
);
CREATE TABLE
postgres=#
You can get the list of tables in a database in PostgreSQL using the \dt command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as follows −
postgres=# \dt
            List of relations
Schema  | Name       | Type  | Owner
--------+------------+-------+----------
public  | cricketers | table | postgres
(1 row)
postgres=#

In the same way, you can get the description of the created table using \d as shown below −
postgres=# \d cricketers
               Table "public.cricketers"
Column          | Type                   | Collation | Nullable | Default
----------------+------------------------+-----------+----------+---------
first_name      | character varying(255) |           |          |
last_name       | character varying(255) |           |          |
age             | integer                |           |          |
place_of_birth  | character varying(255) |           |          |
country         | character varying(255) |           |          |
postgres=#

To create a table using python you need to execute the CREATE TABLE statement using the execute() method of the Cursor of pyscopg2.
The following Python example creates a table with name employee.
import psycopg2

#Establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)'''
cursor.execute(sql)
print("Table created successfully........")
conn.commit()
#Closing the connection
conn.close()
Table created successfully........


    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
Sort items in a Java TreeSet

First, create a TreeSet and add elements to it −
TreeSet<String> set = new TreeSet<String>();
set.add("65");
set.add("45");
set.add("19");
set.add("27");
set.add("89");
set.add("57");
Now, sort it in ascending order, which is the default −
Iterator<String> i = set.iterator();
while(i.hasNext()){
   System.out.println(i.next());
}
If you want to sort in descending order, then use the descendingIterator() method −
Iterator<String> j = set.descendingIterator();
while(j.hasNext()) {
   System.out.println(j.next());
}
The following is an example to sort items in a TreeSet in ascending and descending order −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("65");
      set.add("45");
      set.add("19");
      set.add("27");
      set.add("89");
      set.add("57");
      System.out.println("TreeSet elements (Sorted)...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nTreeSet elements (Sorted) in Descending order...");
      Iterator<String> j = set.descendingIterator();
      while(j.hasNext()) {
         System.out.println(j.next());
      }
   }
}
TreeSet elements (Sorted)...
19
27
45
57
65
89

TreeSet elements (Sorted) in Descending order...
89
65
57
45
27
19
How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on. 
>>> a = (1, 2, 3)
>>> b = (1, 2, 5)
>>> a < b
True
There is another type of comparison that takes into account similar and different elements. This can be performed using sets. Sets will take the tuples and take only unique values. Then you can perform a & operation that acts like intersection to get the common objects from the tuples. 
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a) & set(b)
{5}
You can also use set.intersection function to perform this operation. 
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])
How to set color opacity with RGBA in CSS? - GeeksforGeeks

26 Apr, 2021
In this article, we will see how to set the color opacity with RGBA in CSS. RGBA is a color format, basically containing values for red, green, blue respectively and ‘A’ in RGBA stands for Alpha. To set the opacity of color we mainly change the value of alpha. The value of alpha varies from 0.0 (fully transparent) to 1.0 (fully opaque).
Syntax:
class/id { attribute: rgba(val1, val2, val3, val4) }
Example: In the following example, we use the CSS background-color property with alpha value (opacity).
HTML
<!DOCTYPE html><html> <body>    <h2 style="color:green">        GeeksforGeeks    </h2>    <b>Setting opacity with rgba</b>         <p class="para1" style=        "background-color: rgba(255, 0, 0, 0.0);">        Red    </p>      <p class="para2" style=        "background-color:rgba(255, 0, 0, 0.9) ;">        Red    </p>      <p class="para3" style=        "background-color:  rgba(0, 255, 0, 0.3);">        Green    </p>      <p class="para4" style=        "background-color:  rgba(0, 255, 0, 0.7) ;">        Green    </p>      <p class="para5" style=        "background-color:rgba(0, 0, 255, 0.4) ;">        Blue    </p>      <p class="para6" style=        "background-color: rgba(0, 0, 255, 1.0);">        Blue    </p> </body> </html>
Output: We can see that different values of alpha representing the different transparency.
RGBA
bhartiomee25
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to set space between the flexbox ?
How to style a checkbox using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Angular Material - Content

The md-content, an Angular Directive, is a container element and is used for scrollable content. The layout-padding attribute can be added to have padded content.
The following example shows the use of md-content directive and also the use of angular content display.
am_content.htm
<html lang = "en">
   <head>
      <link rel = "stylesheet"
         href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
      
      <script type = "text/javascript">    
         angular.module('firstApplication', ['ngMaterial']);
      </script>
   </head>
   
   <body ng-app = "firstApplication" ng-cloak>
      <md-toolbar class = "md-warn">
         <div class = "md-toolbar-tools">
            <h2 class = "md-flex">HTML 5</h2>
         </div>
      </md-toolbar>
      
      <md-content flex layout-padding>
         <p>HTML5 is the next major revision of the HTML standard superseding HTML
         4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and
         presenting content on the World Wide Web.</p>
         
         <p>HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the
         Web Hypertext Application Technology Working Group (WHATWG).</p>
         
         <p>The new standard incorporates features like video playback and drag-and-drop
         that have been previously dependent on third-party browser plug-ins such as Adobe
         Flash, Microsoft Silverlight, and Google Gears.</p>
      </md-content>
   </body>
</html>
Verify the result.
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
C/C++ Program for Greedy Algorithm to find Minimum number of Coins

A greedy algorithm is an algorithm used to find an optimal solution for the given problem. greedy algorithm works by finding locally optimal solutions ( optimal solution for a part of the problem) of each part so show the Global optimal solution could be found.
In this problem, we will use a greedy algorithm to find the minimum number of coins/ notes that could makeup to the given sum. For this we will take under consideration all the valid coins or notes i.e. denominations of { 1, 2, 5, 10, 20, 50 , 100, 200 , 500 ,2000 }. And we need to return the number of these coins/notes we will need to make up to the sum.
Let’s take a few examples to understand the context better −
Input : 1231
Output : 7
Explanation − We will need two Rs 500 notes, two Rs 100 notes, one Rs 20 note, one Rs 10 note and one Re 1 coin. That sums to 2+2+1+1+1 = 7
Input : 2150
Output : 3
Explanation − We will need one Rs 2000 note, one Rs 100 note, and one Rs 50 note.
To solve this problem using a greedy algorithm, we will find the which is the largest denomination that can be used. then we will subtract the largest denomination from the sum and again do the same process until the sum becomes zero.
Input: sum,
Initialise the coins = 0
Step 1: Find the largest denomination that can be used i.e. smaller than sum.
Step 2: Add denomination two coins and subtract it from the Sum
Step 3: Repeat step 2 until the sum becomes 0.
Step 4: Print each value in coins.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int notes[] = { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 };
int n = sizeof(notes) / sizeof(notes[0]);
void minchange(int sum){
   vector<int> coins;
   for (int i = n - 1; i >= 0; i--) {
      while (sum >= notes[i]) {
         sum -= notes[i];
         coins.push_back(notes[i]);
      }
   }
   for (int i = 0; i < coins.size(); i++)
      cout << coins[i] << "\t";
}
int main(){
   int n = 3253;
   cout << "The minimum number of coins/notes that sum up " << n << " is \t ";
   minchange(n);
   return 0;
}
The minimum number of coins/notes that sum up 3253 is
2000 500 500 200 50 2 1
MySQL Aliases

Aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Orders" table:
The following SQL statement creates two aliases, one for the CustomerID 
column and one for the CustomerName column:
The following SQL statement creates two aliases, one for the CustomerName 
column and one for the ContactName column. Note: Single or double quotation marks 
are required if the alias name contains spaces:
The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, 
City and Country):
The following SQL statement selects all the orders from the customer with 
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and 
give them the table aliases of "c" and "o" respectively (Here we use 
aliases to make the SQL shorter):
The following SQL statement is the same as above, but without aliases:
Aliases can be useful when:
There are more than one table involved in a query
Functions are used in the query
Column names are big or not very readable
Two or more columns are combined together
When displaying the Customers table,
make an ALIAS of the PostalCode column,
the column should be called Pno instead.
SELECT CustomerName,
Address,
PostalCode 
FROM Customers;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Python – Merge Dictionaries List with duplicate Keys

When it is required to merge dictionaries list with duplicate keys, the keys of the strings are iterated over and depending on the condition, the result is determined.
Below is a demonstration of the same
my_list_1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}]

my_list_2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}]

print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
for i in range(0, len(my_list_1)):

   id_keys = list(my_list_1[i].keys())
   for key in my_list_2[i]:

      if key not in id_keys:
         my_list_1[i][key] = my_list_2[i][key]

print("The result is : " )
print(my_list_1)
The first list is :
[{'aba': 1, 'best': 4}, {'python': 10, 'fun': 15}, {'scala': 'fun'}]
The second list is :
[{'scala': 6}, {'python': 3, 'best': 10}, {'java': 1}]
The result is :
[{'aba': 1, 'best': 4, 'scala': 6}, {'python': 10, 'fun': 15, 'best': 10}, {'scala': 'fun', 'java': 1}]
Two list of dictionaries are defined and displayed on the console.
Two list of dictionaries are defined and displayed on the console.
The list of dictionary is iterated over and the keys are accessed.
The list of dictionary is iterated over and the keys are accessed.
These keys are stored in a variable.
These keys are stored in a variable.
The second list of dictionary is iterated over, and if the keys in this are not present in the previous variable, the specific keys from both the lists are equated.
The second list of dictionary is iterated over, and if the keys in this are not present in the previous variable, the specific keys from both the lists are equated.
The result is displayed on the console.
The result is displayed on the console.
How to programmatically add buttons into a layout one by one in several lines in Android

This example demonstrates how do I programmatically add buttons into a layout one by one several lines in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   tools:context=".MainActivity"
   android:orientation="vertical">
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LinearLayout layout = new LinearLayout(this);
      layout.setOrientation(LinearLayout.VERTICAL);
      for (int i = 0; i < 3; i++) {
         LinearLayout row = new LinearLayout(this);
         row.setLayoutParams(new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.WRAP_CONTENT,
               LinearLayout.LayoutParams.WRAP_CONTENT));
         for (int j = 0; j < 4; j++) {
            Button btnTag = new Button(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.WRAP_CONTENT,
               LinearLayout.LayoutParams.MATCH_PARENT));
            btnTag.setText("Button " + (j + 1 + (i * 4 )));
            btnTag.setId(j + 1 + (i * 4));
            row.addView(btnTag);
         }
         layout.addView(row);
      }
      setContentView(layout);
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
MySQL show tables sort by table name?

You can sort the table_name property from INFORMATION_SCHEMA.TABLES with ORDER BY clause. Sort in ascending order or descending order with the help of ASC or DESC respectively. The syntax is as follows −
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' AND table_schema='yourDatabaseName'
ORDER BY table_name DESC;
Use the database with the name sample and have some tables. First, we will show all tables after that we will apply to sort on the table name. The query to display all tables is as follows −
mysql> show tables;
The following is the output −
+--------------------------+
| Tables_in_sample         |
+--------------------------+
| blobsizedemo             |
| insert_prevent           |
| insertrecord_selecttable |
| insertrecordprevent      |
| mytable                  |
| newlinedemo              |
| notequaloperator         |
| sumofeverydistinct       |
| yourtable                |
+--------------------------+
9 rows in set (0.00 sec)
Here is the query to sort by table name. Now, let us display all tables in descending order with ORDER BY clause −
mysql> SELECT table_name
   -> FROM information_schema.tables
   -> WHERE table_type = 'BASE TABLE' AND table_schema='sample'
   -> ORDER BY table_name DESC;
The following is the output −
+--------------------------+
| TABLE_NAME               |
+--------------------------+
| yourtable                |
| sumofeverydistinct       |
| notequaloperator         |
| newlinedemo              |
| mytable                  |
| insertrecordprevent      |
| insertrecord_selecttable |
| insert_prevent           |
| blobsizedemo             |
+--------------------------+
9 rows in set (0.00 sec)
Redis - Lists

Redis Lists are simply lists of strings, sorted by insertion order. You can add elements in Redis lists in the head or the tail of the list.
Maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per list).
redis 127.0.0.1:6379> LPUSH tutorials redis 
(integer) 1 
redis 127.0.0.1:6379> LPUSH tutorials mongodb 
(integer) 2 
redis 127.0.0.1:6379> LPUSH tutorials mysql 
(integer) 3 
redis 127.0.0.1:6379> LRANGE tutorials 0 10  
1) "mysql" 
2) "mongodb" 
3) "redis"

In the above example, three values are inserted in Redis list named ‘tutorials’ by the command LPUSH.
Following table lists some basic commands related to lists.
Removes and gets the first element in a list, or blocks until one is available
Removes and gets the last element in a list, or blocks until one is available
Pops a value from a list, pushes it to another list and returns it; or blocks until one is available
Gets an element from a list by its index
Inserts an element before or after another element in a list
Gets the length of a list
Removes and gets the first element in a list
Prepends one or multiple values to a list
Prepends a value to a list, only if the list exists
Gets a range of elements from a list
Removes elements from a list
Sets the value of an element in a list by its index
Trims a list to the specified range
Removes and gets the last element in a list
Removes the last element in a list, appends it to another list and returns it
Appends one or multiple values to a list
Appends a value to a list, only if the list exists

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page