code-rag-bench/online-tutorials huggingface dataset:
How to update the image of a Tkinter Label widget?

We have used Label widget to group all the widgets in the application. A Label widget takes text and images in the constructor that sets the label with the position in the top-left corner of the window. However, to change or update the image associated with the Label, we can use a callable method where we provide the information of other images.
In the following example, we will create a button to update the Label image.
#Import the required library
from tkinter import*
from PIL import Image, ImageTk

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

#Define geometry of the window
win.geometry("750x600")
win.title("Gallery")

#Define a Function to change to Image
def change_img():
   img2=ImageTk.PhotoImage(Image.open("tutorialspoint.png"))
   label.configure(image=img2)
   label.image=img2

#Convert To PhotoImage
img1= ImageTk.PhotoImage(Image.open("logo.png"))

#Create a Label widget
label= Label(win,image= img1)
label.pack()

#Create a Button to handle the update Image event
button= Button(win, text= "Change", font= ('Helvetica 13 bold'),
command= change_img)
button.pack(pady=15)
win.bind("<Return>", change_img)
win.mainloop()
Running the example code will display a window with a Label Image and a button that helps to change the label image.
Now, just click the "Change" button to update the Label Image.
Python Tkinter – How to position a topLevel() widget relative to the root window?

In Tkinter, the toplevel widget is used to create a popup modal window. The popup window created by the toplevel window works similar to the default window of the tkinter application. It can have widgets such as text widget, button widget, canvas widget, frame, etc.
The size and position of the toplevel window can be decided by making it flexible throughout the screen. In the toplevel window, all the widgets are always placed on top of the other windows.
You can use root.winfo_x() and root.winfo_y() to get the position of the root window. Then, you can use the geometry method to position a toplevel widget relative to the root window. Making the toplevel widget relative to the root window prevents the overlapping of the two windows and separates them. Let's take an example to demonstrate how it works.
# 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("700x300")
win.title("Root Window")

# Create a toplevel window
top = Toplevel(win)
top.geometry("400x200")

# Create a Label in the toplevel widget
Label(top, text= "This is a Toplevel window", font="Calibri, 12").pack()
x = win.winfo_x()
y = win.winfo_y()
top.geometry("+%d+%d" %(x+200,y+200))

# Keep the toplevel window in front of the root window
top.wm_transient(win)

top.mainloop()
Running the above code will display a toplevel window apart from the main window.
Display MySQL Database, Table, and Column Information

The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes.It provides a command-line interface for several SQL SHOW statements.
The mysqlshow utility can be invoked as shown below −
shell> mysqlshow [options] [db_name [tbl_name [col_name]]]
Here,
If no database is provided, a list of database names are displayed.
If no database is provided, a list of database names are displayed.
If no table is given, all matching tables in the database are displayed.
If no table is given, all matching tables in the database are displayed.
If no column is provided, all matching columns and column types in the table are shown.
If no column is provided, all matching columns and column types in the table are shown.
The output displays the names of only those databases, tables, or columns for which the user has certain privileges.
The output displays the names of only those databases, tables, or columns for which the user has certain privileges.
mysqlshow supports the below options. These can be specified on the command line or in the [mysqlshow] and [client] groups of an option file.
--bind-address=ip_address
If a computer has multiple network interfaces, this option can be used to select which interface has to be used to connect to the MySQL server.
--character-sets-dir=dir_name
It is the directory where character sets are installed.
--compress, -C
It compresses all information that is sent between the client and the server if possible.
--count
It will show the number of rows per table. This can be slow for non-MyISAM tables.
--port=port_num, -P port_num
It is for TCP/IP connections, it tells about the port number to use.
--print-defaults
It prints the program name and all options that it gets from option files.
--user=user_name, -u user_name
It is the user name of the MySQL account that is used to connect to the server.
--verbose, -v
It is the verbose mode. It prints more information about what the program does. This option can be used multiple times to increase the amount of information.
--version, -V
It displays the version information and exits.
p5.js | value() Function

