code-rag-bench/online-tutorials huggingface dataset:
Search record with a specific value in MySQL using LIKE or REGEXP?

Let us first create a table −
mysql> create table DemoTable651 (Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,Value varchar(100));
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable651(Value) values('Title');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable651(Value) values('course');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable651(Value) values('subject');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable651;
This will produce the following output −
+----+---------+
| Id | Value   |
+----+---------+
|  1 | Title   |
|  2 | course  |
|  3 | subject |
+----+---------+
3 rows in set (0.00 sec)
Following is the query to search a specific value using LIKE −
mysql> select *from DemoTable651 where Value LIKE 'course';
This will produce the following output −
+----+--------+
| Id | Value  |
+----+--------+
|  2 | course |
+----+--------+
1 row in set (0.00 sec)
Following is the query to search a specific value using REGEXP −
mysql> select *from DemoTable651 where Value REGEXP 'course';
This will produce the following output −
+----+--------+
| Id | Value  |
+----+--------+
| 2  | course |
+----+--------+
1 row in set (0.00 sec)
How to retrieve Azure VMs using PowerShell?

To retrieve the azure VMs using PowerShell, we can use Get-AzVM commands but before that make sure you logged in using Azure Credentials in the console. When you type this command, you will get the list of all VMs in the specified subscription.
To check which all properties are supported you can use the
Get-AzVM | gm -MemberType Properties
You can select different properties from there using the Select-Object command (Alias: Select). To retrieve the VMs from the specific ResourceGroup, use the below command.
Get-AzVM -ResourceGroupName AUTOMATIONTESTRG2
If your VM is in a different subscription then you need to switch the subscription and need to retrieve the VM list.
Groovy - While Statement

The syntax of the while statement is shown below −
while(condition) { 
   statement #1 
   statement #2 
   ... 
}

The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The process is repeated starting from the evaluation of the condition in the while statement. This loop continues until the condition evaluates to false. When the condition becomes false, the loop terminates. The program logic then continues with the statement immediately following the while statement. The following diagram shows the diagrammatic explanation of this loop.
Following is an example of a while loop statement −
class Example {
   static void main(String[] args) {
      int count = 0;
		
      while(count<5) {
         println(count);
         count++;
      }
   }
}
In the above example, we are first initializing the value of a count integer variable to 0. Then our condition in the while loop is that we are evaluating the condition of the expression to be that count should be less than 5. Till the value of count is less than 5, we will print the value of count and then increment the value of count. The output of the above code would be −
0 
1 
2 
3 
4


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to check the memory used by a program in Java?


For a long-running java code, which makes heavy use of dynamic memory, we may end up with Out-Of-Memory errors due to a memory shortage of the heap space.
In the below program, we can test the free java heap space used by a program. If the heap space is used more than 90 percent, then the garbage collector is explicitly called. The System.gc() call is blocking the calling thread until the garbage collector has completed. Therefore, this code can be executed in a separate thread.
public class GCTest {
   public void runGC() {
      Runtime runtime = Runtime.getRuntime();
      long memoryMax = runtime.maxMemory();
      long memoryUsed = runtime.totalMemory() - runtime.freeMemory();
      double memoryUsedPercent = (memoryUsed * 100.0) / memoryMax;
      System.out.println("memoryUsedPercent: " + memoryUsedPercent);
      if (memoryUsedPercent > 90.0)
         System.gc();
   }
   public static void main(String args[]) {
      GCTest test = new GCTest();
         test.runGC();
   }
}
memoryUsedPercent: 0.07187129404943532
How to display JavaScript variable value in alert box?

To display JavaScript variable value in an alert box, try to run the following code −
Live Demo
<html>
   <head>
      <script>
         function display() {
            var a = "Simple";
            var b = "Learning";
            alert(a +" Easy "+ b);
         }
      </script>
   </head>
   <body>
      <input type="button" value="Click me!" onClick="display();">
   </body>
</html>
MySQL query to select records beginning from a specific id

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | David |
| 3  | Carol |
| 4  | Bob   |
| 5  | Mike  |
| 6  | Chris |
+----+-------+
6 rows in set (0.00 sec)
Following is the query to select records beginning from a specific id.
mysql> select *from DemoTable where Id>=2 order by Id DESC;
+----+-------+
| Id | Name  |
+----+-------+
| 6  | Chris |
| 5  | Mike  |
| 4  | Bob   |
| 3  | Carol |
| 2  | David |
+----+-------+
5 rows in set (0.00 sec)
What are the ways of submitting a form in Selenium with python?

