code-rag-bench/online-tutorials huggingface dataset:
How can Tensorflow be used to train and compile a CNN model?

A convolutional neural network can be trained and compiled using the ‘train’ method and the ‘fit’ method respectively. The ‘epoch’ value is provided in the ‘fit’ method.
Read More:
What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?
We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor.
A neural network that contains at least one layer is known as a convolutional layer. Convolutional neural networks have been used to produce great results for a specific kind of problems, such as image recognition.  
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.
print("Compiling the model")
model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
   metrics=['accuracy'])
print("Training the model to fit the data")
history = model.fit(train_images, train_labels, epochs=10,validation_data=(test_images, test_labels))
Code credit: https://www.tensorflow.org/tutorials/images/cnn
Compiling the model
Training the model to fit the data
Epoch 1/10
1563/1563 [==============================] - 70s 44ms/step - loss: 1.7408 - accuracy: 0.3557 - val_loss: 1.2260 - val_accuracy: 0.5509
Epoch 2/10
1563/1563 [==============================] - 67s 43ms/step - loss: 1.1928 - accuracy: 0.5751 - val_loss: 1.0800 - val_accuracy: 0.6159
Epoch 3/10
1563/1563 [==============================] - 68s 43ms/step - loss: 1.0330 - accuracy: 0.6396 - val_loss: 0.9791 - val_accuracy: 0.6562
Epoch 4/10
1563/1563 [==============================] - 66s 43ms/step - loss: 0.9197 - accuracy: 0.6782 - val_loss: 0.9488 - val_accuracy: 0.6677
Epoch 5/10
1563/1563 [==============================] - 65s 42ms/step - loss: 0.8388 - accuracy: 0.7043 - val_loss: 0.9090 - val_accuracy: 0.6851
Epoch 6/10
1563/1563 [==============================] - 66s 42ms/step - loss: 0.7755 - accuracy: 0.7279 - val_loss: 0.8694 - val_accuracy: 0.6944
Epoch 7/10
1563/1563 [==============================] - 66s 42ms/step - loss: 0.7107 - accuracy: 0.7494 - val_loss: 0.9152 - val_accuracy: 0.6929
Epoch 8/10
1563/1563 [==============================] - 65s 42ms/step - loss: 0.6674 - accuracy: 0.7649 - val_loss: 0.8613 - val_accuracy: 0.7045
Epoch 9/10
1563/1563 [==============================] - 66s 42ms/step - loss: 0.6288 - accuracy: 0.7771 - val_loss: 0.8788 - val_accuracy: 0.7026
Epoch 10/10
1563/1563 [==============================] - 66s 42ms/step - loss: 0.5913 - accuracy: 0.7953 - val_loss: 0.8884 - val_accuracy: 0.7053
The model is compiled.
The next step is to train the model to fit the training data.
The number of steps to train the data is 10.
Python program to print all odd numbers in a range - GeeksforGeeks

31 Mar, 2020
Given starting and end points, write a Python program to print all odd numbers in that given range.
Example:
Input: start = 4, end = 15
Output: 5, 7, 9, 11, 13, 15

Input: start = 3, end = 11
Output: 3, 5, 7, 9, 11
Example #1: Print all odd numbers from given list using for loop
Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.
# Python program to print odd Numbers in given range  start, end = 4, 19  # iterating each number in listfor num in range(start, end + 1):          # checking condition    if num % 2 != 0:        print(num, end = " ")
Output:
5 7 9 11 13 15 17 19 
 Example #2: Taking range limit from user input
# Python program to print Even Numbers in given range  start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: "))  # iterating each number in listfor num in range(start, end + 1):          # checking condition    if num % 2 != 0:        print(num, end = " ")
Output:
Enter the start of range: 3
Enter the end of range: 11
3 5 7 9 11 
 Example #3: Taking range limit from user input
# Python program to print Even Numbers in given range  start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: "))  #create a list that contains only Even numbers in given rangeeven_list = range(start, end + 1)[start%2::2]  for num in even_list:    print(num, end = " ")
Output:
Enter the start of range: 3
Enter the end of range: 11
3 5 7 9 11 
KenMa
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
What is the difference between width and innerWidth in jQuery?

