code-rag-bench/online-tutorials huggingface dataset:
SQL Query to Convert FLOAT to NVARCHAR - GeeksforGeeks

23 Apr, 2021
Here we will see, how to convert FLOAT data to NVARCHAR data in an MS SQL Server’s database table using the CAST(), CONVERT(), and FORMAT() functions.
We will be creating a person table in a database called “geeks”.
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE person(
id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(30) NOT NULL,
weight REAL NOT NULL);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS person;
Use the below statement to add data to the person table:
INSERT INTO person
VALUES
('Yogesh Vaishnav', 62.5),
('Vishal Vishwakarma', 70),
('Ashish Yadav', 69),
('Ajit Yadav', 71.9);
To verify the contents of the table use the below statement:
SELECT * FROM person;
Now let’s convert FLOAT values to nvarchar using three different methods.
Syntax: SELECT CONVERT(<DATA_TYPE>, <VALUE>);
--DATA_TYPE is the type we want to convert to.
--VALUE is the value we want to convert into DATA_TYPE.
Example:
SELECT 'Weight of Yogesh Vaishnav is ' + CONVERT(NVARCHAR(20), weight) 
AS person_weight
FROM person
WHERE name = 'Yogesh Vaishnav';
Output:
Syntax: SELECT CAST(<VALUE> AS <DATA_TYPE>);
--DATA_TYPE is the type we want to convert to.
--VALUE is the value we want to convert into DATA_TYPE.
Example:
SELECT 'Weight of Yogesh Vaishnav is ' + CAST(weight as NVARCHAR(20)) 
AS person_weight
FROM person
WHERE name = 'Yogesh Vaishnav';
Output:
Although the FORMAT() function is useful for formatting datetime and not converting one type into another, still can be used to convert(or here format) float value into an STR value.
Syntax: SELECT FORMAT(<VALUE> , 'actual_format';
--actual_format is the format we want to achieve in a string form.
--VALUE is the value we want to format according to the actual_format.
Example:
SELECT 'Weight of Ashish Yadav is ' + FORMAT(weight, '') --'' denotes no formating
--i.e simply convert it to a string of characters.
AS person_weight
FROM person
WHERE name = 'Ashish Yadav';
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
Mid() and Len() Function in MS Access - GeeksforGeeks

01 Sep, 2020
1. Mid() function :In MS Access the mid() function will extract the string from a given position. In this function 3 parameters will be passed first will be the string and second will be the starting position and last will be the length of the string.
Syntax :
Mid(string, start, length)

Example-1 :
SELECT Mid("GEEKSFORGEEKS", 3, 3) AS ExtractString;

Output –
Example-2 :
SELECT Mid("GEEKSFORGEEKS", 6, 14) AS ExtractString;

Output –
2. Len() function :In MS Access the Len() function will return the length of the string. It will take the string as a parameter and it will return the length of the string.
Syntax :
Len(string/varname)

Example-1 :
SELECT Len("GEEKSFORGEEKS") AS LengthOfString;

Output –
Example-2 :
SELECT Len("GFG") AS LengthOfString;

Output –
DBMS-SQL
Functions
SQL
Functions
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
What is the use of Passthru parameter in Stop-Process in PowerShell?

With the Passthru parameter, PowerShell returns the output in the console. For example, below notepad.exe process with ID 12344 will be stopped and the same will be displayed in the console with the Passthru parameter. Earlier it was not the case with only Stop-Process.
PS C:\WINDOWS\system32> Stop-Process -Id 12344 -PassThru

    Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
    -------  ------    -----      -----     ------     --  -- -----------
        227      13     2800      13440       0.19  12344   1 notepad
You can also combine –Confirm and –PassThru parameters.
PS C:\WINDOWS\system32> Stop-Process -Id 26492 -Confirm -PassThru

Confirm
Are you sure you want to perform this action?
Performing the operation "Stop-Process" on target "notepad (26492)".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    228      14     3152      13736       0.20  26492   1 notepad
Collectors collectingAndThen() method in Java 8

The collectingAndThen() method in Java Collectors class acclimates a Collector to perform an additional finishing transformation. It returns collector which performs the action of the downstream collector, followed by an additional ending step.
The syntax is as follows.
static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR>
finisher)
Here, the parameter,
T − Type of the input elements
T − Type of the input elements
A − Intermediate accumulation type of the downstream collector
A − Intermediate accumulation type of the downstream collector
R − The result type of the downstream collector
R − The result type of the downstream collector
RR − The result type of the resulting collector
RR − The result type of the resulting collector
downstream − Collector
downstream − Collector
finisher − A function to be applied to the final result of the downstream collector
finisher − A function to be applied to the final result of the downstream collector
To work with Collectors class in Java, import the following package.
import java.util.stream.Collectors;
The following is an example to implement collectingAndThen() method in Java.
 Live Demo