There are multiple ways of submitting a form in Selenium. One of the methods is to directly use the click() method on the form submitting button. The next approach is to use the submit() method on the form page.
Using the submit() method.This method shall simply submit the form after the required data is entered on the form page.
Using the submit() method.
This method shall simply submit the form after the required data is entered on the form page.
Syntax −
driver.find_element_by_xpath("//input[class ='gsc-search']").submit()
Using the click() method.This method shall click on the submit button of the form after the required data is entered on the form page.
Using the click() method.
This method shall click on the submit button of the form after the required data is entered on the form page.
Syntax −
driver.find_element_by_xpath("//button[id ='value']").click()
Code Implementation with submit() method.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# submit the text contents
driver.find_element_by_id("gsc-i-id1").submit()
#to close the browser
driver.close()
Code Implementation with click() method for form submission.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# identifying the button then using click() method
driver.find_element_by_xpath("//button[contains(@class,'gsc-search')]") .click()
#to close the browser
driver.close()
File Handling through C++ Classes

In this tutorial, we will be discussing a program to understand File Handling through C++ classes.
The default functions used in file handling to interact with files can be defined by the user using classes. Below is the implementation of ifstream and ofstream functions.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
   //creating ofstream object ofstream fout;
   string line;
   fout.open("sample.txt");
   //initiating loop if file is opened
   while (fout) {
      getline(cin, line);
      if (line == "-1")
         break;
      fout << line << endl;
   }
   fout.close();
   ifstream fin;
   fin.open("sample.txt");
   while (fin) {
      getline(fin, line);
      cout << line << endl;
   }
   fin.close();
   return 0;
}
SAP ABAP - Nested Loop

The DO and WHILE statements can be tested as well as combined with other loop forms. Each nested loop will have it’s own SY-INDEX created and monitored by the system.
The syntax for nested DO loop is −
DO [n TIMES]. 
<statement block n>. 
   DO [m TIMES]. 
   <statement block m>. 
   ENDDO. 
ENDDO.

REPORT YS_SEP_15.
  
Data: a1 type I, b1 type I.
  
a1 = 0.  
b1 = 0.
  
Do 2 times.
  
a1 = a1 + 1.
  
Write: /'Outer', a1.
  
Do 10 times.  
b1 = b1 + 1.
  
Write: /'Inner', b1.
  
ENDDo. 
ENDDo
The above code produces the following output −
Outer   1 
Inner   1 
Inner   2 
Inner   3 
Inner   4 
Inner   5 
Inner   6 
Inner   7 
Inner   8 
Inner   9 
Inner  10 
Outer   2 
Inner  11 
Inner  12 
Inner  13 
Inner  14 
Inner  15 
Inner  16 
Inner  17 
Inner  18 
Inner  19 
Inner  20

In this example, the outer DO loop is processed twice and the inner DO loop is processed 10 times, each time the outer DO loop is processed. So in this case, the inner loop is processed 20 times.

    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to select one item at a time from JCheckBox in Java?

A JCheckBox can extend JToggleButton and it can be a small box that is either checked or unchecked.
When we click on a JCheckBox, it changes from checked to unchecked or vice versa automatically.
A JCheckBox can generate an ActionListener or an ItemListener whenever the checkbox is changed.
An isSelected() method is used to test if a checkbox is checked or not.
By default, we can select all the checkbox items at a time, if we want to select only one item at a time by using ButtonGroup class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxGroupTest extends JFrame {
   private ButtonGroup checkBoxGroup;
   private JCheckBox jcb1, jcb2, jcb3;
   private JPanel panel;
   public JCheckBoxGroupTest() {
      super("JCheckBoxGroup Test");
      panel = new JPanel(new GridLayout(3,0));
      jcb1 = new JCheckBox("India", true);
      jcb2 = new JCheckBox("England", false);
      jcb3 = new JCheckBox("Australia", false);
      checkBoxGroup = new ButtonGroup();
      //add CheckBoxes to ButtonGroup
      checkBoxGroup.add(jcb1);
      checkBoxGroup.add(jcb2);
      checkBoxGroup.add(jcb3);
      panel.add(jcb1);
      panel.add(jcb2);
      panel.add(jcb3);
      add(panel);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JCheckBoxGroupTest();
   }
}
How to empty an array in Java

