code-rag-bench/online-tutorials huggingface dataset:
C++ Program to Create a Random Graph Using Random Edge Generation

In this program a random graph is generated for random vertices and edges. The time complexity of this program is O(v * e). Where v is the number of vertices and e is the number of edges.
Begin
   Develop a function GenRandomGraphs(), with ‘e’ as the
   number of edges and ‘v’ as the number of vertexes, in the argument list.
      Assign random values to the number of vertex and edges of the graph,
   using rand() function.
      Print the connections of each vertex, irrespective of the
      direction.
      Print “Isolated vertex” for the vertex having no degree.
End
#include<iostream>
#include<stdlib.h>
using namespace std;
void GenRandomGraphs(int NOEdge, int NOVertex)
{
   int i, j, edge[NOEdge][2], count;
   i = 0;
   //Assign random values to the number of vertex and edges
   of the graph, Using rand().
   while(i < NOEdge)
   {
      edge[i][0] = rand()%NOVertex+1;
      edge[i][1] = rand()%NOVertex+1;
      //Print the connections of each vertex, irrespective of
      the direction.
      if(edge[i][0] == edge[i][1])
         continue;
      else
      {
         for(j = 0; j < i; j++)
         {
            if((edge[i][0] == edge[j][0] &&
            edge[i][1] == edge[j][1]) || (edge[i][0] == edge[j][1] &&
            edge[i][1] == edge[j][0]))
            i--;
         }
      }i
      ++;
   }
   cout<<"\nThe generated random graph is: ";
   for(i = 0; i < NOVertex; i++)
   {
      count = 0;
      cout<<"\n\t"<<i+1<<"-> { ";
      for(j = 0; j < NOEdge; j++)
      {
         if(edge[j][0] == i+1)
         {
            cout<<edge[j][1]<<" ";
            count++;
         } else if(edge[j][1] == i+1)
         {
            cout<<edge[j][0]<<" ";
            count++;
         } else if(j== NOEdge-1 && count == 0)
         cout<<"Isolated Vertex!"; //Print “Isolated vertex” for the vertex having no degree.
      }
      cout<<" }";
   }
}
int main()
{
   int i, e, n;
   cout<<"Random graph generation: ";
   n= 7 + rand()%6;
   cout<<"\nThe graph has "<<n<<" vertices";
   e = rand()%((n*(n-1))/2);
   cout<<"\nand has "<<e<<" edges.";
   GenRandomGraphs(e, n);
}
Random graph generation:
The graph has 8 vertices
and has 18 edges.
The generated random graph is:
1-> { 5 4 2 }
2-> { 4 8 6 3 1 5 }
3-> { 5 4 7 2 }
4-> { 2 3 7 1 8 5 }
5-> { 3 1 7 4 2 8 }
6-> { 2 8 7 }
7-> { 4 3 5 6 }
8-> { 2 6 4 5 }
Find Maximum difference pair in Python

Data analysis can throw a variety of challenges. In this article we will take a list with numbers as its elements. Then we will find such pairs of elements in the list which has maximum difference in value between them.
The approach here is to first find out all possible combinations of elements and then subtract the second element from the first. Finally apply the nlargest function form heapq module to get those pairs where the difference is maximum.
 Live Demo
from itertools import combinations
from heapq import nlargest

listA = [21, 14, 30, 11, 17, 18]

# Given list
print("Given list : ",listA)

# using nlargest and combinations()
res = nlargest(2, combinations(listA, 2),
               key=lambda sub: abs(sub[0] - sub[1]))

# print result
print("Pairs with maximum difference are : ",res)

Running the above code gives us the following result −
Given list : [21, 14, 30, 11, 17, 18]
Pairs with maximum difference are : [(30, 11), (14, 30)]
Here we also take the same approach as above but we get one pair as a result because we apply the max function which gives us one pair as the result.
 Live Demo
from itertools import combinations

listA = [21, 14, 30, 11, 17, 18]

# Given list
print("Given list : ",listA)

# using combinations() and lambda
res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1]))