import java.util.List;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List<String> list
      = Stream.of("Demo1", "Demo2").collect(Collectors.collectingAndThen(
      Collectors.toList(),
      Collections::<String> unmodifiableList));
      System.out.println(list);
   }
}
[Demo1, Demo2]
Python program to find common elements in three lists using sets

Given three user input lists, our task is to find out common elements from these three lists. Here we are applying intersection method.
Input
A=[2, 3, 4, 5, 6]
B=[2, 3, 7, 6, 90]
C=[2, 3, 45, 34]
Common elements=[2, 3]

Step1: input the elements of three lists.
Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.

def common_ele(my_A, my_B, my_C):
   my_s1 = set(my_A)
   my_s2 = set(my_B)
   my_s3 = set(my_C)
   my_set1 = my_s1.intersection(my_s2)
   output_set = my_set1.intersection(my_s3)
   output_list = list(output_set)
   print(output_list)
if __name__ == '__main__' :
# First List
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("Size="))
   A.append(int(p))
   print (A)
   # Second List
   B=list()
n1=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n1)):
   p=int(input("Size="))
   B.append(int(p))
   print (B)
   # Third Array
   C=list()
n2=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n2)):
   p=int(input("Size="))
   C.append(int(p))
   print (C)
   # Calling Function
   common_ele(A, B, C)
Enter the size of the List 3
Enter the number
Size= 2
[2]
Size= 1
[2, 1]
Size= 2
[2, 1, 2]
Enter the size of the List 3
Enter the number
Size= 2
[2]
Size= 1
[2, 1]
Size= 4
[2, 1, 4]
Enter the size of the List 4
Enter the number
Size= 3
[3]
[]
Size= 2
[3, 2]
[2]
Size= 1
[3, 2, 1]
[1, 2]
Size= 3
[3, 2, 1, 3]
[1, 2]
How to work with MySQL in Lua Programming?

Lua provides different libraries that once can be used to work with MySQL. The most popular framework that enables us to work with MySQL in Lua is LuaSQL.
LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to −
Connect to ODBC, ADO, Oracle, MySQL, SQLite, Firebird and PostgreSQL databases;
Execute arbitrary SQL statements;
Retrieve results in a row-by-row cursor fashion.
You can download MySQL with the help of this command −
luarocks install luasql-mysql
In order to use the following examples to work as expected, we need the initial db setup. The assumptions are listed below.
You have installed and set up MySQL with the default user as root and password as '123456'.
You have created a database test.
We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly.
mysql = require "luasql.mysql"
The variable mysql will provide access to the functions by referring to the main mysql table.
We can set up the connection by initiating a MySQL environment and then creating a connection for the environment. It is shown below.
create environment object
env = assert (mysql.mysql())
connect to data source
con = assert (env:connect("test","root","123456"))
The above connection will connect to an existing MySQL file and establish the connection with the newly created file.
Below code is the complete code that establishes the connection and then traverses over the table present inside the MySQL database.
Consider the code shown below −
-- load driver
local driver = require "luasql.mysql"
create environment object
env = assert (driver.mysql())
connect to data source
con = assert (env:connect("test","root","123456"))
-- reset our table
res = con:execute"DROP TABLE people"
res = assert (con:execute[[
   CREATE TABLE people(
      name varchar(50),
      email varchar(50)
   )
]])
add a few elements list = {
   { name="Mukul Latiyan", email="immukul@protonmail.com", },
   { name="Manoel Joaquim", email="manoel@cafundo.com", },
   { name="Rahul", email="rahul@protonmail.com", },
}
for i, p in pairs (list) do
   res = assert (con:execute(string.format([[
      INSERT INTO people
      VALUES ('%s', '%s')]], p.name, p.email)
   ))
end
-- retrieve a cursor
cur = assert (con:execute"SELECT name, email from people")
-- print all rows, the rows will be indexed by field names
row = cur:fetch ({}, "a")
while row do
   print(string.format("Name: %s, E-mail: %s", row.name, row.email))
   -- reusing the table of results
   row = cur:fetch (row, "a")