Use List.clear() method to empty an array.
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      list.add("C");
      list.add("D");
      list.add("E");
      list.add("F");
      list.add("G");
      list.add("H");
      System.out.println("Original List " + list);
      list.clear();
      System.out.println("Cleared List " + list);
   }
}
Original List [A, B, C, D, E, F, G, H]
Cleared List []
Creating a table look-a-like using Tkinter

A table contains data items in the form of rows and columns. Consider a case of having a table GUI in an application where we can manipulate the data using other Python libraries such as Numpy, Pandas, Matplotlib, etc. Tkinter provides TreeView widget which enable the user to draw the table and insert the data into it. The TreeView widget can be constructed by defining the Treeview(parent, column, **options) constructor.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window
win.geometry("700x350")
s = ttk.Style()
s.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("c1", "c2", "c3"), show='headings', height=5)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="FName")
tree.column("# 3", anchor=CENTER)
tree.heading("# 3", text="LName")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('1', 'Joe', 'Nash'))
tree.insert('', 'end', text="2", values=('2', 'Emily', 'Mackmohan'))
tree.insert('', 'end', text="3", values=('3', 'Estilla', 'Roffe'))
tree.insert('', 'end', text="4", values=('4', 'Percy', 'Andrews'))
tree.insert('', 'end', text="5", values=('5', 'Stephan', 'Heyward'))

tree.pack()

win.mainloop()
Running the above code will display a window that contains a table with some rows and columns in it.
Ionic - Cordova Integration

Cordova offers ngCordova, which is set of wrappers specifically designed to work with AngularJS.
When you the start Ionic app, you will notice that it is using bower. It can be used for managing ngCordova plugins. If you have bower installed skip this step, if you do not have it, then you can install it in the command prompt window.
C:\Users\Username\Desktop\MyApp> npm install -g bower

Now we need to install ngCordova. Open your app in the command prompt window. The following example is used for the app that is located on the desktop and is named MyApp.
C:\Users\Username\Desktop\MyApp> bower install ngCordova

Next, we need to include ngCordova to our app. Open index.html file and add the following scripts. It is important to add these scripts before cordova.js and after ionic scripts.
<script src = "lib/ngCordova/dist/ng-cordova.js"></script>

Now, we need to inject ngCordova as angular dependency. Open your app.js file and add the ngCordova to angular module. If you have used one of the Ionic template apps, you will notice that there is injected ionic, controllers and services. In that case, you will just add ngCordova at the end of the array.
angular.module('myApp', ['ngCordova'])

You can always check the plugins that are already installed by typing the following command. 
C:\Users\Username\Desktop\MyApp> cordova plugins ls

Now, we can use the Cordova plugins. You can check all the other plugins here.

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Repeating a String for Specific Number of Times in Golang - GeeksforGeeks

26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.You are allowed to repeat a string of for a specific number of times with the help of the Repeat() Function. This method returns a new string which contains a repeated string and it is defined under the strings package. So, you have to import strings package in your program for accessing Repeat function.
Syntax:
func Repeat(str string, count int) string
Here, str represents the string that you want to repeat and the count value represents how many times you want to repeat str string.
Example 1:
// Go program to illustrate how to repeat// a string to a specific number of timespackage main  import (    "fmt"    "strings")  // Main methodfunc main() {      // Creating and initializing a string    // Using shorthand declaration    str1 := "Welcome to GeeksforGeeks !.."    str2 := "This is the tutorial of Go"      // Repeating the given strings    // Using Repeat function    res1 := strings.Repeat(str1, 4)    res2 := str2 + strings.Repeat("Language..", 2)      // Display the results    fmt.Println("Result 1: ", res1)    fmt.Println("Result 2:", res2)}
Output:
Result 1: Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Result 2: This is the tutorial of GoLanguage..Language..
Note: This method will panics if the value of the count is negative or the result of (len(str) * count) overflows.
Example:
// Go program to illustrate how to repeat// a string to a specific number of timespackage main  import (    "fmt"    "strings")  // Main methodfunc main() {      // Creating and initializing a string    // Using shorthand declaration    str1 := "Welcome to GeeksforGeeks !.."    str2 := "This is the tutorial of Go"      // Repeating the given strings    // Using Repeat function    res1 := strings.Repeat(str1, 4)      // If we use a negative value in the count    // then this method will panic because negative    // values are not allowed to count    res2 := str2 + strings.Repeat("Language..", -2)      // Display the results    fmt.Println("Result 1: ", res1)    fmt.Println("Result 2:", res2)}
Output:
panic: strings: negative Repeat count
goroutine 1 [running]:strings.Repeat(0x104b22, 0xa, 0xfffffffe, 0x0, 0x450000, 0x70)/usr/local/go/src/strings/strings.go:533 +0x540main.main()/tmp/sandbox829702598/prog.go:25 +0x80
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Split a String in Golang?
Arrays in Go
How to compare times in Golang?
Golang Maps
How to Trim a String in Golang?
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Channel in Golang
How to Parse JSON in Golang?
Loops in Go Language
Overloading unary operators + in C++