21 Jun, 2021
The value() function is an inbuilt function which is used to set or return the value of the element.This function requires p5.dom library. So add the following line in the head section of the index.html file.  
javascript
<script language="javascript"    type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:  
value()
or  
value( value )
Parameters: This function accepts single parameter value which holds the value in number or string format.Return Value: This function returns the value of the element.Below examples illustrate the value() function in p5.js:Example 1: This example uses value() function to display the value as output.  
javascript
// Gets the valuevar input_val; function setup() {         // Canvas size 400*400    createCanvas(400, 200);         // Set background color    background('green');         // Create an input element with its value    input_val = createInput('Welcome to GeeksforGeeks');        // Set the position of div element    input_val.position(30, 80);       // Set width of input field    input_val.style('width', '250px');       // Set font-size of input text    input_val.style('font-size', '20px');       // Set margin property    input_val.style('margin-left', '50px');} function mousePressed() {         // Display the input value    print(input_val.value());}
Output:  
Example 2: This example uses value() function to set the value of an element.  
javascript
// Set the input valuevar input_val; function setup() {         // Canvas size 400*400    createCanvas(400, 200);         // Set background color    background('green');         // Create an input element with its value    input_val = createInput('Welcome to GeeksforGeeks');        // Set the position of div element    input_val.position(30, 80);       // Set width of input field    input_val.style('width', '250px');       // Set font-size of input text    input_val.style('font-size', '20px');       // Set margin property    input_val.style('margin-left', '50px');} function mousePressed() {         // Change input value    input_val.value('A computer science portal');}
Output:  
Before Click on the Element:  
After Click on the Element:  
 
abhishek0719kadiyan
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
How to Remove Time from Date/Timestamp in Excel?

20 May, 2021
Timestamp stores a combined Date and Time value. In this article, we will look at how we can create Timestamp and remove Time from Date in Excel. 
To do so follow the steps below:
Step 1: Formatting data to create a timestamp.
Select the cell, right-click on it choose Format Cells...
Step 2: Then in the Formal Cells box select Custom in Category and in the type select dd-mm-yyyy hh:mm, and then click Ok.
Then, we will enter our date with time in the cell.
Step 1: Highlight the cells to remove time from date.
Step 2: Then right-click on it and choose Format Cells...
Step 3:-Then in the Format Cells box select Date in Category and select *14-03-2012 in Type, and then click Ok.
After that time is removed from the date.
Step 1: Highlight the cells to remove time from date.
Step 2: Then, click to Home on the Ribbon. In the Editing group, click Find & Select.
Step 3: In the resulting menu click Replace...
Step 4: Then in Find and Replace box enter the space bar and * in Find what box and leave a blank in Replace with box, then click Replace All.
After that time is removed from the date.
Step 1: Highlight the cells to remove time from date.
Step 2: Press Alt + F11 then a Microsoft  Visual Basic for Applications window will be displayed and then click Insert.
Step 3: Then in the resulting menu click Module.
Step 4: In the Module write the following code.
Step 5: Then, click on the red marked button as shown below to run the code.
Step 6: In the KutoolsforExcel box select the range from which we want to remove time and then click Ok.
After that time is removed from the date.
Step 1: Visit on the given link below to install Kutools for Excel
https://www.extendoffice.com/download/kutools-for-excel.html
Step 2: Then, click to Kutools on the Ribbon. In the Formula group, click Formula Helper.
Step 3: In the resulting menu click Formula Helper...
Step 4:- In the Formulas Helper box select Date in Formula Type then choose Remove time from data in choose a formula box then select the range from which we want to remove date in Date time box and then click Ok.
After that time is removed from the date.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Macros in Excel
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
Fix Error 1136: Column count doesn't match value count at row 1?