Width in jQuery
The width is the horizontal measurement of the container, for example, width of a div. It excludes the padding, border, or margin.
You can try to run the following code to learn how to get the width of an element in jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Width of div element: " + $("div").width());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br>
<button>Get Width of div</button>

</body>
</html>
innerWidth in jQuery
The innerWidth() returns the inner width of the first matched element. It includes padding, but not border and margin.
You can try to run the following code to get the inner width in jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Inner Width of div element: " + $("div").innerWidth());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br>
<button>Get Inner Width of div</button>

</body>
</html>
Why the constructor name is same as the class name in Java?

Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name.
class MyConstructor{
   public MyConstructor() {
      System.out.println("The constructor name should be same as the class name");
   }
   public static void main(String args[]){
      MyConstructor mc = new MyConstructor();
   }
}
In the above program, the constructor name should be the same as the class name (MyConstructor).
The constructor name should be same as the class name
How to use the PI constant in C++?

Here we will see how to use the PI constant in C++ program. The PI constant is present in the cmath header file. The name of the constant is M_PI. We can simply include that header file, and use the constant to perform operation.
In the following example we will see how to find area of a circle using PI constant.
#include <iostream>
#include <cmath>
using namespace std;
float area(int radius) {
   return M_PI * (radius * radius);
}
int main () {
   cout << "Area of a circle with radius 7 unit is: " << area(7);
}
Area of a circle with radius 7 unit is: 153.938
Print all prime numbers less than or equal to N in C++

In this problem, we are given a number N and we have to print all prime numbers less than or equal to N.
Let’s take an example to understand the topic better −
Input: 10
Output: 2 3 5 7
A prime number is a number that can be divided by only one and the number itself. Example: 2, 3.
A simple approach is to iterate from 2 to N and divide the number by it. If the number is not divisible, then it’s a prime number. Print the number. Do this till the number is equal to N. This approach is not that efficient.
A more effective approach will be checking for prime number by iterating from 2 to √N.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isPrimeNumber(int n){
   if (n <= 1)
      return false;
   if (n <= 3)
      return true;
   if (n % 2 == 0 || n % 3 == 0)
      return false;
   for (int i = 5; i * i <= n; i = i + 6)
      if (n % i == 0 || n % (i + 2) == 0)
         return false;
   return true;
}
void printPrime(int n){
   for (int i = 2; i <= n; i++) {
      if (isPrimeNumber(i))
         cout<<i<<" ";
      }
   }
int main(){
   int n = 41;
   cout<<"Prime numbers less than or equal to "<<n<<" are \n";
   printPrime(n);
}
Prime numbers less than or equal to 41 are
2 3 5 7 11 13 17 19 23 29 31 37 41
Simulation of 4-bit ALU

Moreover, we write an assembly program in 8085 assembly language just to simulate a 4-bit ALU by using an interface which is based on the logic controller. The Arithmetic Logical Unit always performs an addition, subtraction, AND operation, or OR operation, which is based on the 4-bit inputs for the desired operations to be performed.
For the simulation of the Arithmetic Logical Unit all the terminal inputs and outputs are provided by the ports of 8255 as it is indicated in the figure below.
The Pins ranging from 7-4 in the Port B are used as the inputs of X3-0;
The pins ranging from 3-0 of Port B are used as the inputs ranging from Y3-0;
Pins 7 and 6 of Port C used as S1 and S0 inputs;
The port A pins of 3-0 are used as the output Z3-0;
Pin 4 of Port A is used to provide Cy output in case of add and subtract operations.
S1 and S0 inputs determine the operation to be performed by the ALU as per the table that follows.
Here S1 and S0 are the inputs and Z is the output.
; FILE NAME ALU_PROG1.ASM
ORG C000H
PA EQU D8H
PB EQU D9H
PC EQU DAH
CTRL EQU DBH

MVI A, 10001010B
OUT CTRL ; Configure 8255 ports
LOOP: IN PB ; Input X and Y values through Port B
MOV B, A

ANI 0FH
MOV C, A ; C will now have Y input

MOV A, B
ANI F0H
RRC
RRC
RRC
RRC
MOV B, A ; B will now have X input

IN PC ; Read S1 and S0 values from Port
ANI 11000000B

RLC
RLC ; LS 2 bits of A will now have S1 and S0

CPI 00H
JZ ADD ; If S1 = 0 and S0 = 0 do Add operation