The operator keyword declares a function specifying what operator-symbol means that once applied to instances of a class. this gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
The unary operators operate on a single operand and following are the examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in +obj, !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.
Following example explain how plus(+) operator can be overloaded for prefix usage −
#include <iostream>
using namespace std;

class Distance {
   private:
   int feet;             // 0 to infinite
   int inches;           // 0 to 12

   public:
   // Constructor
   Distance(int f, int i) {
      feet = f;
      inches = i;
   }

   // method to display distance
   void display() {
      cout << "F: " << feet << " I:" << inches <<endl;
   }

   // overloaded plus(+) operator
   Distance operator+() {
      if(inches == 11) {
         inches = 0;
         feet = feet + 1;
      } else {
         inches = inches + 1;
      }
      return Distance(feet, inches);
   }
};

int main() {
   Distance D1(3, 4), D2(1, 11);

   +D1;
   D1.display();

   +D2;
   D2.display();

   return 0;
}
This will give the output −
F: 3 I:5
F: 2 I:0
Bool to int conversion in C++

Here we will see how to convert bool to int equivalent in C++. Bool is a datatype in C++, and we can use true or false keyword for it. If we want to convert bool to int, we can use typecasting. Always true value will be 1, and false value will be 0.
#include <iostream>
using namespace std;
main() {
   bool my_bool;
   my_bool = true;
   cout << "The int equivalent of my_bool is: " << int(my_bool) << endl;
   my_bool = false;
   cout << "The int equivalent of my_bool is: " << int(my_bool);
}
The int equivalent of my_bool is: 1
The int equivalent of my_bool is: 0
Continuous Tree in C++

A Continuous Tree is defined as a tree with any path from root node to leaf node has value or
weight of nodes such that the absolute difference between the parent node and all of its direct
children nodes is always 1.
If we pick any node on the path from root to leaf, then
|weight of node-weight of left child node|=|weight of left child node-weight of node| = 1, this
holds true for right child as well
|weight of node-weight of right child node|=|weight lof right child node-weight of node| = 1
Diagram
Let us understand with examples.
The tree below is continuous as absolute difference between parent nodes and their child is
always 1.
The tree below is not qualified for being a Continuous Tree.
If root is NULL, return 1
If root is NULL, return 1
If it is a leaf node, return 1 as the tree has been Continuous that's why the leaf node
reached.
If it is a leaf node, return 1 as the tree has been Continuous that's why the leaf node
reached.
If the left subtree is empty check continuity of the current node with the right child (
calculate absolute difference of weights) and continue for the right subtree recursively.
If the left subtree is empty check continuity of the current node with the right child (
calculate absolute difference of weights) and continue for the right subtree recursively.
If the right subtree is empty check continuity of the current node with the left child (
calculate absolute difference of weights) and continue for the left subtree recursively.
If the right subtree is empty check continuity of the current node with the left child (
calculate absolute difference of weights) and continue for the left subtree recursively.
Else calculate absolute difference with weights of left and right child and continue for left
and right subtrees, recursively.
Else calculate absolute difference with weights of left and right child and continue for left
and right subtrees, recursively.
// Function to check tree is continuous or not
struct btreeNode{
   int data;
   btreeNode* left, * right;
};
int isContinuous(btreeNode *root){
   // if node is NULL return 1, exit condition
   if (root == NULL)
      return 1;
   //if leaf node is reached then tree must be continous during this path
   if (root->left == NULL && root->right == NULL)
      return 1;
   // if no left child
   if (root->left == NULL)
      return (abs(root->data - root->right->data) == 1) && isContinuous(root->right);
   // if no right child
   if (root->right == NULL)
      return (abs(root->data - root->left->data) == 1) && isContinuous(root->left);
      // calculate absoute difference
      return abs(root->data - root->left->data)==1 && abs(root->data - root->right->data)==1 &&
   isContinuous(root->left) && isContinuous(root->right);
}
Scala this keyword - GeeksforGeeks