You may get tis value, if you are missing the value for auto_increment column. The error is as follows −
mysql> insert into DemoTable1353 values('Chris',23);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
You need to provide the value for auto_increment or leave it to automatic generation.
Let us see an example and create a table −
mysql> create table DemoTable1353
    -> (
    -> Id int NOT NULL AUTO_INCREMENT,
    -> Name varchar(20),
    -> Age int,
    -> PRIMARY KEY(Id)
    -> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command. We haven’t inserted auto increment value and it will generate on its own −
mysql> insert into DemoTable1353(Name,Age) values('Chris',23);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable1353(Name,Age) values('David',21);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1353(Name,Age) values('Bob',24);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1353(Name,Age) values('John',47);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1353;
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Chris |   23 |
|  2 | David |   21 |
|  3 | Bob   |   24 |
|  4 | John  |   47 |
+----+-------+------+
4 rows in set (0.00 sec)
Program to convert IP address to hexadecimal

02 Dec, 2021
Given an IP Address and task is to change the IP address equivalent the hexadecimal value.Examples:
Input  : 127.0.0.1
Output : 0x7f000001

Input  : 172.31.0.2
Output : 0xac1f0002


Explanationusing the Library function to convert the IP address to convert into the hexadecimal value we use ” arpa/inet.h “ header file. The inet_addr() function shall convert the string in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address.
// C++ program for IP to// hexadecimal conversion#include <arpa/inet.h>#include <iostream>#include <string.h>using namespace std;  // function for reverse hexadecimal numbervoid reverse(char* str){    // l for swap with index 2    int l = 2;    int r = strlen(str) - 2;      // swap with in two-2 pair    while (l < r) {        swap(str[l++], str[r++]);        swap(str[l++], str[r]);        r = r - 3;    }}  // function to conversion and print// the hexadecimal valuevoid ipToHexa(int addr){    char str[15];      // convert integer to string for reverse    sprintf(str, "0x%08x", addr);      // reverse for get actual hexadecimal    // number without reverse it will    // print 0x0100007f for 127.0.0.1    reverse(str);      // print string    cout << str << "\n";}  // Driver codeint main(){    // The inet_addr() function  convert  string    // in to standard IPv4 dotted decimal notation    int addr = inet_addr("127.0.0.1");      ipToHexa(addr);      return 0;}
Output:-
0x7f000001

gulshankumarar231
C-String
C++ Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Different ways to print elements of vector
Dynamic _Cast in C++
How to convert a Vector to Set in C++
Why it is important to write "using namespace std" in C++ program?
string::npos in C++ with Examples
Maximum value of long long int in C++
list pop_back() function in C++ STL

13 Jun, 2022
The list::pop_back() is a built-in function in C++ STL which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list. Syntax:
list_name.pop_back();
Parameters: The function does not accept any parameter. Return Value: This function does not returns anything. Below program illustrate the list::pop_back() function in C++ STL: 
CPP
// CPP program to illustrate the// list::pop_back() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList;  // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40);  // Initial List: cout << "Initial List: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++)  cout << *itr << " ";  // removing an element from the end of List // using pop_back demoList.pop_back();  // List after removing element from end cout << "\n\nList after removing an element from end: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++)  cout << *itr << " ";  return 0;}
Initial List: 10 20 30 40 

List after removing an element from end: 10 20 30
Time Complexity: O(1)
Auxiliary Space: O(1)
utkarshgupta110092
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
Sorting a vector in C++
How to add a paragraph in HTML?

Use the HTML <p> tag to add a paragraph in HTML. You can try to run the following code to implement <p> tag in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML p Tag</title>
   </head>
   <body>
      <p>This is demo text.</p>
   </body>
</html>
What is $(window).load() method in jQuery?

The code which gets included inside $( window ).on( "load", function() { ... }) runs only once the entire page is ready (not only DOM).
Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.
You can try to run the following code to learn how to use $(window).load() method in jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("img").load(function(){
     alert("Image successfully loaded.");
   });
});
</script>
</head>
<body>

<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor" width="280" height="236">

<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>

</body>
</html>
Differences between abstract class and concrete class in Java

In Java, abstraction is achieved using Abstract classes and interfaces. An abstract class contains abstract methods which a child class. Following are the important differences between abstract class and a concrete class.
public class JavaTester {
   public static void main(String args[]) {
      Cat lion = new Lion();
      lion.eat();
   }
}
abstract class Cat {
   abstract public void eat();
}
class Lion extends Cat{
   public void eat(){
      System.out.println("Lion eats");
   }
}
Lion eats
Tryit Editor v3.7

Tryit: The universal (*) selector
Roll Out Animation Effect with CSS

To create a rollout animation effect with CSS, you can try to run the following code −
<html>
   <head>
      <style>
         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }

         @-webkit-keyframes rollOut {
            0% {
               opacity: 1;
               -webkit-transform: translateX(0px) rotate(0deg);
            }
            100% {
               opacity: 0;
               -webkit-transform: translateX(100%) rotate(120deg);
            }
         }

         @keyframes rollOut {
            0% {
               opacity: 1;
               transform: translateX(0px) rotate(0deg);
            }
            100% {
               opacity: 0;
               transform: translateX(100%) rotate(120deg);
            }
         }

         .rollOut {
            -webkit-animation-name: rollOut;
            animation-name: rollOut;
         }
      <style>

   </head>
   <body>

      <div id = "animated-example" class = "animated rollOut"></div>
      <button onclick = "myFunction()">Reload page</button>

      <script>
         function myFunction() {
            location.reload();
         }
      </script>
   </body>
</html>
What is morphological gradient in image processing?