end
-- close everything
cur:close() -- already closed because all the result set was consumed
con:close()
env:close()
Name: Mukul Latiyan, E-mail: immukul@protonmail.com
Name: Manoel Joaquim, E-mail: manoel@cafundo.com
Name: Rahul, E-mail: rahul@protonmail.com
Character.equals() method in Java with examples - GeeksforGeeks

06 Dec, 2018
The java.lang.Character.equals() is a function in Java which compares this object against the specified object. If the argument is not null then the result is true and is a Character object that represents the same char value as this object.
Syntax:
public boolean equals(Object obj)
Parameters: The function accepts a single parameter obj which specifies the object to be compared with.
Return Value: The function returns a boolean value. It returns true if the objects are same, otherwise, it returns false.
Below programs illustrates the above method:
Program 1:
// Java program to demonstrate the function// Character.equals() when two objects are sameimport java.lang.*;  public class gfg {      public static void main(String[] args)    {          // assign values to c1, c2        Character c1 = new Character('Z');        Character c2 = new Character('Z');          // assign the result of equals method on c1, c2 to res        boolean res = c1.equals(c2);          // print res value        System.out.println(c1 + " and " + c2 + " are equal is " + res);    }}
Z and Z are equal is true

Program 2:
// Java program to demonstrate function// when two objects are different  import java.lang.*;  public class gfg {      public static void main(String[] args)    {          // assign values to c1, c2        Character c1 = new Character('a');        Character c2 = new Character('A');          // assign the result of equals        // method on c1, c2 to res        boolean res = c1.equals(c2);          // prints the res value        System.out.println(c1 + " and " + c2 + " are equal is " + res);    }}
a and A are equal is false

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object)
Java-Character
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
setjump() and longjump() in C

In this section, we will see what are the setjump and longjump in C. The setjump() and longjump() is located at setjmp.h library. The syntax of these two functions is like below.
setjump(jmp_buf buf) : uses buf to store current position and returns 0.
longjump(jmp_buf buf, i) : Go back to place pointed by buf and return i.
These are used in C for exception handling. The setjump() can be used as try block, and longjump() can be used as throw statement. The longjump() transfers control the pointe which is pointed by setjump().
Here we will see how to print a number 100 times without using recursion, loop, or macro expansion. Here we will use the setjump() and longjump() functions to do that.
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
main() {
   int x = 1;
   setjmp(buf); //set the jump position using buf
   printf("5"); // Prints a number
   x++;
   if (x <= 100)
      longjmp(buf, 1); // Jump to the point located by setjmp
}
5555555555555555555555555555555555555555555555555555555555555555555555555555
555555555555555555555555
Scanner delimiter() method in Java with Examples - GeeksforGeeks

10 Oct, 2018
The delimiter() method ofjava.util.Scanner class returns the Pattern this Scanner is currently using to match delimiters.
Syntax:
public Pattern delimiter()
Return Value: The function returns the scanner’s delimiting pattern.
Below programs illustrate the above function:
Program 1:
// Java program to illustrate the// delimiter() method of Scanner class in Java  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          String s = "Geeksforgeeks has Scanner Class Methods";          // create a new scanner        // with the specified String Object        Scanner scanner = new Scanner(s);          // prints the next line of the string        System.out.println("Scanner String: \n"                           + scanner.nextLine());          // print the delimiter this scanner is using        System.out.println("\nDelimiter being used in Scanner: "                           + scanner.delimiter());          // Close the scanner        scanner.close();    }}
Scanner String: 
Geeksforgeeks has Scanner Class Methods

Delimiter being used in Scanner: \p{javaWhitespace}+

Program 2:
// Java program to illustrate the// delimiter() method of Scanner class in Java  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          String s = "Geeksforgeeks.has.Scanner.Class.Methods";          // create a new scanner        // with the specified String Object        Scanner scanner = new Scanner(s);          // Set the delimiter to "."        scanner.useDelimiter(".");          // prints the next line of the string        System.out.println("Scanner String: \n"                           + scanner.nextLine());          // print the delimiter this scanner is using        System.out.println("\nDelimiter being used in Scanner: "                           + scanner.delimiter());          // Close the scanner        scanner.close();    }}
Scanner String: 
Geeksforgeeks.has.Scanner.Class.Methods

Delimiter being used in Scanner: .

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#delimiter()
Java - util package
Java-Functions
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
VBScript If Statement