# print result
print("Pairs with maximum difference are : ",res)
Running the above code gives us the following result −
Given list : [21, 14, 30, 11, 17, 18]
Pairs with maximum difference are : (30, 11)
Clear a list in C#

Firstly, set a list −
List<int> myList = new List<int>();
myList.Add(45);
myList.Add(77);
Now, to clear the above list, use Clear() −
myList.Clear();
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> myList = new List<int>();
      myList.Add(45);
      myList.Add(77);
      Console.WriteLine("Elements: "+myList.Count);
      myList.Clear();
      Console.WriteLine("Elements after using clear: "+myList.Count);
   }
}
Elements: 2
Elements after using clear: 0
Arcade inbuilt functions to draw polygon in Python3 - GeeksforGeeks

11 Oct, 2020
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions.
Arcade has two inbuilt functions for drawing a polygon:
1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of the polygon. 
Syntax: arcade.draw_polygon_outline (point_list,  color,  line_width )
Parameters:
point_list: List of points making up the lines. Each point is in a list. So it is a list of lists.
color (Color): specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters.)
line_width:- Width of the line in pixels.
Example:
Python3
import arcade  # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, "Draw  a polygon for GfG ")  arcade.set_background_color(arcade.color.ORANGE)  # Start the render process.arcade.start_render()  point_list = ((30, 240),              (45, 240),              (60, 255),              (60, 285),              (45, 300),              (30, 300))arcade.draw_polygon_outline(point_list, arcade.color.SPANISH_VIOLET, 3)  arcade.finish_render()  arcade.run()
Output:
2. arcade.draw_polygon_filled( ): This inbuilt function of arcade is used to draw polygon filled with color. 
Syntax: arcade.draw_polygon_filled (point_list, color )
Parameters:
point_list- It is basically List of points where each point is in a list. So it is a list of lists.
Color – specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters. )
Example:
Python3
import arcade  # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, "Draw  a polygon for GfG ")  arcade.set_background_color(arcade.color.ORANGE)  # Start the render process.arcade.start_render()  point_list = ((150, 240),              (165, 240),              (180, 255),              (180, 285),              (165, 300),              (150, 300))arcade.draw_polygon_filled(point_list, arcade.color.SPANISH_VIOLET)  arcade.finish_render()  arcade.run()
Output:
Python-Arcade
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to get the title and full URL of a document in JavaScript?

Javascript HTML DOM has provided some basic methods to access and manipulate the HTML data. To find the title and URL of a document, javascript has provided document.title and document.URL respectively. Let's discuss them individually.
To get the title of a document javascript HTML DOM has provided document.title method. 
 In the following example, the title of the document is found out and displayed as shown in the output.
Live Demo
<html>
<head>
   <title>Tutorix</title>
</head>
<body>
<script>
   document.write("The title of the document is" +" "+ document.title);
</script>
</body>
</html>
Tutorix
To get the URL of a document javascript HTML DOM has provided document.URL method.
 In the following example, the URL of the document is found out and displayed in the output.
Live Demo
<html>
<body>
<script>
   document.write("The URL of the document is:" + " " +document.URL)
</script>
</body>
</html>
The URL of the document is: https://www.tutorialspoint.com/cg/assets/ovPEzF.php
Java Program for focal length of a spherical mirror

Following is the Java code for focal length of a spherical mirror −
 Live Demo
import java.util.*;
import java.lang.*;
public class Demo{
   public static float concave_f_len(float val){
      return val/2 ;
   }
   public static float convex_f_len(float val){
      return - (val/2 ) ;
   }
   public static void main(String argc[]){
      float val = 55 ;
      System.out.print("The focal length of spherical mirror (concave) is : " + concave_f_len(val) + "units\n");
      System.out.println("The focal length of spherical mirror (convex) is : "+ convex_f_len(val) + "units");
   }
}
The focal length of spherical mirror (concave) is : 27.5units
The focal length of spherical mirror (convex) is : -27.5 units
A class named Demo defines a static function that returns a float value. It takes a float value as the parameter and divides it by 2 and returns the result. Similarly, another static function takes in a float value as parameter and divides by 2 and negates the value and returns the output. In the main function, a value for the float value that was passed to both the static functions is defined. Next, the function is called and relevant message is displayed on the console.
Install Shapely on Windows. Simple instructions for installing... | by Dalya Gartzman | Towards Data Science