Erosion and dilation are the two basic morphological operations. As the name implies, morphological operations are the set of operations that process images
according to their shapes.
During dilation operation additional pixels are added to an image boundary and, during erosion operation, additional pixels are removed from image boundaries, The total number of pixels added during the dilation process depends on the dimensions of the structuring element used.
Morphological Gradient is the operation that is equal to the difference between dilation and erosion of an image. Each pixel value in the resulting image indicates the contrast intensity in the nearby pixels. This is used in edge detection, segmentation and to find the outline of an object.
Following Java example generates a window containing the Morphological gradient of the given image −
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class MorphologicalGradient extends Application {
   public void start(Stage stage) throws IOException {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading image data
      String file ="D:\\Images\\morph_input1.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating destination matrix
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      //Preparing the kernel matrix object
      Mat kernel = Mat.ones(5,5, CvType.CV_32F);
      //Applying dilate on the Image
      Imgproc.morphologyEx(src, dst, Imgproc.MORPH_GRADIENT, kernel);
      //Converting matrix to JavaFX writable image
      Image img = HighGui.toBufferedImage(dst);
      WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
      //Setting the image view
      ImageView imageView = new ImageView(writableImage);
      imageView.setX(10);
      imageView.setY(10);
      imageView.setFitWidth(575);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 400);
      stage.setTitle("Morphological Gradient");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}
Java break statement with switch

Following is an example
Live Demo
public class Test {

   public static void main(String args[]) {
      // char grade = args[0].charAt(0);
      char grade = 'C';

      switch(grade) {
         case 'A' :
            System.out.println("Excellent!");
            break;
         case 'B' :
         case 'C' :
            System.out.println("Well done");
            break;
         case 'D' :
            System.out.println("You passed");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}
Compile and run the above program using various command line arguments. This will produce the following result −
Well done
Your grade is C
Binary Search Tree insert with Parent Pointer in C++

We can insert new node into the BST in recursive manner. In that case we return the address of the root of each subtree. Here we will see another approach, where parent pointer will need to be maintained. Parent pointer will be helpful to find ancestor of a node etc.
The idea is to store the address of the left and right subtrees, we set parent pointers of the returned pointers after recursive call. This confirms that all parent pointers are set during insertion. The parent of root is set to null.
insert(node, key) −
begin
   if node is null, then create a new node and return
      if the key is less than the key of node, then
         create a new node with key
         add the new node with the left pointer or node
      else if key is greater or equal to the key of node, then
            create a new node with key
         add the new node at the right pointer of the node
      end if
   return node
end
#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *left, *right, *parent;
};
struct Node *getNode(int item) {
   Node *temp = new Node;
   temp->data = item;
   temp->left = temp->right = temp->parent = NULL;
   return temp;
}
void inorderTraverse(struct Node *root) {
   if (root != NULL) {
      inorderTraverse(root->left);
      cout << root->data << " ";
      if (root->parent == NULL)
         cout << "NULL" << endl;
      else
         cout << root->parent->data << endl;
      inorderTraverse(root->right);
   }
}
struct Node* insert(struct Node* node, int key) {
   if (node == NULL) return getNode(key);
   if (key < node->data) { //to the left subtree
      Node *left_child = insert(node->left, key);
      node->left = left_child;
      left_child->parent = node;
   }
   else if (key > node->data) { // to the right subtree
      Node *right_child = insert(node->right, key);
      node->right = right_child;
      right_child->parent = node;
   }
   return node;
}
int main() {
   struct Node *root = NULL;
   root = insert(root, 100);
   insert(root, 60);
   insert(root, 40);
   insert(root, 80);
   insert(root, 140);
   insert(root, 120);
   insert(root, 160);
   inorderTraverse(root);
}
40 60
60 100
80 60
100 NULL
120 140
140 100
160 140
How to check if an input is an integer using C/C++?

Here we will see how to check whether a given input is integer string or a normal string. The integer string will hold all characters that are in range 0 – 9. The solution is very simple, we will simply go through each characters one by one, and check whether it is numeric or not. If it is numeric, then point to the next, otherwise return false value.
#include <iostream>
using namespace std;
bool isNumeric(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isdigit(str[i]) == false)
      return false; //when one non numeric value is found, return false
   return true;
}
int main() {
   string str;
   cout << "Enter a string: ";
   cin >> str;
   if (isNumeric(str))
      cout << "This is a Number" << endl;
   else
      cout << "This is not a number";
}
Enter a string: 5687
This is a Number
Enter a string: 584asS
This is not a number
How to connect to my MongoDB table by command line?