An If statement consists of a Boolean expression followed by one or more statements. If the condition is said to be True, the statements under If condition(s) are Executed. If the Condition is said to be False, the statements after the If loop are executed.
The syntax of an If statement in VBScript is −
If(boolean_expression) Then
   Statement 1
	.....
	.....
   Statement n
End If

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a : a = 20
         Dim b : b = 10

         If a > b Then
            Document.write "a is Greater than b"
         End If

      </script>
   </body>
</html>
When the above code is executed, it produces the following result −
a is Greater than b


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Program for Surface Area of Octahedron in C++

The word ‘dodecahedron’ is derived from the Greek words where, Octa means ‘Eight’ and hedron specifies ‘faces’. octahedron in geometric is a 3-D platonic or regular solid with eight faces. Like, other figures octahedrons also have properties and that are −
6 polyhedron vertices
12 polyhedron edges
8 equilateral faces
Given below is the figure of octahedron
Given with the sides, the program must find the surface area of octahedron where surface area is the total space occupied by the faces of the given figure.
To calculate surface area of octahedron there is a formula −
Where, a is side of an Octahedron
Input-: side=5
Output-: 86.6025
Start
Step 1 -> declare function to find area of octahedron
   double surface_area(double side)
      return (2*(sqrt(3))*(side*side))
Step 2 -> In main()
   Declare variable double side=5
   Print surface_area(side)
Stop
#include <bits/stdc++.h>
using namespace std;
//function for surface area of octahedron
double surface_area(double side){
   return (2*(sqrt(3))*(side*side));
}
int main(){
   double side = 5;
   cout << "Surface area of octahedron is : " << surface_area(side);
}
Surface area of octahedron is : 86.6025
How to write data to .csv file in Java?

A library named OpenCSV provides API’s to read and write data from/into a.CSV file. Here it is explained how to write the contents of a .csv file using a Java program.
<dependency>
   <groupId>com.opencsv</groupId>
   <artifactId>opencsv</artifactId>
   <version>4.4</version>
</dependency>
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>
The CSVWriter class of the com.opencsv package represents a simple csv writer. While instantiating this class you need to pass a Writer object representing the file, to which you want to write the data, as a parameter to its constructor.
It provides methods named writeAll() and writeNext() to write data to a .csv file.
The writeNext() method of the CSVWriter class writes the next line to the .csv file
Following Java program demonstrates how to write data to a .csv file using the writeNext() method.
import java.io.FileWriter;
import com.opencsv.CSVWriter;
public class WritingToCSV {
   public static void main(String args[]) throws Exception {
      //Instantiating the CSVWriter class
      CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv"));
      //Writing data to a csv file
      String line1[] = {"id", "name", "salary", "start_date", "dept"};
      String line2[] = {"1", "Krishna", "2548", "2012-01-01", "IT"};
      String line3[] = {"2", "Vishnu", "4522", "2013-02-26", "Operations"};
      String line4[] = {"3", "Raja", "3021", "2016-10-10", "HR"};
      String line5[] = {"4", "Raghav", "6988", "2012-01-01", "IT"};
      //Writing data to the csv file
      writer.writeNext(line1);
      writer.writeNext(line2);
      writer.writeNext(line3);
      writer.writeNext(line4);
      //Flushing data from writer to file
      writer.flush();
      System.out.println("Data entered");
   }
}
Data entered
This method accepts a List object (of String array type) containing the contents to be written and, writes them to the .csv file at once.
Following Java program demonstrates write contents to a .csv file using the writeAll() method.
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVWriter;
public class WritingToCSV {
   public static void main(String args[]) throws Exception {
      //Instantiating the CSVWriter class
      CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv"));
      //Writing data to a csv file
      String line1[] = {"id", "name", "salary", "start_date", "dept"};
      String line2[] = {"1", "Krishna", "2548", "2012-01-01", "IT"};
      String line3[] = {"2", "Vishnu", "4522", "2013-02-26", "Operations"};
      String line4[] = {"3", "Raja", "3021", "2016-10-10", "HR"};
      String line5[] = {"4", "Raghav", "6988", "2012-01-01", "IT"};
      //Instantiating the List Object
      List list = new ArrayList();
      list.add(line1);
      list.add(line2);
      list.add(line3);
      list.add(line4);
      list.add(line5);
      //Writing data to the csv file
      writer.writeAll(list);
      writer.flush();
      System.out.println("Data entered");
   }
}
Data entered
Decimal.ToString() Method in C#