Shapely is a Python package full of wonderful possibilities for geometric stuff to do with your data.Though, if you are working on Windows OS, installing Shapely is not a trivial task.
Luckily, once you know the details, it’s not that hard.
Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type .Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 .pip install wheelGo here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .pip install <path-to-Downloads>\<filename_from_item_4> . For example in my case I enteredpip install C:\Users\Dalya\Downloads\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type .
Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 .
pip install wheel
Go here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
pip install <path-to-Downloads>\<filename_from_item_4> . For example in my case I enteredpip install C:\Users\Dalya\Downloads\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
And that’s it!
Now this is really simple!For more information on why conda install shapely sometimes does not work, and why the first line is needed, go here.
conda config --add channels conda-forgeconda install shapely
And that’s it!
base64.DecodeString() Function in Golang With Examples - GeeksforGeeks

19 May, 2020
Go language provides inbuilt support for base64 encoding/decoding and has functions that could be used to perform operations on the given data using the base64 package. This package provides DecodeString() function which is used to decode a base64 string to its plaintext form. It supports decoding using both standard and URL compatible base64 standards.
Syntax:
func (enc *Encoding) DecodeString(s string) ([]byte, error)
The Encoding type used with the decoder has 4 variations:
StdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard.
RawStdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard, except that the padding characters are omitted.
URLEncoding: It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames.
RawURLEncoding:It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames, except that the padding characters are omitted.
Return Value: It returns the bytes represented by the given base64 string.
Below programs illustrate the DecodeString() function:
Example 1:
// Golang program to illustrate// the base64.DecodeString() Functionpackage main  import (    "encoding/base64"    "fmt")  func main() {      // taking a string    givenString := "R2Vla3Nmb3JHZWVrcw=="      // using the function    decodedString, err := base64.StdEncoding.DecodeString(givenString)    if err != nil {        fmt.Println("Error Found:", err)        return    }      fmt.Print("Decoded Bytes: ")    fmt.Println(decodedString)      fmt.Print("Decoded String: ")    fmt.Println(string(decodedString))}
Output:
Decoded Bytes: [71 101 101 107 115 102 111 114 71 101 101 107 115]
Decoded String: GeeksforGeeks

Example 2:
// Golang program to illustrate// the base64.DecodeString() Functionpackage main  import (    "encoding/base64"    "fmt")  func main() {      // taking a string    givenString := "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv"      // using the function    decodedString, err := base64.URLEncoding.DecodeString(givenString)    if err != nil {        fmt.Println("Error Found:", err)        return    }      fmt.Print("Decoded Bytes: ")    fmt.Println(decodedString)      fmt.Print("Decoded String: ")    fmt.Println(string(decodedString))}
Output:
Decoded Bytes: [104 116 116 112 115 58 47 47 119 119 119 46 103 101 101 107 115 102 111 114 103 101 101 107 115 46 111 114 103 47]Decoded String: https://www.geeksforgeeks.org/
Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Loops in Go Language
Anonymous function in Go Language
Structures in Golang
Strings in Golang
Time Durations in Golang
How to convert a string in uppercase in Golang?
Functions in Go Language
Convert an Integer to a Binary value in R Programming - as.binary() Function - GeeksforGeeks

16 Jun, 2020
as.binary() function in R Language is used to convert an integer value to a binary value.
Syntax: as.binary(x)
Parameters:x: Integer value
Example 1:
# R Program to convert# an integer to binary  # Loading librarylibrary(binaryLogic)  # Calling as.binary() functionas.binary(1)as.binary(10)as.binary(-1)as.binary(0xAB)
Output:
[1] 1
[1] 1 0 1 0
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[1] 1 0 1 0 1 0 1 1

Example 2:
# R Program to convert# an integer to binary  # Loading librarylibrary(binaryLogic)  # Creating a vectorx1 <- c(1, 10, -1, 2, 5)  # Calling as.binary() functionas.binary(x1)
Output:
[[1]]
[1] 1