CPI 01H
JZ SUB ; If S1 = 0 and S0 = 1 do Subtract operation

CPI 02H
JZ AND ; If S1 = 1 and S0 = 0 do AND operation
OR: MOV A, B
ORA C
JMP DISP

ADD: MOV A, B
ADD C
JMP DISP

SUB: MOV A, B
SUB C
JMP DISP

AND: MOV A, B
ANA C
DISP: OUT PA
JMP LOOP
Pass arguments from array in PHP to constructor

The Reflection API can be used to pass arguments from array to constructor.
The above line creates a new class instance from given arguments −
public ReflectionClass::newInstanceArgs ([ array $args ] ) : object
It creates a new instance of the class when the arguments are passed to the constructor. Here, args refers to the arguments that need to be passed to the class constructor.
 Live Demo
<?php
   $my_class = new ReflectionClass('ReflectionFunction');
   $my_instance = $my_class->newInstanceArgs(array('substr'));
   var_dump($my_instance);
?>
This will produce the following output −
object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" }
Linux and Unix Test Disk I/O Performance with DD Command

Do you know how to check the performance of a hard drive like checking the read and write speed on your Linux operating systems? then, this article is for you!! which is basically created to provide you an overview of DD command, which is geared towards better guidance to new users and as an exploration tour for getting started to the Linux world.
DD is a command-line utility for Unix and Unix-like operating systems where the primary purpose is to copy a file and converting the format of the data during the process.
Open your Linux root terminal and add the following command-
$ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync
Output should be like this-
tp@linux:~$ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync
[sudo] password for tp:
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB) copied, 11.9635 s, 89.8 MB/s
tp@linux:~$
Please note that, 1GB is copied during the test and 89.8 MB/second is served throughout fthe test.
Chunks of DD command should be like this –
Before testing the first flush caches data, use the following command-
$ echo 3 | sudo tee /proc/sys/vm/drop_caches
time time dd if=/path/to/bigfile of=/dev/null bs=8k
Run the following command to test the data with cache-
tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB) copied, 11.4265 s, 94.0 MB/s
The above command copies 1.1GB of data and 94.0 MB/s is served for the test.
To deactivate cache, use the following command –
$ sudo hdparm -W0 /dev/sda
The output should be like this –
tp@linux:~$ sudo hdparm -W0 /dev/sda
/dev/sda:
setting drive write-caching to 0 (off)
write-caching = 0 (off)
Run the following command to test the data without cache -
$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct
The output should be like this –
tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB) copied, 11.5062 s, 93.3 MB/s
The above command copies 1.1GB of data and 93.3 MB/s is served for the test.
Congratulations! Now, you know how to test the disk I/O Performance with DD Command. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
Python dictionary len() Method

Python dictionary  method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
Following is the syntax for len() method −
len(dict)

dict − This is the dictionary, whose length needs to be calculated.
dict − This is the dictionary, whose length needs to be calculated.
This method returns the length.
The following example shows the usage of len() method.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7};
print "Length : %d" % len (dict)
When we run above program, it produces following result −
Length : 2


    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
Spurious Tuples in DBMS

24 Jun, 2020
In Database Management System (DBMS), data is represented in a tabular form through attributes and tuples i.e., columns and rows.There are various operations (insert, delete, update, modify, etc.) that we can perform on tables. One such operation is join. When we combine two tables into one, we call it a join and it is denoted by ⨝.
Spurious Tuples :Spurious Tuples are those rows in a table, which occur as a result of joining two tables in wrong manner. They are extra tuples (rows) which might not be required.
If relation is denoted by R, and its decomposed relations are denoted by R1, R2, R3....Rn, then, condition for not getting any Spurious Tuple is denoted by,
R1 ⨝ R2 ⨝ R3 .... ⨝ Rn = R
Whereas condition for getting Spurious Tuples is denoted by,
R ⊂ R1 ⨝ R2 ⨝ R3 .... ⨝ Rn
Example-1:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R.
After performing join operation of relations R1 and R2 (R1 ⨝ R2), we get back original relation R.
The condition for no spurious tuples, R1 ⨝ R2 = R, is met. Hence, we do not get any Spurious Tuples.
Conclusion – No Spurious Tuple exists.
Example-2:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R.
After performing join operation of relations R1 and R2 (R1 ⨝ R2), we do not get back original relation R.
The condition for spurious tuples, R ⊂ R1 ⨝ R2, is met. Hence, we get Spurious Tuples.
Conclusion – Spurious Tuples exist.
Note –Rows in DBMS are called tuples. Whereas, columns in DBMS are called attributes. Spurious Tuples can be remembered as extra rows in table. The natural join leading to Spurious Tuples is called Lossy Join. The natural join not resulting in Spurious Tuples is called Lossless Join.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
Difference between Star Schema and Snowflake Schema
What is Cursor in SQL ?
Getting the return value of Javascript code in Selenium.