The Decimal.ToString() method in C# is used to convert the numeric value of this instance to its equivalent string representation.
Following is the syntax −
public override string ToString ();
Let us now see an example to implement the Decimal.ToString() method −
using System;
public class Demo{
   public static void Main(){
      decimal d = 3444.787m;
      string str = d.ToString();
      Console.WriteLine("String = "+str);
   }
}
This will produce the following output −
String = 3444.787
Let us see another example −
using System;
public class Demo{
   public static void Main(){
      decimal d = 100;
      string str = d.ToString();
      Console.WriteLine("String = "+str);
   }
}
This will produce the following output −
String = 100
Can we use reserved word ‘index’ as MySQL column name?

Yes, but you need to add a backtick symbol to the reserved word (index) to avoid error while using it as a column name.
Let us first create a table −
mysql> create table DemoTable
(
   `index` int
);
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1000);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(1020);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(967);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(567);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(1010);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| index |
+-------+
| 1000  |
| 1020  |
| 967   |
| 567   |
| 1010  |
+-------+
5 rows in set (0.00 sec)
Now let us display some records with our column name `index`. Here, we are displaying 3 records −
mysql> select *from DemoTable order by `index` DESC LIMIT 3;
This will produce the following output −
+-------+
| index |
+-------+
| 1020  |
| 1010  |
| 1000  |
+-------+
3 rows in set (0.00 sec)
How to change Table Engine in MySQL?

You can change table engine with the help of alter command. The syntax is as follows −
alter table yourTableName ENGINE = yourEngineName;
To understand the above syntax let us create a table with engine MyISAM. Later you can change any other engine. The following is the query to create a table.
mysql> create table ChangeEngineTableDemo
−> (
   −> MovieId int,
   −> MovieName varchar(100),
   −> IsPopular bool
−> )ENGINE = 'MyISAM';
Query OK, 0 rows affected (0.37 sec)
Look at the above query, the table engine is MyISAM, now you can change it to any other engine. Here, we will change engine type InnoDB. The query to change engine type is as follows −
mysql> alter table ChangeEngineTableDemo ENGINE = InnoDB;
Query OK, 0 rows affected (2.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
To check the engine type has been changed or not with the help of show command, the following is the query −
mysql> show create table ChangeEngineTableDemo;
The following is the output −
+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table                 | Create Table                                                                                                                                                                                                                        |
+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ChangeEngineTableDemo | CREATE TABLE `changeenginetabledemo` (
`MovieId` int(11) DEFAULT NULL,
`MovieName` varchar(100) DEFAULT NULL,
`IsPopular` tinyint(1) DEFAULT NULL
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci                                                                                                            |
+-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.03 sec)
How can I capture network traffic of a specific page using Selenium?

We can capture network traffic on a specific page using Selenium webdriver in Python. To achieve this, we take the help of the JavaScript Executor. Selenium can execute JavaScript commands with the help of the execute_script method.
JavaScript command to be executed is passed as a parameter to this method. To capture the network traffic, we have to pass the command: return window.performance.getEntries() as a parameter to the execute_script method.
r = driver.execute_script("return window.performance.getEntries();")
Code Implementation
from selenium import webdriver
#configure chromedriver path
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.google.com/")
#JavaScript command to traffic
r = driver.execute_script("return window.performance.getEntries();")
for res in r:
print(res['name'])
#browser close
driver.close()
JDBC Class.forName vs DriverManager.registerDriver

To connect with a database using JDBC you need to select get the driver for the respective database and register the driver. You can register a database driver in two ways −
Using Class.forName() method − The forName() method of the class named Class accepts a class name as a String parameter and loads it into the memory, Soon the is loaded into the memory it gets registered automatically.
Class.forName("com.mysql.jdbc.Driver");
Following JDBC program establishes connection with MySQL database. Here, we are trying to register the MySQL driver using the forName() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class RegisterDriverExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      Class.forName("com.mysql.jdbc.Driver");
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established: "+con);
   }
}
Connection established: com.mysql.jdbc.JDBC4Connection@4fccd51b
Using the registerDriver() method − The registerDriver() method of the DriverManager class accepts an object of the diver class as a parameter and, registers it with the JDBC driver manager.
Driver myDriver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(myDriver);
Following JDBC program establishes connection with MySQL database. Here, we are trying to register the MySQL driver using the registerDriver() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class RegisterDriverExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established: "+con);
   }
}
Connection established: com.mysql.jdbc.JDBC4Connection@4fccd51b
C++ Program to Calculate Sum of Natural Numbers