17 Jun, 2021
Keywords are the words in a language that are used to represent some predefined actions or some internal process. We use the this keyword when we want to introduce the current object for a class. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using this keyword. this keyword is also used with auxiliary constructors.
Let’s understand this keyword with some examples.
Example #1: 
Scala
// Scala program to illustrate this keywordclass Addition(i:Int){    // using this keyword    def this(i:Int, j:Int)    {        this(i)        println(i + " + " + j + " = " + { i + j })    }} // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        var add = new Addition(15, 12)    }     }
Output: 
15 + 12 = 27
In above example, a class addition defined which consist one parameter and in that class we created a method using this keyword with two parameters i and j. In this method a primary constructor is also invoked (i.e this(i)).   Example #2: 
Scala
// Scala program to illustrate this keywordclass geeks{    var Lname: String = ""    var Articles = 0         // Using this keyword    def this(Lname:String, Articles:Int )    {        this()        this.Lname = Lname        this.Articles = Articles             }    def show()    {        println("Language name " + Lname +                " published article " + Articles )    }} // Creating objectobject GFG{    // Main method    def main(args: Array[String])    {        var GeeksForGeeks = new geeks( "Scala", 105)        GeeksForGeeks.show()    }}
Output: 
Language name Scala published article 105
As we can see, in above example, an auxiliary constructor defined with this keyword and a primary constructor called using this keyword. instance variables (i.e Lname, Articles)is also referred using dot(.) operator. 
akshaysingh98088
Scala-Keyword
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | map() method
Scala | flatMap Method
Scala | reduce() Function
Scala List filter() method with example
String concatenation in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
How to get the first element of List in Scala
Scala List contains() method with example
What is a materialized view in DBMS?

A materialized view is a view whose contents are computed and stored. Materialized view is also a logical virtual table, but in this case the result of the query is stored in the table or the disk. The performance of the materialized view is better than normal view since the data is stored in the disk.
It's also called indexed views since the table created after the query is indexed and can be accessed faster and efficiently.
Consider the view given below −
Create view branchloan(branch-name, total-loan) as select branch-name , sum(amount) from loan groupby branch-name;
Materializing the above view would be especially useful if the total loan amount is required frequently.
It saves the effort of finding multiple tuples and adding up their amounts.
The task of keeping a materialized view up-to-date with the underlying data is known as materialised view maintenance. It can be maintained by recompilation on every update.
A better option is to use incremental view maintenance. It changes to database relations are used to compute changes to materialized view, which is then updated.
View maintenance can be done by following −
Manually defining triggers on insert, delete, and update of each relation in the view definition.
Manually defining triggers on insert, delete, and update of each relation in the view definition.
Manually written code to update the view whenever database relations are updated.
Manually written code to update the view whenever database relations are updated.
Supported directly by the database.
Supported directly by the database.
The changes like insert and delete operations to a relation or expressions are referred to as its differential, the set of tuples inserted to and deleted from r are denoted ir and dr.
To simplify our description, let’s consider inserts and deletes, we replace updates to a tuple by deletion of the tuple followed by insertion of the updated tuple.
We describe how to compute the change to the result of each relational operation, given changes to its inputs. We then outline how to handle relational algebra expressions.
The materialized view selection decision must be made on the basis of the system workload. Indices are just like materialized views, the problem of index selection is closely related to that of materialized view selection, although it is simpler.
Some database systems provide tools to help the database administrator with index and materialized view selection.
Tk - Check Button Widget

Tk check button is used to create multiple selectable items in the form of check boxes. The syntax for check button widget is shown below −
checkbutton checkbuttonName options

The options available for the check button widget are listed below in the following table −
-font fontDescriptor
Used to set font for widget.
-height number
Used to set height for widget.
-command action
Sets the command action for button.
-text text
Sets the text for widget.
-width number
Sets the width for widget.
-variable variableName
Sets the variable for widget.
A simple Tk example for check button is shown below −
#!/usr/bin/wish