We can get the return value of Javascript code with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method.
We shall be returning the value from the Javascript code with the help of the keyword return. Also we have to add the statement import org.openqa.selenium.JavascriptExecutor to work with Javascript.
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.getElementsByName('txtSearchText')[0].value")
Let us obtain the value entered in the edit box. The output should be Selenium.
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavascriptValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/tutor_connect/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element and enter text
      WebElement t=driver.findElement(By.id("txtSearchText"));
      t.sendKeys("Selenium");
      // Javascript executor to return value
      JavascriptExecutor j = (JavascriptExecutor) driver;
      String s = (String) j.executeScript("return document.getElementsByName('txtSearchText')[0].value");
      System.out.print("Value is: " +s);
      driver.quit();
   }
}
jsoup - Using Selector Syntax

Following example will showcase use of selector methods after parsing an HTML String into a Document object. jsoup supports selectors similar to CSS Selectors.
Document document = Jsoup.parse(html);
Element sampleDiv = document.getElementById("sampleDiv");
Elements links = sampleDiv.getElementsByTag("a");

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
Jsoup − main class to parse the given HTML String.
html − HTML String.
html − HTML String.
sampleDiv − Element object represent the html node element identified by id "sampleDiv".
sampleDiv − Element object represent the html node element identified by id "sampleDiv".
links − Elements object represents the multiple node elements identified by tag "a".
links − Elements object represents the multiple node elements identified by tag "a".
The document.select(expression) method parses the given CSS selector expression to select a html dom element.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content</p>"
         + "<div id='sampleDiv'><a href='www.google.com'>Google</a>"
         + "<h3><a>Sample</a><h3>"
         +"</div>"
         + "<div id='imageDiv' class='header'><img name='google' src='google.png' />"
         + "<img name='yahoo' src='yahoo.jpg' />"
         +"</div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      //a with href
      Elements links = document.select("a[href]");

      for (Element link : links) {
         System.out.println("Href: " + link.attr("href"));
         System.out.println("Text: " + link.text());
      }

      // img with src ending .png
      Elements pngs = document.select("img[src$=.png]");

      for (Element png : pngs) {
         System.out.println("Name: " + png.attr("name"));
      }

      // div with class=header
      Element headerDiv = document.select("div.header").first();
      System.out.println("Id: " + headerDiv.id());
   
      // direct a after h3
      Elements sampleLinks = document.select("h3 > a"); 

      for (Element link : sampleLinks) {
         System.out.println("Text: " + link.text());
      }
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Href: www.google.com
Text: Google
Name: google
Id: imageDiv
Text: Sample

 Print
 Add Notes
 Bookmark this page
How can I stop running a MySQL query?

Before stopping a running query of MySQL, first we need to see how many processes are
running with the help of show command.
The query for that is given as follows −
mysql> show processlist;
After executing the above query, we will get the output with some id’s. This is given as follows −
+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+
| 4 | event_scheduler | localhost | NULL | Daemon | 71034 | Waiting on empty queue |
NULL |
| 8 | Manish | localhost:53496 | business | Query | 0 | starting |show processlist|
+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+
2 rows in set (0.00 sec)
As seen from the above output, the db currently in use is ‘business’. and its id is 8. To stop the
query the command call can be used with the given id that is in process list. The syntax for that
is as follows −
call mysql.rds_kill(valueOfGivenIdInProcesslist);

Now, the above syntax is applied to the query and valueOfGivenIdInProcesslist is put as 8. This
is shown below −
mysql> CALL mysql.rds_kill(8);
After executing the above query, the following output is obtained −
ERROR 2013 (HY000): Lost connection to MySQL server during query