In order to connect to my table by command line, you need to use db command
db.yourCollectionName.find();
Let’s say we have a database “sample” with some collections. First check the current database
> use sample;
switched to db sample
> db;
Sample
Now we have reached the database sample. The database “sample” is having the following collections:
> show collections;
This will produce the following output
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation
Here is the correct way of connecting to a table i.e. collection. You need to use db command. Following is the query
> db.userInformation.find();
This will produce the following output
{ "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), "Name" : "John", "Age" : 30, "isStudent" : false, "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] }
Display MySQL table values using Java

For this, you can use the ResultSet concept. For connection, we will be using the MySQL JDBC Driver.
Let us create a table −
mysql> create table demo87
   -> (
   -> name varchar(20),
   -> age int
   -> )
   -> ;
Query OK, 0 rows affected (0.62
Insert some records into the table with the help of insert command −
mysql> insert into demo87 values('John',21);
Query OK, 1 row affected (0.15

mysql> insert into demo87 values('David',23);
Query OK, 1 row affected (0.12

mysql> insert into demo87 values('Bob',22);
Query OK, 1 row affected (0.16
Display records from the table using select statement −
mysql> select *from demo87;
This will produce the following output −
+-------+------+
| name  | age  |+-------+------+
| John  |   21 || David |   23 |
| Bob   |   22 |+-------+------+
3 rows in set (0.00 sec)
| name  | age  |
| John  |   21 |
| Bob   |   22 |
3 rows in set (0.00 sec)
Following is the Java code to display table values in MySQL −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

import com.mysql.jdbc.Statement;

public class TableValuesDemo {
   public static void main(String[] args) {
      Connection con = null;
      Statement statement = null;
      try {
         HashMap hm = new HashMap<>();
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
         statement = (Statement) con.createStatement();
         String sql;
         sql = "select *from demo87";
         ResultSet resultSet = statement.executeQuery(sql);
         while (resultSet.next()) {
         hm.put(resultSet.getString("name"), resultSet.getInt("age"));
      }
      System.out.println(hm);

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
This will produce the following output −
{Bob=22, John=21, David=23}
Following is the snapshot of sample output −
Get Random record from MongoDB?

To get a random record from MongoDB, you can use aggregate function. The syntax is as follows:
db.yourCollectionName.aggregate([{$sample:{size:1}}]);
To understand the above syntax, let us create a collection with some documents. The query to create collection is as follows:
>db.employeeInformation.insert({"EmployeeId":1,"EmployeeName":"Maxwell","EmployeeAge":26});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":2,"EmployeeName":"David","EmployeeAge":25});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":3,"EmployeeName":"Carol","EmployeeAge":24});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":4,"EmployeeName":"Bob","EmployeeAge":28});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":5,"EmployeeName":"Sam","EmployeeAge":27);
WriteResult({ "nInserted" : 1 })
Now you can display all documents from a collection with the help of find() method. The query is as follows:
> db.employeeInformation.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d3079734e98fc0a434ae5"),
   "EmployeeId" : 1,
   "EmployeeName" : "Maxwell",
   "EmployeeAge" : 26
}
{
   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
   "EmployeeId" : 2,
   "EmployeeName" : "David",
   "EmployeeAge" : 25
}
{
   "_id" : ObjectId("5c6d309d734e98fc0a434ae7"),
   "EmployeeId" : 3,
   "EmployeeName" : "Carol",
   "EmployeeAge" : 24
}
{
   "_id" : ObjectId("5c6d30ab734e98fc0a434ae8"),
   "EmployeeId" : 4,
   "EmployeeName" : "Bob",
   "EmployeeAge" : 28
}
{
   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
   "EmployeeId" : 5,
   "EmployeeName" : "Sam",
   "EmployeeAge" : 27
}
Here is the query to get random record:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
   "EmployeeId" : 5,
   "EmployeeName" : "Sam",
   "EmployeeAge" : 27
}
Let us get another random record using the same query:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
   "EmployeeId" : 2,
   "EmployeeName" : "David",
   "EmployeeAge" : 25
}
How to create a simple MySQL function?

You can create a function using create function command. The syntax is as follows −
delimiter //
DROP FUNCTION if exists yourFunctionName;
CREATE FUNCTION yourFunctionName(Parameter1,...N) returns type
BEGIN
# declaring variables;
# MySQL statementns
END //
delimiter ;
First, here we will create a table and add some records in the table. After that, a simple function will be created. The following is the query to create a table −
mysql> create table ViewDemo
   −> (
   −> Id int,
   −> Name varchar(200),
   −> Age int
   −> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into ViewDemo values(1,'John',23);
Query OK, 1 row affected (0.15 sec)

mysql> insert into ViewDemo values(2,'Sam',24);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from ViewDemo;
The following is the output −
+------+------+------+
| Id   | Name | Age  |
+------+------+------+
|    1 | John | 23   |
|    2 | Sam  | 24   |
+------+------+------+
2 rows in set (0.00 sec)
Now we will create a function that takes on integer parameters and returns strings. The purpose of this function is to search records with given id. If the given id matches with table id then it returns the name otherwise it will give an error message like not found.
The function is as follows −
mysql> SET GLOBAL log_bin_trust_function_creators = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> drop function if exists searchRecord;
   ->
   -> create function searchRecord(yourId int) returns char(100)
   -> begin
   -> declare Name1 char(100) default "No Name Found For This Id";
   -> select Name into Name1 from ViewDemo where Id =yourId;
   -> return Name1;
   -> end //
Query OK, 0 rows affected (0.21 sec)
Query OK, 0 rows affected (0.33 sec)
mysql> delimiter ;
Now to check the function is working with given id.
Case 1 − When the given id is present.
The query is as follows −
mysql> select searchRecord(2) as Found;
The following is the output −
+-------+
| Found |
+-------+
| Sam   |
+-------+
1 row in set (0.00 sec)
Case 2 − When the given id is not present. 
The query is as follows −
mysql> select searchRecord(100) as Found;
The following is the output displaing the record isn’t there −
+---------------------------+
| Found                     |
+---------------------------+
| No Name Found For This Id |
+---------------------------+
1 row in set (0.00 sec)
How do I pass options to the Selenium Chrome driver using Python?

We can pass options to the Selenium Chrome driver using Python. This can be with the help of the ChromeOptions and the DesiredCapabilities class. For the ChromeOptions, we have to create an object for that class.
Then we shall take the help of the add_argument method and pass the option we want to send to the browser as a parameter to the method. Finally, this information must be given to the web driver.
Code Implementation.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
#object of ChromeOptions
op = webdriver.ChromeOptions()
#add option
op.add_argument('--enable-extensions')
#pass option to webdriver object
driver = webdriver.Chrome(chrome_options=op)
We can also add capabilities with the help of DesiredCapabilities class.
Code Implementation.
#object of DesiredCapabilities
c = webdriver.DesiredCapabilities.Chrome.copy()

#set capability to True
c['acceptInsecureCerts'] = True
#pass capability to webdriver object
driver = webdriver.Chrome(desired_capabilities=c)
In this way, we can pass the Chrome options.
JUnit - Plug with Eclipse

To set up JUnit with eclipse, follow the steps given below.
Download a JUnit jar based on the operating system you have on your system.
Assume you have copied the above JAR file onto the folder C:\>JUnit.
Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10.jar in the libraries using the button Add External Jar.
We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\>eclipse\plugins directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the plugin folder of the Eclipse. Finally restart Eclipse.
Now your Eclipse is ready for the development of JUnit test cases.
Create a project TestJunit in Eclipse at any location. Then create a class MessageUtil to test in the project.
   
/*
* This class prints the given message on console.
*/

public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message;
   }
      
   // prints the message
   public String printMessage(){
      System.out.println(message);
      return message;
   }   
} 
Create a test class TestJunit in the project.
   
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestJunit {
	
   String message = "Hello World";	
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   public void testPrintMessage() {	  
      assertEquals(message,messageUtil.printMessage());
   }
}
Following should be the project structure −
Finally, right click the program and run as JUnit to verify the output of the program.
Verify the result.

    24 Lectures 
     2.5 hours 

 Nishita Bhatt

    56 Lectures 
     7.5 hours 

 Dinesh Varyani
 Print
 Add Notes
 Bookmark this page