[[2]]
[1] 1 0 1 0

[[3]]
 [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

[[4]]
[1] 1 0

[[5]]
[1] 1 0 1

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
DateTime.ToOADate() Method in C#

The DateTime.ToOADate() method in C# is used to convert the value of this instance to the equivalent OLE Automation date.
Following is the syntax −
public double ToOADate ();
Let us now see an example to implement the DateTime.ToOADate() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 10, 11, 9, 10, 35);
      Console.WriteLine("Date = {0}", d);
      double res = d.ToOADate();
      Console.WriteLine("OLE Automation date = {0}", res);
   }
}
This will produce the following output −
Date = 10/11/2019 9:10:35 AM
OLE Automation date = 43749.382349537
Let us now see another example to implement the DateTime.ToOADate() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      double res = d.ToOADate();
      Console.WriteLine("OLE Automation date = {0}", res);
   }
}
This will produce the following output −
Date = 10/16/2019 8:50:25 AM
OLE Automation date = 43754.3683518634
HTML DOM removeChild() Method

The DOM removeChild() method returns and remove the specified child node of the specified node in an HTML document.
Following is the syntax −
node.removeChild(node);
Let us see an example of removeChild() method −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
   html{
      height:100%;
   }
   body{
      text-align:center;
      color:#fff;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
      height:100%;
   }
   p{
      font-weight:700;
      font-size:1.2rem;
   }
   ul{
      list-style-type: none;
      padding:0;
   }
   .btn{
      background:#0197F6;
      border:none;
      height:2rem;
      border-radius:2px;
      width:50%;
      margin:2rem auto;
      display:block;
      color:#fff;
      outline:none;
      cursor:pointer;
   }
   .show{
      font-size:1.5rem;
      font-weight:bold;
   }
</style>
</head>
<body>
<h1>Student Subjects</h1>
<p>Hi, My favourite subjects are:</p>
<ul id="subjectList">
<li>Physics</li>
<li>Chemistry</li>
<li>Maths</li>
<li>English</li>
</ul>
<button onclick="removeSubject()" class="btn">Remove Subject</button>
<script>
   function removeSubject() {
      var subList = document.getElementById("subjectList");
      if (subList.hasChildNodes()) {
         subList.removeChild(subList.childNodes[0]);
      }
   }
</script>
</body>
</html>
This will produce the following output −
Click on “Remove Subject” button to remove subject from the list −
Profit and loss Problems using C

Given a certain cost price(cp) and a selling price(sp) of an unknown product or a service, our task is to find the profit earned or loss suffered using a C program where if the profit is earned should print “Profit” and it’s amount or if the loss is suffered “Loss” and its respective amount or if there is not profit no loss then print “No profit nor Loss”.
To find the profit or the loss we generally see whether the selling price(sp) or the price/amount at which a certain thing is sold or the cost price(cp) at which a certain thing is bought. If the cost price(cp) is higher than the selling price(sp) then it is believed that there is loss, and their difference will be the total loss suffered. When the selling price(sp) is higher than the cost price(cp) then it is believed that profit is earned, and their difference is the total profit.
Input − cp = 149, sp = 229
Output − Profit 80
Explanation −selling price(sp) > cost price(cp), so there is profit of sp-cp=80
Input − cp = 149, sp = 129
Output −Loss 20
Explanation −cost price(cp) > selling price(sp), so there is loss of cp-sp=20
Take the cost price and selling price as input
Take the cost price and selling price as input
Check if cost price > selling price, then it is a loss find difference and return the result.
Check if cost price > selling price, then it is a loss find difference and return the result.
Check if selling price > cost price, then it is a profit find difference and return the result.
Check if selling price > cost price, then it is a profit find difference and return the result.
And if selling price == cost price, then there is not profit nor a loss.
And if selling price == cost price, then there is not profit nor a loss.
Start
In function int Profit(int cp, int sp)
   Step 1→ Return (sp - cp)
In function int Loss(int cp, int sp)
   Step 1→ Return (cp - sp)