This happens as the above query stops running. The use command is used to check if it has
stopped or not. The syntax for that is as follows −
use yourDatabaseName;
The above syntax is applied to the mydatabase name ‘business’ in the system. The query is as
follows −
mysql> use business;

After executing the above query, the following output is obtained −
No connection. Trying to reconnect...
Connection id: 10
Current database: *** NONE ***



Database changed
mysql>
So, it is clear that the query has stopped because the message is coming “Trying to
reconnect...” in MySQL. And it is also showing that the current database is “none”. After some
time the connection with the database is resumed.
Convert min Heap to max Heap in C++

In this tutorial, we will be discussing a program to convert min heap to max heap.
For this we will be provided with the array representation of the min heap. Our task is to convert that given min heap to max heap in O(n) time complexity.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//converting a given subtree into a heap
void convert_arrayheap(int arr[], int i, int n){
   int l = 2*i + 1;
   int r = 2*i + 2;
   int largest = i;
   if (l < n && arr[l] > arr[i])
      largest = l;
   if (r < n && arr[r] > arr[largest])
      largest = r;
   if (largest != i){
      swap(arr[i], arr[largest]);
      convert_arrayheap(arr, largest, n);
   }
}
//finally building the max heap
void convert_maxheap(int arr[], int n){
   //heapify all the node elements
   for (int i = (n-2)/2; i >= 0; --i)
   convert_arrayheap(arr, i, n);
}
//printing the array
void printArray(int* arr, int size){
   for (int i = 0; i < size; ++i)
   printf("%d ", arr[i]);
}
int main(){
   int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   printf("Min Heap array : ");
   printArray(arr, n);
   convert_maxheap(arr, n);
   printf("\nMax Heap array : ");
   printArray(arr, n);
   return 0;
}
Min Heap array : 3 5 9 6 8 20 10 12 18 9
Max Heap array : 20 18 10 12 9 9 3 5 6 8
Filter the records of current day, month and year in MySQL?