grid [label .myLabel1  -text "Range 20-30 not selected" -textvariable myLabelValue1 ] 
grid [checkbutton .chk1 -text "Range 20-30" -variable occupied1 -command {if {$occupied1 } {
   set myLabelValue1 {Range 20-30 selected}
} else {
   set myLabelValue1 {Range 20-30 not selected}
} }]
grid [label .myLabel2  -text "Range 30+ not selected" -textvariable myLabelValue2 ] 
grid [checkbutton .chk2 -text "Range 20-30" -variable occupied2 -command {if {$occupied2 } {
   set myLabelValue2 {Range 30+ selected}
} else {
   set myLabelValue2 {Range 30+ not selected}
} }]
When we run the above program, we will get the following output −
When we click the check button1 and check button2, we will get the following output −
 Print
 Add Notes
 Bookmark this page
PyQtGraph – Removing Item from Plot Window

24 Sep, 2020
In this article we will see how we can remove item from the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. By default the plot window is empty we have to add some graph or image to show in the window these graph/image/structure is the item. It can be added with the help of addItem method.
We can create a plot window with the help of command given below
# creating a pyqtgraph plot window
window = pg.plot()

In order to do this we use addItem method with the plot window object
Syntax : window.removeItem(item)
Argument : It takes PyQtGraph widget object as argument
Return : It returns None
Below is the implementation
# importing pyqtgraph as pgimport pyqtgraph as pg  # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui  # importing numpy as npimport numpy as np  import time  # creating a pyqtgraph plot windowwindow = pg.plot()  # titletitle = "GeeksforGeeks PyQtGraph"      # setting window titlewindow.setWindowTitle(title)  # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2]  # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g')  # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1)    # removing item from the plot windowwindow.removeItem(bargraph1)      # main methodif __name__ == '__main__':          # importing system    import sys          # Start Qt event loop unless running in interactive mode or using     if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):        QtGui.QApplication.instance().exec_()         
Output :
Python-gui
Python-PyQtGraph
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
nmcli command in Linux with Examples

08 Oct, 2021
nmcli is a command-line tool which is used for controlling NetworkManager. nmcli command can also be used to display network device status, create, edit, activate/deactivate, and delete network connections. 
Typical Uses:  
Scripts: Instead of manually managing the network connections it utilize NetworkMaager via nmcli.
Servers, headless machine and terminals: Can be used to control NetworkManager with no GUI and control system-wide connections.
Syntax:  
nmcli [OPTIONS] OBJECT { COMMAND | help }
Where the OBJECT can be any one of the following:  
nm: NetworkManager’s status.
connection/cn: NetworkManager’s connection.
d[evice]: devices managed by NetworkManager.
Example 1: To check the device status using nmcli command. 
We can see that the output is shown in various columns that include the device name, its type and connection status. The output might vary with different machines. 
Example 2: To check active connection on the device. 
In the above output, we can see that there is one connection which is active. The number of connection, it’s UUID(universally unique identifier) and type might vary from machine to machine. 
Example 3: To list all the available device. 
Options: 
-t, –terse: This option is used to terse the output i.e. when we want the output to be very brief and in very few words. It is suitable for script processing. Example: 
Example: 
nmcli -t device list
             Input: 
           Output: 
-p, –pretty: This option prints the output in an organized format which is convenient and easily readable to humans. Example: Input:  
Example: 
Input: 
 
          Output: 
-m, –mode {tabular|multiline}: Used to switch the output mode between tabular and multiline. If the option is not used, nmcli will print the output in tabular form by default.
-f, –fields {fields1, fields2.... |all|common}: This option is used to specify the fields to print as output. Where the field is the column that we want to print as output. all is used when we want all the value field to be displayed. Example 1: To print device list with field DHCP4.  
Example 1: To print device list with field DHCP4. 
 
          Example 2: To print device list with field GENERAL.  
-e, –escape {yes | no}: This option is used to escape columns separators(“:”, “\”) in values.
-v, –version: Show the version information version. Example: 
Example: 
-h[elp]: Print help related information. Example: 
Example: 
gulshankumarar231
linux-command
Linux-networking-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl bless Function