In function int main()
   Step 1→ Declare and initialize cp = 5000, sp = 6700
   Step 2→ If sp == cp then,
      Print "No profit nor Loss"
   Step 3→ Else if sp > cp
      Print Profit
   Step 4→ Else
      Print Loss
Stop
 Live Demo
#include <stdio.h>
//Function will return profit
int Profit(int cp, int sp){
   return (sp - cp);
}
// Function will return Loss.
int Loss(int cp, int sp){
   return (cp - sp);
}
int main(){
   int cp = 5000, sp = 6700;
   if (sp == cp)
      printf("No profit nor Loss\n");
   else if (sp > cp)
      printf("%d Profit\n", Profit(cp, sp));
   else
      printf("%d Loss\n", Loss(cp, sp));
   return 0;
}
If run the above code it will generate the following output −
1700 Profit
Python | Index of Non-Zero elements in Python list - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let’s discuss a shorthand by which we can perform this particular task.
Method : Using enumerate() + list comprehensionThis method can be performed using combination of functionalities. In this, we use enumerate function to access index-element together and list comprehension is used for iteration and logic creation.
# Python3 code to demonstrate working of# Index of Non-Zero elements in Python list# using list comprehension + enumerate()  # initialize listtest_list = [6, 7, 0, 1, 0, 2, 0, 12]  # printing original listprint("The original list is : " + str(test_list))  # Index of Non-Zero elements in Python list# using list comprehension + enumerate()res = [idx for idx, val in enumerate(test_list) if val != 0]  # printing resultprint("Indices of Non-Zero elements : " + str(res))
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
C | Functions | Question 8 - GeeksforGeeks

28 Jun, 2021
What is the meaning of using extern before function declaration?
For example following function sum is made extern
extern int sum(int x, int y, int z)
{
    return (x + y + z);
}
(A) Function is made globally available(B) extern means nothing, sum() is same without extern keyword.(C) Function need not to be declared before its use(D) Function is made local to the file.Answer: (B)Explanation: extern keyword is used for global variables. Functions are global anyways, so adding extern doesn’t add anything.Quiz of this Question
C-Functions
Functions
C Language
C Quiz
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
Substring in C++
TCP Server-Client implementation in C
Enumeration (or enum) in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | Pointer Basics | Question 15
C | Misc | Question 7
C | File Handling | Question 1
How can we use MySQL SUM() function with HAVING clause?

By using MySQL SUM() function with the HAVING clause, it filters the result based on a specific condition given after the HAVING clause. To understand the above concept, consider an ‘employee_tbl’ table, which is having the following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id   | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
| 1    | John | 2007-01-24 |        250         |
| 2    | Ram  | 2007-05-27 |        220         |
| 3    | Jack | 2007-05-06 |        170         |
| 3    | Jack | 2007-04-06 |        100         |
| 4    | Jill | 2007-04-06 |        220         |
| 5    | Zara | 2007-06-06 |        300         |
| 5    | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, the query below will use the HAVING clause with SUM() function to get the total of daily_typing_pages which are more than 250.
mysql> Select Name, SUM(daily_typing_pages) From employee_tbl GROUP BY NAME HAVING SUM(daily_typing_pages) > 250;
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack |          270            |
| Zara |          650            |
+------+-------------------------+
2 rows in set (0.17 sec)
TCL Full Form - GeeksforGeeks

08 Nov, 2021
TCL stands for Transaction Control Languages. These commands are used for maintaining consistency of the database and for the management of transactions made by the DML commands. 
A Transaction is a set of SQL statements that are executed on the data stored in DBMS. Whenever any transaction is made these transactions are temporarily happen in database.So to make the changes permanent, we use TCL commands. 
The TCL commands are:  
COMMITROLLBACKSAVEPOINT
COMMIT
ROLLBACK
SAVEPOINT
1. COMMIT : This command is used to save the data permanently. Whenever we perform any of the DDL command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored permanently. So in order to be at the safer side COMMIT command is used. 
Syntax:  
commit; 
2. ROLLBACK : This command is used to get the data or restore the data to the last savepoint or last committed state. If due to some reasons the data inserted, deleted or updated is not correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to the last committed state. 
Syntax:  
rollback;
3. SAVEPOINT : This command is used to save the data at a particular point temporarily, so that whenever needed can be rollback to that particular point. 
Syntax:  
Savepoint A; 
Consider the following Table Student: 
UPDATE STUDENT 
SET NAME = ‘Sherlock’ 
WHERE NAME = ‘Jolly’;