Explain dependency injection in C#

A dependency is an object that another object depends on. Dependency Injection (or inversion) is basically providing the objects that an object needs, instead of having it construct the objects themselves. It is a useful technique that makes testing easier, as it allows you to mock the dependencies.
For example, if class A calls a method on class B, which in turn calls a method on class C, that means A depends on B and B depends on C. Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C.
In the example, below, class Runner has a dependency on the class Logger. Notice that in the class Runner creates an instance of Logger in the constructor. There are a few problems with this code.
This ties the logger class to Runner and we can't substitute it with other classes,
without modifying Runner.
This ties the logger class to Runner and we can't substitute it with other classes,
without modifying Runner.
If Logger has any dependencies, then Worker has to configure them before
instantiating Logger.
If Logger has any dependencies, then Worker has to configure them before
instantiating Logger.
Testing is harder. If Logger is a resource-intensive class, such as accessing the
network or file system, it will slow the testing down. We can't replace it easily.
Testing is harder. If Logger is a resource-intensive class, such as accessing the
network or file system, it will slow the testing down. We can't replace it easily.
using System;
class Program{
   static void Main(string[] args){
      var runner = new Runner();
      runner.Run();
   }
}
class Runner{
   private Logger _logger;
   public Runner(){
      _logger = new Logger();
   }
   public void Run(){
      // Do some work
      _logger.Log("Message to be logged");
   }
}
class Logger{
   public void Log(string message){
      Console.WriteLine(message);
   }
}
Using dependency injection, we modify the constructor of Runner to accept an interface ILogger, instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner's constructor. The benefit of this is that during testing, we can create a TestLogger class that implements ILogger and pass that to Runner's constructor.
 Live Demo