The natural numbers are the positive integers starting from 1.
The sequence of natural numbers is −
1, 2, 3, 4, 5, 6, 7, 8, 9, 10......
Sum of the first n natural numbers can be calculated using the for loop or the formula.
Programs specifying both of these methods are given as follows −
The program to calculate the sum of n natural numbers using for loop is given as follows.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n=5, sum=0, i;
   for(i=1;i<=n;i++)
   sum=sum+i;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}
Sum of first 5 natural numbers is 15
In the above program, a for loop is run from 1 to n. In each iteration of the loop, the value of i is added to the sum. So, the sum of the first n natural numbers is obtained. This is demonstrated by the following code snippet.
for(i=1;i<=n;i++)
sum=sum+i;
The formula to find the sum of first n natural numbers is as follows.
sum = n(n+1)/2
The program to calculate the sum of n natural numbers using the above formula is given as follows.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n=5, sum;
   sum = n*(n+1)/2;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}
Sum of first 5 natural numbers is 15
In the above program, the sum of the first n natural numbers is calculated using the formula. Then this value is displayed. This is demonstrated by the following code snippet.
sum = n*(n+1)/2;
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
How to iterate two Lists or Arrays with one foreach statement in C#?

Set two arrays.
var val = new [] { 20, 40, 60};
var str = new [] { "ele1", "ele2", "ele3"};
Use the zip() method to process the two arrays in parallel.
var res = val.Zip(str, (n, w) => new { Number = n, Word = w });
The above fetches both the arrays with int and string elements respectively.
Now, use foreach to iterate the two arrays −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      var val = new [] { 20, 40, 60};
      var str = new [] { "ele1", "ele2", "ele3"};
      var res = val.Zip(str, (n, w) => new { Number = n, Word = w });

      foreach(var a in res) {
         Console.WriteLine(a.Number + a.Word);
      }
   }
}
20ele1
40ele2
60ele3
Check if words are sorted according to new order of alphabets - GeeksforGeeks

09 Dec, 2018
Given a sequence of Words and the Order of the alphabet. The order of the alphabet is some permutation of lowercase letters. The task is to check whether the given words are sorted lexicographically according to order of alphabets. Return “True” if it is, otherwise “False”.
Examples:
Input : Words = [“hello”, “leetcode”], Order = “habcldefgijkmnopqrstuvwxyz”Output : true
Input : Words = [“word”, “world”, “row”], Order = “abcworldefghijkmnpqstuvxyz”Output : falseExplanation : As ‘d’ comes after ‘l’ in Order, thus words[0] > words[1], hence the sequence is unsorted.
Approach : The words are sorted lexicographically if and only if adjacent words are sorted. This is because order is transitive i:e if a <= b and b <= c, implies a <= c.
So our goal it to check whether all adjacent words a and b have a <= b.
To check whether for two adjacent words a and b, a <= b holds we can find their first difference. For example, "seen" and "scene" have a first difference of e and c. After this, we compare these characters to the index in order.
We have to deal with the blank character effectively. If for example, we are comparing "add" to "addition", this is a first difference of (NULL) vs "i".
Below is the implementation of above approach :
Python3
# Function to check whether Words are sorted in given Orderdef isAlienSorted(Words, Order):    Order_index = {c: i for i, c in enumerate(Order)}      for i in range(len(Words) - 1):        word1 = Words[i]        word2 = Words[i + 1]          # Find the first difference word1[k] != word2[k].        for k in range(min(len(word1), len(word2))):              # If they compare false then it's not sorted.            if word1[k] != word2[k]:                if Order_index[word1[k]] > Order_index[word2[k]]:                    return False                break        else:              # If we didn't find a first difference, the            # Words are like ("add", "addition").            if len(word1) > len(word2):                return False      return True    # Program CodeWords = ["hello", "leetcode"]Order = "habcldefgijkmnopqrstuvwxyz"  # Function call to print required answerprint(isAlienSorted(Words, Order))
True

Time Complexity: O(N), where N is the total number of characters in all words.
Auxiliary Space: O(1)
lexicographic-ordering
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HeapSort
Time Complexities of all Sorting Algorithms
Radix Sort
Merge two sorted arrays
Python Program for Bubble Sort
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Auto comment on a facebook post using JavaScript - GeeksforGeeks