This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.
Following is the simple syntax for this function −
bless REF, CLASSNAME

bless REF

This function returns the reference to an object blessed into CLASSNAME.
Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class −
#!/usr/bin/perl

package Person;
sub new {
   my $class = shift;
   my $self = {
      _firstName => shift,
      _lastName  => shift,
      _ssn       => shift,
   };
   # Print all the values just for clarification.
   print "First Name is $self->{_firstName}\n";
   print "Last Name is $self->{_lastName}\n";
   print "SSN is $self->{_ssn}\n";
   bless $self, $class;
Python PIL | Image.point() method

17 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.point() Maps this image through a lookup table or function.
Syntax: Maps this image through a lookup table or function.
Parameters:
lut – A lookup table, containing 256 (or 65336 if self.mode==”I” and mode == “L”) values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image.
mode – Output mode (default is same as input). In the current version, this can only be used if the source image has mode “L” or “P”, and the output has mode “1” or the source image mode is “I” and the output mode is “L”.
Returns: An Image object.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\home.png")   # using point functionthreshold = 191  im = im.point(lambda p: p >value threshold and 255)im.show()
Output:
Another Example:Here changing threshold value.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\home.png")   # using point functionthreshold = 120  im = im.point(lambda p: p > threshold and 255)im.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
Gate IT 2005 - GeeksforGeeks

29 Sep, 2021
(A ⊕ B) ⊕ C

By Solving, We get
= (A ⊕ B)′ C + (A ⊕ B) C′

The above expression can be written as:
= (A ⊙ B) C + (A ⊕ B) C′

Now,

= (AB + A′B′) C + (A ⊕ B) C′

= ABC + A′B′C + AB′C′ + A′BC′	     [As: X + X = X]				     
			         [So, A′B′C + A′B′C = A′B′C]
= ABC + (A′B′C + A′B′C) + AB′C′ + A′BC′

This can be written as:

= ABC + A′ (B ⊕ C) + B′ (A ⊕ C)


Then, for each pair from LSB to MSB (add 1 bit at a time):
00 = 0, 01 = +1, 10 = -1, 11 = 0
= 2's complement of (00111001) = 11000110+1 = 11000111
= append 0 into LSB of (11000111) = 110001110
Now Booth's code (add 1 bit at a time, from LSB to MSB):
= 11, 10, 00, 00, 01, 11, 11, 10 = 0 -1 0 0 1 0 0 -1
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Relational plots in Seaborn – Part I

21 Jul, 2021
Relational plots are used for visualizing the statistical relationship between the data points. Visualization is necessary because it allows the human to see trends and patterns in the data. The process of understanding how the variables in the dataset relate each other and their relationships are termed as Statistical analysis. 
Seaborn, unlike to matplotlib, also provides some default datasets. In this article, we will be using a default dataset named ‘tips’. This dataset gives information about people who had food at some restaurant and whether they left tip for waiters or not, their gender and whether they do smoke or not, and more.
Let us have a look to the dataset.
python3
# importing the libraryimport seaborn as sns # reading the datasetdata = sns.load_dataset('tips') # printing first five entriesprint(data.head())
Output :
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4
To draw the relational plots seaborn provides three functions. These are:
relplot()
scatterplot()
lineplot()
This function provides us the access to some other different axes-level functions which shows the relationships between two variables with semantic mappings of subsets.
Syntax : 
seaborn.relplot(x=None, y=None, data=None, **kwargs) 
Parameters : 
 
 
Example 1: Visualizing the most basic plot to show all the data points in tips dataset.
 
Python3
# importing the libraryimport seaborn as sns # selecting stylesns.set(style ="ticks") # reading the datasettips = sns.load_dataset('tips') # plotting a simple visualization of data pointssns.relplot(x ="total_bill", y ="tip", data = tips)
Output :
Example 2: Grouping data points on the basis of category, here as time.
Python3
# importing the libraryimport seaborn as sns # selecting stylesns.set(style ="ticks") # reading the datasettips = sns.load_dataset('tips') sns.relplot(x="total_bill",            y="tip",            hue="time",            data=tips)
Output :
Example 3: using time and sex for determining the facet of the grid.
Python3
# importing the libraryimport seaborn as sns # selecting stylesns.set(style ="ticks") # reading the datasettips = sns.load_dataset('tips') sns.relplot(x="total_bill",            y="tip",            hue="day",            col="time",            row="sex",            data=tips)
Output :
Example 4: using size attribute, we can see data points having different size.
Python3
# importing the libraryimport seaborn as sns # selecting stylesns.set(style ="ticks") # reading the datasettips = sns.load_dataset('tips') sns.relplot(x="total_bill",            y="tip",            hue="day",            size="size",            data=tips)
Output :
09amit
sumitgumber28
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.sync() method

14 Aug, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.sync() method in Python is used to force write of everything to disk. This method allows a process to flush all dirty buffers to disk.Difference between os.sync(), os.fsync(fd) and os.fdatasync(fd) method – os.sync() method force write of everything to disk where as os.fsync(fd) method force write of file associated with the specified file descriptor fd and os.fdatasync(fd) method is similar to os.fsync() method but it does not force update of file’s metadata.Note: This method is only available on Unix platforms.  
Syntax: os.sync()Parameter: No parameter is required.Return type: This method does not return any value.  
Code: Use of os.sync() method  
Python3
# Python program to explain os.sync() method   # importing os moduleimport os  # File path 1path1 = 'file.txt' # File path 2path2 = 'file2.txt' # File path 3path3 = 'file3.txt' # Open the files and get# the file descriptors# associated with them# using os.open() methodfd1 = os.open(path1, os.O_RDWR)fd2 = os.open(path2, os.O_RDWR)fd3 = os.open(path3, os.O_RDWR)  # Write a bytestringstr = b"GeeksforGeeks"os.write(fd1, str)os.write(fd2, str)os.write(fd3, str)  # Sync. all buffers to disk# i.e force write everything# to disk using os.sync() methodos.sync()print("Force write everything committed successfully") # Close the file descriptorsos.close(fd1)os.close(fd2)os.close(fd3)  # os.sync() method# will flush all buffers# to disk.# it may take a significant# length of time
Force write of everything committed successfully
 
Reference: https://docs.python.org/3/library/os.html#os.sync 
varshagumber28
python-os-module
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
PostgreSQL – GRANT

17 Aug, 2021
In PostgreSQL, the GRANT statement is used to grant privileges to a role to alter on database objects like tables, views, functions, etc.
The following shows the syntax of the GRANT statement:
Syntax:
GRANT privilege_list | ALL 
ON  table_name
TO  role_name;
Let’s analyze the above syntax:
Some elements of the privilege_list are SELECT, INSERT, UPDATE, DELETE, TRUNCATE, etc. The ALL option to grant all available privileges to a role.
It is required to mention the name of the table after the ON keyword.
The next step is to mention the name of the role to be granted the privileges.
Example:
Create a role called ‘Anshul’ that can login to the PostgreSQL database server as shown below:
create role anshul
login 
password 'geeks12345';
Now create a table called candidate as below:
create table Players (
    player_id int generated always as identity,
    first_name varchar(100) not null,
    last_name varchar(100) not null,
    email varchar(255) not null unique,
    phone varchar(25) not null,
    primary key(player_id)
);
Now, use the role ‘Anshul’ to log in to the PostgreSQL database server separately and try to select data from the players table from the Anshul’s session:
SELECT * FROM players;
Here PostgreSQL will raise an error as shown below:
ERROR:  permission denied for table players
To grant the SELECT privilege on the players table to the role anshul, the GRANT statement can be executed in the postgres‘ session as shown below:
GRANT SELECT 
ON players
TO anshul;
Now, execute the SELECT statement from the anshul’s session:
SELECT * FROM players;
Seventh, execute the following INSERT statement;
INSERT INTO players(first_name, last_name, email, phone)
VALUES('raju', 'kumar', 'raju.kumar@geeforgeeks.org', '408-111-2222');
PostgreSQL issued the following error because anshul does not have the INSERT privilege on the players table:
ERROR:  permission denied for table players
Now, grant INSERT, UPDATE, and DELETE privileges on the candidates table to the role anshul:
GRANT INSERT, UPDATE, DELETE
ON players
TO anshul;
Ninth, execute the INSERT statement again from the anshul’s session:
INSERT INTO players(first_name, last_name, email, phone)
VALUES('raju', 'kumar', 'raju.kumar@gmail.com', '408-111-2222');
Now, anshul can insert data into the players table. In addition to that the Anshul role can update or delete data from the table.
Output:
simranarora5sos
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function