Let’s say you have a table with UserLoginTime column wherein we have stored some values for sample. This is the login time of users and we want to filter all these records on the basis of current day, month and year i.e. the current date. We will be
Let us now create the table we discussed above
mysql> create table userLoginInformation
   - > (
   - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserName varchar(20),
   - > UserLoginTime datetime
   - > );
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('John','2016-02-12');
Query OK, 1 row affected (0.18 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Carol','2019-01-31');
Query OK, 1 row affected (0.16 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Bob','2019-02-19');
Query OK, 1 row affected (0.12 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Sam','2018-02-19');
Query OK, 1 row affected (0.16 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Larry','2017-04-18');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from userLoginInformation;
The following is the output
+--------+----------+---------------------+
| UserId | UserName | UserLoginTime       |
+--------+----------+---------------------+
|      1 | John     | 2016-02-12 00:00:00 |
|      2 | Carol    | 2019-01-31 00:00:00 |
|      3 | Bob      | 2019-02-19 00:00:00 |
|      4 | Sam      | 2018-02-19 00:00:00 |
|      5 | Larry    | 2017-04-18 00:00:00 |
+--------+----------+---------------------+
5 rows in set (0.00 sec)
Now, we will filter records on the basis of current date using the YEAR() and now(). Here, we are using now() to get the current date
mysql> select *from userLoginInformation where YEAR(UserLoginTime)=YEAR(now());
The following is the output
+--------+----------+---------------------+
| UserId | UserName | UserLoginTime       |
+--------+----------+---------------------+
|      2 | Carol    | 2019-01-31 00:00:00 |
|      3 | Bob      | 2019-02-19 00:00:00 |
+--------+----------+---------------------+
2 rows in set (0.00 sec)
PySpark – Extracting single value from DataFrame

17 Jun, 2021
In this article, we are going to extract a single value from the pyspark dataframe columns. To do this we will use the first() and head() functions.
Single value means only one value, we can extract this value based on the column name
Syntax: 
dataframe.first()[‘column name’]
Dataframe.head()[‘Index’]
Where,
dataframe is the input dataframe and column name is the specific column
Index is the row and columns.
So we are going to create the dataframe using the nested list.
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  data data =[["1","sravan","vignan"],       ["2","ojaswi","vvit"],       ["3","rohith","vvit"],       ["4","sridevi","vignan"],       ["1","sravan","vignan"],        ["5","gnanesh","iit"]]  # specify column namescolumns=['student ID','student NAME','college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns)  print("Actual data in dataframe")# show dataframedataframe.show()
Output:
Actual data in dataframe
+----------+------------+-------+
|student ID|student NAME|college|
+----------+------------+-------+
|         1|      sravan| vignan|
|         2|      ojaswi|   vvit|
|         3|      rohith|   vvit|
|         4|     sridevi| vignan|
|         1|      sravan| vignan|
|         5|     gnanesh|    iit|
+----------+------------+-------+
Example 1: Python program to extract a single value from a particular column using first().
Python3
# extract single value based on# column in the dataframedataframe.first()['student ID']
Output:
'1'
Example 2: Extract a single value using head().
Python3
# extract single value based# on column in the dataframedataframe.head()[0]
Output:
'1'
Example 3: Extract a single value using head().
Python3
# extract single value based# on column in the dataframedataframe.head()[2]
Output:
'vignan'
Picked
Python-Pyspark
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
Python OOPs Concepts
Iterate over a list in Python
How do I get the index of an item in Tkinter.Listbox?

We use the Tkinter Listbox widget to create a list of items. Each item in the listbox has some indexes that are assigned to them sequentially in vertical order.
Let us suppose that we want to get the index of a clicked item in the listbox. Then, we have to first create a button that will capture the current selection of the items using list.curselection() method and then, we will print the index using the get() method.
# Import the required libraries
from tkinter import *

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

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

# Create a Listbox widget
lb = Listbox(win, width=100, height=10, font=('Times 13'), selectbackground="black")
lb.pack()

# Define a function to edit the listbox ite
def save():
   for item in lb.curselection():
      print("You have selected " + str(item+1))

# Add items in the Listbox
lb.insert("end", "A", "B", "C", "D", "E", "F")

# Add a Button To Edit and Delete the Listbox Item
Button(win, text="Save", command=save).pack()

win.mainloop()
If we run the above code, it will display a window containing a list of alphabets (A-F).
Select an item from the list and click the "Save" button to get the index of the selected item printed on the console.
You have selected 3
Convert CSV to Pandas Dataframe

02 Dec, 2020
In this article, we will discuss how to convert CSV to Pandas Dataframe, this operation can be performed using pandas.read_csv reads a comma-separated values (csv) file into DataFrame.
Example 1: In the below program we are going to convert nba.csv into a data frame and then display it.
Python
# import pandas module import pandas as pd     # making dataframe df = pd.read_csv("nba.csv")    # output the dataframeprint(df)
Output:
Example 2: Here is another example to convert a CSV dataset into pandas data frame. 
Python
# import pandas module import pandas as pd     # making dataframe df = pd.read_csv("nba.csv")    # output the dataframeprint(df)
Output:
Python pandas-io
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Stack.Count Property in C#

04 Feb, 2019
This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to Count. Retrieving the value of this property is an O(1) operation.
Syntax:
public virtual int Count { get; }
Return Value: It returns the number of elements contained in the Stack having type System.Int32.
Below programs illustrate the use of above-discussed property:
Example 1:
// C# code illustrate the// Stack.Count Propertyusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Inserting the elements into the Stack        myStack.Push("Chandigarh");        myStack.Push("Delhi");        myStack.Push("Noida");        myStack.Push("Himachal");        myStack.Push("Punjab");        myStack.Push("Jammu");          // Displaying the count of elements        // contained in the Stack        Console.Write("Total number of elements"+                         " in the Stack are : ");          Console.WriteLine(myStack.Count);    }}
Total number of elements in the Stack are : 6

Example 2:
// C# code illustrate the// Stack.Count Propertyusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Displaying the count of elements        // contained in the Stack        Console.Write("Total number of elements"+                         " in the Stack are : ");          // The function should return 0        // as the Stack is empty and it        // doesn't contain any element        Console.WriteLine(myStack.Count);    }}
Total number of elements in the Stack are : 0

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.count?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Multiple inheritance using interfaces
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
How to set default value to NULL in MySQL?

Use DEFAULT keyword in MySQL to set default value to NULL. Let us first create a −
mysql> create table DemoTable1440
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20) DEFAULT NULL,
   -> StudentAge int DEFAULT NULL
   -> );
Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command. For values left blank, the default gets inserted −
mysql> insert into DemoTable1440(StudentName,StudentAge) values('Chris',21);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1440 values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1440(StudentName) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1440(StudentAge) values(24);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select −
mysql> select * from DemoTable1440;
This will produce the following output −
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | Chris       |         21 |
|         2 | NULL        |       NULL |
|         3 | David       |       NULL |
|         4 | NULL        |         24 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)
Matplotlib.axes.Axes.margins() in Python

09 Jul, 2021
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. 
The Axes.margins() function in axes module of matplotlib library is used to set or retrieve autoscaling margins. 
Syntax: Axes.margins(self, *margins, x=None, y=None, tight=True)Parameters: This method accepts the following parameters.  
*margins: This parameter is used to specify both margins of the x-axis and y-axis limits.
x, y: These parameter is used to specific margin values for the x-axis and y-axis, respectively.
tight : This parameter is passed to autoscale_view(), which is executed after a margin is changed.
Return value: The following values are returned by this method.  
xmargin
ymargin
 
Below examples illustrate the matplotlib.axes.Axes.margins() function in matplotlib.axes:Example 1:  
Python3
# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button, RadioButtons fig, (ax, ax1) = plt.subplots(1, 2)plt.subplots_adjust(bottom = 0.25)t = np.arange(0.0, 1.0, 0.001)a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t)ax.plot(t, s, lw = 2, color = 'green') ax1.plot(t, s, lw = 2, color = 'green')ax1.margins(0.5) ax.set_title("Without margin() Function")ax1.set_title("With margin value = 0") fig.suptitle('matplotlib.axes.Axes.margins() function \Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:  
Example 2:  
Python3
# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt t = np.arange(0.0, 3.0, 0.01)t1 = np.exp(-t) * np.cos(2 * np.pi * t) fig, [ax1, ax2, ax3] = plt.subplots(nrows = 3)ax1.plot(t, t1, color ="green")ax1.text(1.1, 0.65, 'Original window') ax2.margins(2, 2)ax2.plot(t, t1, color ="green")ax2.text(0, 2.0, 'Zoomed out') ax3.margins(x = 0, y =-0.25)ax3.plot(t, t1, color ="green")ax3.text(1.2, 0.35, 'Zoomed in') fig.suptitle('matplotlib.axes.Axes.margins() function\ Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:  
 
sagartomar9927
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change font style using drop-down list in JavaScript ? - GeeksforGeeks

03 Jun, 2020
To change or set a font style for certain text, the fontFamily CSS property needs to be changed. The fontFamily property sets or returns a list of font-family names for text in an element.
Syntax:
object.style.fontFamily = "font"
To change the font style by option dropdown: The font values can be passed in option tags using option value.
Syntax:
<option value="value">
The value attribute specifies the value to be sent when a form is submitted. So after the value to be sent is selected, we set the fontFamily property for the text in the element to the selected value as specified in the above syntax. In the javascript function, here changeFontStyle(), the fontFamily property value is set to the font value of the option selected. By default, it is set to Times New Roman.
Example:
<!DOCTYPE html><html>  <head>    <title>        Change Font Style by Option        Dropdown Javascript    </title></head>  <body style="text-align:center;">      <div id="output-text">        <h1 style="color:green;">            GeeksForGeeks        </h1>    </div>      <select id="input-font" class="input"        onchange="changeFontStyle (this);">          <option value="Times New Roman"             selected="selected">            Times New Roman        </option>        <option value="Arial">Arial</option>        <option value="fantasy">Fantasy</option>        <option value="cursive">cursive</option>    </select>      <script>        var changeFontStyle = function (font) {            document.getElementById(                "output-text").style.fontFamily                        = font.value;        }    </script></body>  </html>
Output:
Before selecting any option (Initial value – Times New Roman):
After selecting an option in dropdown:
After selecting another option in dropdown:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Difference between == and === operator in JavaScript - GeeksforGeeks

31 Jan, 2022
The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison.But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false.
Example 1:
<script>    // In R.H.S. string "9" is converted into    // number 9, hence returns true.    document.write(9 == "9");           // used for next line    document.write('<br>')       // Here no type conversion takes place,    // hence returns false    document.write(9 === "9"); </script>
Output:
true
false

Example 2:
<script>    // Here L.H.S. is a string literal whereas    // R.H.S. is a string object,    // due to type conversion of string object into     // a string literal, it returns true.    document.write("GeeksforGeeks" == new String("GeeksforGeeks"));      // used for next line    document.write('<br>')      // No type conversion takes place    document.write("GeeksforGeeks" === new String("GeeksforGeeks"));  </script>
Output:
true
false

Example 3:
<script>    // Here number 1 is converted into true(boolean type)   // as in javascript true is referred as 1 and false is   // referred as 0, hence it returns true.   document.write(true == '1');     // used for next line   document.write('<br>')      // No type conversion so it returns false       document.write(true === '1');  </script>
Output:
true
false

In general “===” operator is recommended since it never does type conversion we are doing an exact comparison thus it always produces correct results.
saraswatgaurang
javascript-basics
JavaScript-Misc
javascript-operators
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Node.js | fs.writeFileSync() Method
Set the value of an input field in JavaScript
How to read a local text file using JavaScript?
How to Use the JavaScript Fetch API to Get Data?
Form validation using HTML and JavaScript
Altering a database view in SAP HANA

You can alter the view, then we can use the Alter View command to alter the view.
Alter view View_EmpInfo  as Select Emp_Details.Id, Emp_Details.EmplName,
EmpProj.Projname from Emp_Details inner join EmpProjInfo
on Emp_Details.Id=EmpProjInfo.Id;
We have applied ALTER command to update an existing view with name- View_EmpInfo which is applying Inner Join on two tables on Id column to create a database view.
PHP - Function opendir()

resource opendir ( string $path [, resource $context] );

It opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
path(Required)
The directory path that is to be opened
context(Optional)
Specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream.
It returns a directory handle resource on success, or FALSE on failure.
Following is the usage of this function −
<?php
   $dir = opendir("/var/www/images");
   while (($file = readdir($dir)) !== false) {
      echo "filename: " . $file . "<br />";
   }
   closedir($dir);
?> 
This will produce the following result −
filename: .
filename: ..
filename: logo.gif
filename: mohd.gif


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
bool Keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. bool is a keyword that is used to declare a variable which can store Boolean values true or false. It is an alias of System.Boolean.
Bool Keyword occupies 1 byte (8 bits) in the memory. There are only two possible values of bool i.e. true or false.
Syntax:
bool variable_name = value;
Example:
Input: true

Output: answer: False
        Size of a byte variable: 1

Input: false

Output: Type of answer: System.Boolean
        answer: True
        Size of a bool variable: 1

Example 1:
// C# program for bool keywordusing System;using System.Text;       class GFG    {        static void Main(string[] args)        {             // bool variable declaration            bool answer = false;               // to print value            Console.WriteLine("answer: " + answer);              // to print size of a bool             Console.WriteLine("Size of a bool variable: " + sizeof(bool));           }    }
Output:
answer: False
Size of a bool variable: 1

Example 2:
// C# program for bool keywordusing System;using System.Text;  namespace geeks {  class GFG {      static void Main(string[] args)    {        // bool variable declaration        bool answer = true;          // to print type of variable        Console.WriteLine("Type of answer: " + answer.GetType());          // to print value        Console.WriteLine("answer: " + answer);          // to print size of a bool        Console.WriteLine("Size of a bool variable: " + sizeof(bool));          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of answer: System.Boolean
answer: True
Size of a bool variable: 1

CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
The build() method in Java Stream.Builder

The build() method in Stream.Builder class is used to build the stream. It returns the built stream.
The syntax is as follows:
Stream<T>l build()
Import the following package for the Stream.Builder class in Java:
import java.util.stream.Stream;
Declare a Stream.Builder:
Stream.Builder<String> builder = Stream.builder();
Add some elements in the stream:
builder.add("One");
builder.add("Two");
builder.add("Three");
Now, use the build() method:
Stream<String> str = builder.build();
The following is an example displaying how to implement build() method of Stream.Builder in Java:
 Live Demo
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream.Builder<String> builder = Stream.builder();
      builder.add("One");
      builder.add("Two");
      builder.add("Three");
      builder.add("Four");
      builder.add("Five");
      builder.add("Six");
      builder.add("Seven");
      builder.add("Eight");
      Stream<String> str = builder.build();
      str.forEach(System.out::println);
   }
}
One
Two
Three
Four
Five
Six
Seven
Eigh