29 Jul, 2020
In this article, we are going to learn how to comment automatically in a Facebook post. You can use this method to wish your friends a happy birthday or just comment on anything. It is useful when you want to comment a number of times on a post. You just need to specify the count and message that will be automatically commented on a time-interval. Also, you don’t need to install anything for this method to work.
Approach:
Initialize count and message value.Then define an interval function which will be called each time.Make an input variable that points to the input field of comment section.Make a submit variable that points to the comment button.Since, comment button is disabled by default, so first enable it.Set the message to be written in input.Click on the submit.Decrement the count.If count become zero, then clear the interval function.Set the time interval of 10000ms, it means the function will be called after each 10 seconds.
Initialize count and message value.
Then define an interval function which will be called each time.
Make an input variable that points to the input field of comment section.
Make a submit variable that points to the comment button.
Since, comment button is disabled by default, so first enable it.
Set the message to be written in input.
Click on the submit.
Decrement the count.
If count become zero, then clear the interval function.
Set the time interval of 10000ms, it means the function will be called after each 10 seconds.
Below are the steps:
Go to facebook page using m.facebook.com
Sign in and open any post.
Open developer mode in Chrome by pressing Ctrl+Shift+I
Navigate to the console.
Now, run the below script.
var count = 100;var message = "Hi";var loop = setInterval(function(){    var input = document.getElementsByName("comment_text")[0];    var submit = document.querySelector('button[type="submit"]');    submit.disabled = false;    input.value = message;    submit.click();    count -= 1;    if(count == 0)    {        clearInterval(loop);    }}, 10000);
Output:
Output
Note: Please ensure that there is stable internet connection available, so that the script runs smoothly. Also ensure to visit facebook with m.facebook.com not www.facebook.com because this script works on mobile version of facebook only.
This tutorial is for educational purpose only, please don’t use it for disturbing anyone or any unethical way.
JavaScript-Misc
GBlog
JavaScript
TechTips
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Working with csv files in Python
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
How to create a delete confirmation modal with CSS and JavaScript?

To create a delete confirmation modal 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: Arial, Helvetica, sans-serif;
   }
   .modal {
      text-align: center;
      display: none;
      position: fixed;
      z-index: 1;
      padding-top: 100px;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
   }
   .modalContent {
      font-size: 20px;
      font-weight: bold;
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
   }
   .close {
      color: rgb(255, 65, 65);
      float: right;
      font-size: 40px;
      font-weight: bold;
   }
   .close:hover, .close:focus {
      color: #ff1010;
      cursor: pointer;
   }
   .modalContent button {
      border: none;
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      padding: 10px;
   }
   .del {
      background-color: rgb(255, 65, 65);
   }
   .del:hover {
      background-color: rgb(255, 7, 7);
   }
   .cancel:hover {
      background-color: rgb(167, 167, 167);
   }
</style>
</head>
<body>
<h1>Modal Example</h1>
<button class="openModal">Open Modal</button>
<h2>Click on the above button to open modal</h2>
<div class="modal">
<div class="modalContent">
<span class="close">×</span>
<p>Are you sure you want to delete your account</p>
<button class="del" onclick="hideModal()">Delete Account</button>
<button class="cancel" onclick="hideModal()">Cancel</button>
</div>
</div>
<script>
   var modal = document.querySelector(".modal");
   var btn = document.querySelector(".openModal");
   var span = document.querySelector(".close");
   btn.addEventListener("click", () => {
      modal.style.display = "block";
   });
   span.addEventListener("click", () => {
      hideModal();
   });
   function hideModal() {
      modal.style.display = "none";
   }
   window.onclick = function(event) {
      if (event.target == modal) {
         hideModal();
      }
   };
</script>
</body>
</html>
The above code will produce the following output −
On clicking the Open Modal button −
How to Create Empty List in R? - GeeksforGeeks

03 Dec, 2021
In this article, we will discuss how to create an empty list in R Programming Language.
Here we are going to create an empty list with length 0 by using list() function.
Syntax:
data=list()
Example:
R
# create empty listdata = list() print(data) # display lengthprint(length(data))
Output:
list()
[1] 0
Here we are specifying length in an empty list using the following syntax.
vector(mode='list', length)
where,
mode specifies the list
length specifies the length of empty list
Example:
R
# create empty list with length 3data = vector(mode='list', length=3) print(data) # display lengthprint(length(data))
Output:
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[1] 3
anikakapoor
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
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?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Numbers in Ruby - GeeksforGeeks