COMMIT;
ROLLBACK; 
By using this command you can update the record and save it permanently by using COMMIT command. 
Now after COMMIT : 
If commit was not performed then the changes made by the update command can be rollback. 
Now if no COMMIT is performed.  
UPDATE STUDENT 
SET NAME = ‘Sherlock’ 
WHERE STUDENT_NAME = ‘Jolly’; 
After update command the table will be: 
Now if ROLLBACK is performed on the above table:  
rollback; 
After Rollback: 
If on the above table savepoint is performed: 
INSERT into STUDENT 
VALUES ('Jack', 95);

Commit;

UPDATE NAME 
SET NAME= ‘Rossie’ 
WHERE marks= 70;

SAVEPOINT A;

INSERT INTO STUDENT 
VALUES (‘Zack’, 76);

Savepoint B;

INSERT INTO STUDENT 
VALUES (‘Bruno’, 85);

Savepoint C;

SELECT * 
FROM STUDENT; 
Now if we Rollback to Savepoint B:  
Rollback to B; 
The resulting Table will be- 
Now if we Rollback to Savepoint A:  
Rollback to A; 
The resulting Table will be- 
So It was all about TCL commands in SQL (transaction control language) with examples.
adnanirshad158
ruhelaa48
Picked
DBMS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Interview Questions
Data Preprocessing in Data Mining
SQL | GROUP BY
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
How does garbage collection work in Python?

Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.
An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.
a = 40      # Create object <40>
b = a       # Increase ref. count  of <40>
c = [b]     # Increase ref. count  of <40>
del a       # Decrease ref. count  of <40>
b = 100     # Decrease ref. count  of <40>
c[0] = -1   # Decrease ref. count  of <40>
You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python
class Point:
   def __init__( self, x=0, y=0):
      self.x = x       self.y = y    def __del__(self):
      class_name = self.__class__.__name__       print class_name, "destroyed"
 pt1 = Point()
pt2 = pt1 pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed
Python IMDbPY – Getting rating of the series - GeeksforGeeks

10 May, 2020
In this article we will see how we can get the rating of the series, rating in IMDb is given from 10 points the rating is based on the viewer experience, the higher the rating means views are highly satisfied or in other words they like the movie.
In order to get this we have to do the following –
1. Get the series details with the help of get_movie method2. As this object will act as dictionary therefore we have to filter the object3. Get the main data of object with the help of data method which will return dictionary4. Get the rating details from the dictionary
Below is the implementation
# importing the moduleimport imdb  # creating instance of IMDbia = imdb.IMDb()  # idcode = "6468322"  # getting informationseries = ia.get_movie(code)  # getting rating of the seriesrating = series.data['rating']  # printing the object i.e nameprint(series)  # print the ratingprint(rating)
Output :
Money Heist
8.5
Another example
# importing the moduleimport imdb  # creating instance of IMDbia = imdb.IMDb()  # idcode = "6077448"  # getting informationseries = ia.get_movie(code)  # getting rating of the seriesrating = series.data['rating']  # printing the object i.e nameprint(series)  # print the ratingprint(rating)
Output :
Sacred Games
8.7
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
How to create a collapsible section with CSS and JavaScript?

To create a collapsible section with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .collapse {
      background-color: rgb(83, 186, 255);
      color: white;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 18px;
   }
   .active, .collapse:hover {
      background-color: rgb(34, 85, 160);
   }
   .content {
      padding: 0 18px;
      display: none;
      overflow: hidden;
      background-color: #b6fdff;
      font-size: 18px;
   }