using System;
class Program{
   static void Main(string[] args){
      var logger = new Logger();
      var runner = new Runner(logger);
      runner.Run();
   }
}
class Runner{
   private ILogger _logger;
   public Runner(ILogger logger){
      _logger = logger;
   }
   public void Run(){
      // Do some work
      _logger.Log("Message to be logged");
   }
}
interface ILogger{
   void Log(string message);
}
class Logger : ILogger{
   public void Log(string message){
      Console.WriteLine(message);
   }
}
Message to be logged
How to find the 95% confidence interval for the slope of regression line in R?

The slope of the regression line is a very important part of regression analysis, by finding the slope we get an estimate of the value by which the dependent variable is expected to increase or decrease. But the confidence interval provides the range of the slope values that we expect 95% of the times when the sample size is same. To find the 95% confidence for the slope of regression line we can use confint function with regression model object.
Consider the below data frame −
set.seed(1)
x <-rnorm(20)
y <-rnorm(20,2.5)
df <-data.frame(x,y)
df
      x       y
1 -0.62645381 3.4189774
2 0.18364332 3.2821363
3 -0.83562861 2.5745650
4 1.59528080 0.5106483
5 0.32950777 3.1198257
6 -0.82046838 2.4438713
7 0.48742905 2.3442045
8 0.73832471 1.0292476
9 0.57578135 2.0218499
10 -0.30538839 2.9179416
11 1.51178117 3.8586796
12 0.38984324 2.3972123
13 -0.62124058 2.8876716
14 -2.21469989 2.4461950
15 1.12493092 1.1229404
16 -0.04493361 2.0850054
17 -0.01619026 2.1057100
18 0.94383621 2.4406866
19 0.82122120 3.6000254
20 0.59390132 3.2631757
Creating regression model to predict y from x −
RegressionModel <-lm(y~x,data=df)
summary(RegressionModel)
Call:
lm(formula = y ~ x, data = df)

Residuals:
Min 1Q Median 3Q Max
-1.69133 -0.43739 -0.07132 0.68033 1.63937

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.5331 0.1998 12.677 2.08e-10 ***
x -0.2075 0.2195 -0.946 0.357
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.8738 on 18 degrees of freedom
Multiple R-squared: 0.04732, Adjusted R-squared: -0.00561
F-statistic: 0.894 on 1 and 18 DF, p-value: 0.3569
Finding the 95% confidence interval for the slope of the regression line −
confint(RegressionModel,'x',level=0.95)
2.5 % 97.5 %
x -0.6687129 0.2536177
Lets’ have a look at another example:
BloodPressure <-c(165,170,190,195,220)
Weight <-c(50,75,64,60,62)
data <-data.frame(BloodPressure,Weight)
data
BloodPressure Weight
1 165 50
2 170 75
3 190 64
4 195 60
5 220 62
RegM <-lm(BloodPressure~Weight,data=data)
summary(RegM)
Call:
lm(formula = BloodPressure ~ Weight, data = data)
Residuals:
1 2 3 4 5
-21.783 -19.277 1.820 7.219 32.020
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 181.79551 88.73672 2.049 0.133
Weight 0.09975 1.41495 0.070 0.948
Residual standard error: 25.34 on 3 degrees of freedom
Multiple R-squared: 0.001654, Adjusted R-squared: -0.3311
F-statistic: 0.00497 on 1 and 3 DF, p-value: 0.9482
confint(RegM,'Weight',level=0.95)
2.5 % 97.5 %
Weight -4.403255 4.602756
2.5 % 97.5 %
Weight -4.403255 4.602756
How can we use MySQL TRIM() to remove the whitespaces from all the rows and update table?