10 Sep, 2021
Ruby supports two types of numbers:
Integers: An integer is simply a sequence of digits, e.g., 12, 100. Or in other words, numbers without decimal points are called Integers. In Ruby, Integers are object of class Fixnum(32 or 64 bits) or Bignum(used for bigger numbers).Floating-point numbers: Numbers with decimal points are usually called floats, e.g., 1.2, 10.0. The floating-point numbers are object of class Float.
Integers: An integer is simply a sequence of digits, e.g., 12, 100. Or in other words, numbers without decimal points are called Integers. In Ruby, Integers are object of class Fixnum(32 or 64 bits) or Bignum(used for bigger numbers).
Floating-point numbers: Numbers with decimal points are usually called floats, e.g., 1.2, 10.0. The floating-point numbers are object of class Float.
Note: Underscore can be used to separate a thousand places e.g: 25_120.55 is the same as the number 25120.55.
Example 1: Basic arithmetic operations on numbers in Ruby is shown below. In Ruby, mathematical operations result in an integer only if all numbers used are integer numbers unless we get the result as a float. 
Ruby
# Addition of two integersputs 2 + 3 # Addition of integer and floatputs 2 + 3.0 # Subtraction of two integersputs 5 - 3 # Multiplication and division of two integersputs 2 * 3puts 6 / 2 # Exponential operationputs 2 ** 3
Output: 
5
5.0
2
6
3
8
Example 2: In Ruby, for Modulus(%) operator the sign of the result is always the same as the sign of the second operand. So, 10 % -3 is -2 and -10 % 3 is 2.
Ruby
# Modulus operation on numbersputs 10 % 3puts 10 % -3puts -10 % 3
Output: 
1
-2
2
Example 3: Other mathematical operations on numbers in Ruby is shown below.
Ruby
num1 = -20num2 = 10.2 # abs() method returns absolute value of numberputs num1.abs() # round() method returns the number after roundingputs num2.round() # ceil() and floor() function for numbers in Rubyputs num2.ceil()puts num2.floor()
Output:
20
10
11
10
 
simmytarika5
Picked
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_index function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby For Beginners
Ruby | Types of Iterators
Ruby on Rails Introduction
Ruby | Array shift() function
Ruby | Class Method and Variables
Ruby | Enumerable find() function
Ruby | String concat Method
Ruby | pop() function
How to write to CSV in R without index ? - GeeksforGeeks

07 Apr, 2021
We know that when we write some data from DataFrame to CSV file then a column is automatically created for indexing. We can remove it by some modifications. So, in this article, we are going to see how to write CSV in R without index.
To write to csv file write.csv() is used.
Syntax:
write.csv(data,path)
Lets first see how indices appear when data is written to CSV.
Example:
R
Country <- c("China", "India", "United States", "Indonesia", "Pakistan")  Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280",                             "327,096,265", "267,670,543", "212,228,286")  Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754",                             "329,064,917", "270,625,568", "216,565,318")  change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")    data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)print(data)  write.csv(data,"C:\\Users\\...YOUR PATH...\\population.csv")print ('CSV file written Successfully :)')
Output:
CSV file with extra index column
Now let us see how these indices can be removed, for that simply set row.names parameter to False while writing data to a csv file using write.csv() function. By Default, it will be TRUE and create one extra column to CSV file as index column.
Example:
R
Country <- c("China", "India", "United States", "Indonesia", "Pakistan")  Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280",                             "327,096,265", "267,670,543", "212,228,286")  Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754",                             "329,064,917", "270,625,568", "216,565,318")  change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")    data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)  write.csv(data,"C:\\Users\\..YOUR PATH...\\population.csv", row.names = FALSE)print ('CSV file written Successfully :)')
Output:
CSV file without extra index column
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
Ruby | Range first() function - GeeksforGeeks

06 Jan, 2020
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only.
Syntax: range1.first(X)
Parameters: The function accepts X which is the number of elements from the beginning.
Return Value: It returns an array of first X elements.
Example 1:
# Ruby program for first() # method in Range   # Initialize range range1 = (0..10)  # Prints the first element puts range1.first()
Output:
0

Example 2:
# Ruby program for first() # method in Range   # Initialize range range1 = (0..10)  # Prints the first element puts range1.first(3)
Output:
0
1
2

Ruby Range-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby Mixins
Ruby | Array collect() operation
Ruby | Array shift() function
Ruby | String concat Method
Ruby | unless Statement and unless Modifier
Ruby | Module