</style>
</head>
<body>
<h1>Collapsible Example</h1>
<h2>Click on the below collapsible to show the contents</h2>
<button type="button" class="collapse">Open Collapsible</button>
<div class="content">
<h3>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Optio, ducimus!
</h3>
</div>
<script>
   var collapse = document.querySelector(".collapse");
   var i;
   collapse.addEventListener("click", function() {
      this.classList.toggle("active");
      var content = this.nextElementSibling;
      if (content.style.display === "block") {
         content.style.display = "none";
      } else {
         content.style.display = "block";
      }
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Open Collapsible” −
Path iterator() method in Java with Examples

30 Jul, 2019
The iterator() method of java.nio.file.Path used to returns an iterator of the name elements which construct this path.The first element of this iterator contains the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element of this iterator is the name of the file or directory denoted by this path. The root component is not returned by the iterator.
Syntax:
default Iterator<Path> iterator()

Parameters: This method accepts nothing.It is parameter less method.
Return value: This method returns an iterator over the name elements of this path.
Below programs illustrate iterator() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.iterator() method  import java.nio.file.Path;import java.nio.file.Paths;import java.util.*;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path            = Paths.get("D:\\eclipse\\p2"                        + "\\org\\eclipse\\equinox\\p2\\core"                        + "\\cache\\binary");          // Creating an iterator        Iterator<Path> elements            = path.iterator();          // Displaying the values        System.out.println("The iterator values are: ");        while (elements.hasNext()) {            System.out.println(elements.next());        }    }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.iterator() method  import java.nio.file.Path;import java.nio.file.Paths;import java.util.*;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path            = Paths.get("D:\\Workspace"                        + "\\nEclipseWork"                        + "\\GFG\\bin\\defaultpackage");          System.out.println("Original Path:"                           + path);          // Creating an iterator        Iterator<Path> elements            = path.iterator();          // Displaying the values        System.out.println("The iterator values are: ");        while (elements.hasNext()) {            System.out.println(elements.next());        }    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#iterator()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nested switch statement in C++

01 Dec, 2018
Switch-case statements:
These are a substitute for long if statements that compare a variable to several integral values
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
    case 1: // code to be executed if n = 1;
  break;
    case 2: // code to be executed if n = 2;
  break;
    default: // code to be executed if 
      // n doesn't match any cases
}
Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
Syntax:
switch(n)
{
  // code to be executed if n = 1;
  case 1: 
    
  // Nested switch
  switch(num) 
  {
    // code to be executed if num = 10
    case 10: 
      statement 1;
      break;
      
    // code to be executed if num = 20
    case 20: 
      statement 2;
      break;
      
    // code to be executed if num = 30
    case 30: 
      statement 3;
      break;
      
      // code to be executed if n 
      // doesn't match any cases
      default: 
  }
  
  
  break;
    
  // code to be executed if n = 2;
  case 2:
    statement 2;
    break;
  
  // code to be executed if n = 3;
  case 3: 
    statement 3;
    break;
  
   // code to be executed if n doesn't match any cases
   default: 
}

Example:
// Following is a simple program to demonstrate// syntax of Nested Switch Statements.  #include <iostream>using namespace std;  int main(){    int x = 1, y = 2;      // Outer Switch    switch (x) {      // If x == 1    case 1:          // Nested Switch          switch (y) {          // If y == 2        case 2:            cout << "Choice is 2";            break;          // If y == 3        case 3:            cout << "Choice is 3";            break;        }        break;      // If x == 4    case 4:        cout << "Choice is 4";        break;      // If x == 5    case 5:        cout << "Choice is 5";        break;      default:        cout << "Choice is other than 1, 2 3, 4, or 5";        break;    }    return 0;}
Choice is 2

CPP-Control-Flow
cpp-switch
C++
C++ Programs
School Programming
Technical Scripter
CPP-Control-Flow
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
How to append a string in PHP ?

02 Jun, 2020
We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP:
Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to append a string str1 with another string str2.
Syntax:
$x .= $y

Example :
PHP
<?php// PHP program to append a string     // function to append a string function append_string ($str1, $str2) {          // Using Concatenation assignment    // operator (.=)    $str1 .=$str2;          // Returning the result     return $str1;}  // Given string$str1 = "Geeks"; $str2 = "for"; $str3 = "Geeks";   // function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3);  // Printing the resultecho $str; ?>
GeeksforGeeks
Using Concatenation Operator(“.”): The Concatenation operator is used to append a string str1 with another string str2 by concatenation of str1 and str2.
Syntax:
$x . $y

Example :
PHP
<?php// PHP program to append a string     // Function to append a string function append_string ($str1, $str2){          // Using Concatenation assignment    // operator (.)    $str = $str1 . $str2;          // Returning the result     return $str;}  // Given string$str1 = "Geeks"; $str2 = "for"; $str3 = "Geeks";   // Function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3);  // Printing the resultecho $str; ?>
GeeksforGeeks
PHP-Misc
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to Insert Form Data into Database using PHP ?
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to execute PHP code using command line ?
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
C# | How to change Foreground Color of Text in Console

28 Jan, 2019
Given the normal Console in C#, the default color of the text foreground is “Black”. The task is to change this color to some other color.
Approach: This can be done using the ForegroundColor property in the Console class of the System package in C#.
Program 1: Changing the Console Foreground Color to Blue.
// C# program to illustrate the // ForegroundColor propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Display current Foreground color        Console.WriteLine("Default Foreground Color: {0}",                                 Console.ForegroundColor);          // Set the Foreground color to blue        Console.ForegroundColor            = ConsoleColor.Blue;          // Display current Foreground color        Console.WriteLine("Changed Foreground Color: {0}",                                Console.ForegroundColor);    }}}
Output:
Program 2: The list of available colors in which the ForegroundColor can be changed are
// C# program to get the// list of available colorsusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the list of available colors        // that can be changed        ConsoleColor[] consoleColors            = (ConsoleColor[])ConsoleColor                  .GetValues(typeof(ConsoleColor));          // Display the list        // of available console colors        Console.WriteLine("List of available "                          + "Console Colors:");        foreach(var color in consoleColors)            Console.WriteLine(color);    }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.uniqBy() Method

11 Feb, 2021
The _.uniqBy method is similar to _.uniq except that it accepts iteratee which is invoked for each element in an array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array.Syntax:
_.uniqBy([array], [iteratee=_.identity])
Parameters: This method accepts two parameters as mentioned above and described below: 
[arrays]: This parameter holds the arrays to inspect.
[iteratee=_.identity](Function): This parameter holds the iteratee invoked per element.
Return Value: This method is used to return the new duplicate free array.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.  
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = ([2.4, 1.6, 2.2, 1.3]);      // Use of _.uniqBy() // method  let gfg = _.uniqBy(y, Math.floor);      // Printing the output console.log(gfg);
Output:  
[2.4, 1.6 ]
Example 2:  
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = ( [{'x': 2 }, { 'x': 2 }, { 'x': 1 }]);      // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y, 'x');      // Printing the output console.log(gfg);
Output:  
[ { 'x': 2 }, { 'x': 1 } ]
Example 3:  
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = (['aee', 'bee', 'bee', 'cee', 'eee',   'dee', 'gee', 'dee']);      // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y);      // Printing the output console.log(gfg);
Output:  
['aee', 'bee', 'cee', 'eee', 'dee', 'gee']
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. 
manishkumar142
JavaScript-Lodash
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 ?
Installation of Node.js on Linux
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 ?
GATE | GATE CS 1999 | Question 40

30 Sep, 2020
A grammar that is both left and right recursive for a non-terminal is(A) Ambiguous(B) Unambiguous(C) Information is not sufficient to decide whether it is ambiguous or Unambiguous.(D) None of the aboveAnswer: (C)Explanation: Suppose we have grammar like this :
S → n
B → BbB 
Here we see that grammar is left as well as right recursive but still it is unambiguous grammar because A is useless production but it is still part of grammar.So we can say that a grammar having both left as well as right recursion may or may not be ambiguous .
Lets understand with another example as we have grammar like this A→AA using this grammar we can not produce any string in finite steps as language of this grammar is empty set {}.Hence, we finally get conclusion as if grammar is having both left as well as right recursion, then grammar may or may not be ambiguous.
Option (C) is correct.Quiz of this Question
ApurvaRaj
GATE CS 1999
GATE-GATE CS 1999
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31