Suppose if a table has many values having whitespaces in the columns of a table then it is wastage of space. We can use TRIM() function to remove whitespaces from all the rows and update the table too in a single query. Following the example from ‘Employee’, having whitespaces in all its rows will exhibit the concept −
mysql> Select * from Employee;
+------+----------------------+----------------------+----------------------+
| Id   | Name                 | Address              | Department           |
+------+----------------------+----------------------+----------------------+
| 100  | Raman                | Delhi                | IT                   |
| 101  | Mohan                | Haryana              | History              |
| 102  | Shyam                | Chandigarh           | ENGLISH              |
| 103  | Sukhjeet Singh       | Patiala              | Computer Engg.       |
| 104  | Bimal Roy            | Calcutta             | Computer Engg.       |                    
+------+----------------------+----------------------+----------------------+
5 rows in set (0.00 sec)
We can see from the above result set that Employee table is having so many whitespaces in its rows. It can be removed and updated with the following query −
mysql> Update Employee SET Id = TRIM(Id), Name = TRIM(Name), Address = TRIM(Address), DEPARTMENT = TRIM(Department);
Query OK, 5 rows affected (0.24 sec)
Rows matched: 5 Changed: 5 Warnings: 0

mysql> Select * from Employee;
+------+----------------+------------+----------------+
| Id   | Name           | Address    | Department     |
+------+----------------+------------+----------------+
| 100  | Raman          | Delhi      | IT             |
| 101  | Mohan          | Haryana    | History        |
| 102  | Shyam          | Chandigarh | ENGLISH        |
| 103  | Sukhjeet Singh | Patiala    | Computer Engg. |
| 104  | Bimal Roy      | Calcutta   | Computer Engg. |
+------+----------------+------------+----------------+
5 rows in set (0.00 sec)
We can see from the above result set that all the whitespaces have been removed and the table is updated.
C Program to sum the digits of a given number in single statement

In this section we will see how to find the sum of digits without writing multiple statements. In other
words, we will find the sum of digits in a single statement.
As we know that, to find the sum of digits we cut the last digit by taking the remainder after
dividing the number by 10, and then divide the number by 10 again and again until the number
becomes 0.
To do these task in a single statement the for loop can be used. As we know there are three
different sections in the for loop. In the initialization phase we are doing nothing in this case, then in
the condition checking phase are checking whether the number is greater than 0 or not. In the
increment decrement phase, we are doing multiple tasks. At first we are incrementing the sum by
taking the last digits of the number, and also reduce the number by dividing it by 10.
#include<stdio.h>
main() {
   int n, sum = 0;
   printf("Enter a number: "); //take the number from the user
   scanf("%d", &n);
   for(; n > 0; sum += n%10, n/= 10) {
   }
   printf("The sum of digits: %d", sum);
}
Enter a number: 457
The sum of digits: 16
PL/SQL - IF-THEN Statement

It is the simplest form of the IF control statement, frequently used in decision-making and changing the control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN  
   S; 
END IF; 

Where condition is a Boolean or relational condition and S is a simple or compound statement. Following is an example of the IF-THEN statement −
IF (a <= 20) THEN
   c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.
Let us try an example that will help you understand the concept −
DECLARE 
   a number(2) := 10; 
BEGIN 
   a:= 10; 
  -- check the boolean condition using if statement  
   IF( a < 20 ) THEN 
      -- if condition is true then print the following   
      dbms_output.put_line('a is less than 20 ' ); 
   END IF; 
   dbms_output.put_line('value of a is : ' || a); 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20 
value of a is : 10  

PL/SQL procedure successfully completed. 

Consider we have a table and few records in the table as we had created in PL/SQL Variable Types
DECLARE 
   c_id customers.id%type := 1; 
   c_sal  customers.salary%type; 
BEGIN 
   SELECT  salary  
   INTO  c_sal 
   FROM customers 
   WHERE id = c_id; 
   IF (c_sal <= 2000) THEN 
      UPDATE customers  
      SET salary =  salary + 1000 
         WHERE id = c_id; 
      dbms_output.put_line ('Salary updated'); 
   END IF; 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
Salary updated  

PL/SQL procedure successfully completed. 
 Print
 Add Notes
 Bookmark this page