code-rag-bench/online-tutorials huggingface dataset:
How to select a column of a matrix by column name in R?

When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name.
M1 <-matrix(1:25,nrow=5)
M1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
colnames(M1) <-c("C1","C2","C3","C4","C5")
M1
C1 C2 C3 C4 C5
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
M1[,"C1"]
[1] 1 2 3 4 5
M1[,"C2"]
[1] 6 7 8 9 10
M1[,"C4"]
[1] 16 17 18 19 20
M1[,"C5"]
[1] 21 22 23 24 25
M2 <-matrix(sample(1:100,36),nrow=6)
M2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29
colnames(M2) <-c("Rate","Percentage","Class","Group","ID","Section")
M2
Rate Percentage Class Group ID Section
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29 70
M2[,"Rate"]
[1] 97 41 65 46 6 71
M2[,"Percentage"]

[1] 53 98 54 87 23 51
M2[,"Class"]
[1] 27 38 15 100 91 26
M2[,"Group"]

[1] 60 73 49 19 45 85
M2[,"ID"]
[1] 13 74 9 94 34 29
M2[,"Section"]

[1] 8 57 5 62 32 70
M3 <-matrix(1:100,nrow=10)
colnames(M3) <-c("Var1","Var2","Var3","Var4","Var5","Var6","Var7","Var8","Var9","Var10")
M3
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
M3[,"Var1"]
[1] 1 2 3 4 5 6 7 8 9 10
M3[,"Var5"]
[1] 41 42 43 44 45 46 47 48 49 50
M3[,"Var7"]
[1] 61 62 63 64 65 66 67 68 69 70
M3[,"Var9"]
[1] 81 82 83 84 85 86 87 88 89 90
Tryit Editor v3.7

Tryit: Force all buttons to have the same look with !important
Differences between anonymous class and lambda expression in Java?


Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.
An anonymous class object generates a separate class file after compilation that increases the size of a jar file while a lambda expression is converted into a private method. It uses invokedynamic bytecode instruction to bind this method dynamically, which saves time and memory.
We use this keyword to represent the current class in lambda expression while in the case of an anonymous class, this keyword can represent that particular anonymous class.
Anonymous classes can be used in case of more than one abstract method while a lambda expression specifically used for functional interfaces.
We need to provide the function body only in lambda expression while in the case of an anonymous class, we need to write the redundant class definition.
public class ThreadTest {
   public static void main(String[] args) {
      Runnable r1 = new Runnable() { // Anonymous class
      @Override
      public void run() {
         System.out.println("Using Anonymous class");
      }
   };
      Runnable r2 = () -> { // lambda expression
         System.out.println("Using Lambda Expression");
      };
      new Thread(r1).start();
      new Thread(r2).start();
   }
}
Using Anonymous class
Using Lambda Expression
Finding square root of a number without using Math.sqrt() in JavaScript

We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return the square root of the number provided as the input.
Following is the code −
const squareRoot = (num, precision = 0) => {
   if (num <= 0) {
      return 0;
   };
   let res = 1;
   const deviation = 1 / (10 ** precision);
   while (Math.abs(num - (res ** 2)) > deviation) {
      res -= ((res ** 2) - num) / (2 * res);
   };
   return Math.round(res * (10 ** precision)) / (10 ** precision);
};
console.log(squareRoot(16));
console.log(squareRoot(161, 3));
console.log(squareRoot(1611, 4));
Following is the output on console −
4
12.689
40.1373
Number.doubleValue() method in java with examples - GeeksforGeeks

20 Jun, 2018
The java.lang.Number.doubleValue() is an inbuilt method in java that returns the value of the specified number casted as a double data type. This may involve rounding or truncation.
Syntax:
public abstract double doubleValue()

Parameters: This method does not accepts any parameter.
Return value: This method returns the numeric value represented by this object after conversion to type double.
Below programs illustrate the Number.doubleValue()method:
Program 1:
// java program that demonstrates// the Number.doubleValue()public class gfg {      public static void main(String[] args)    {          // number as integer        Integer x = new Integer(1234785456);        // print value as double        System.out.println(x.doubleValue());          // number as float        Float y = new Float(98745876f);        // print value as double        System.out.println(y.doubleValue());    }}
1.234785456E9
9.8745872E7

Program 2:
// java program that demonstrates// the Number.doubleValue()  public class gfg {      public static void main(String[] args)    {          // number as integer        Integer x = new Integer(123);        // print value as double        System.out.println(x.doubleValue());          // number as float        Float y = new Float(9876f);        // print value as double        System.out.println(y.doubleValue());    }}
123.0
9876.0

Java-Functions
Java-lang package
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
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
How to skip a middleware in Express.js ? - GeeksforGeeks

09 Apr, 2021
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call.
Prerequisite:
express.js: To handle routing.
Setting up environment and execution:
Step 1: Initialize node projectnpm init
Step 1: Initialize node project
npm init
Step 2: Install required modulesnpm install express
Step 2: Install required modules
npm install express
Example:
index.js
const express = require("express");// const database = require('./sqlConnection');  const app = express();  // Start server on port 5000app.listen(5000, () => {  console.log(`Server is up and running on 5000 ...`);});  // define middleware 1let middleware1 = (req, res, next) => {      // decide a parameter    req.shouldRunMiddleware2 = false;      console.log("Middleware 1 is running !");    next();}  // define middleware 2let middleware2 = (req, res, next) => {    if(!req.shouldRunMiddleware2) {        console.log("Skipped middleware 2");        return next();    }      console.log("Middleware 2 is running !");}  // define middleware 3let middleware3 = (req, res, next) => {    console.log("Middleware 3 is running !");}  // create route for home page '/'app.get("/", middleware1, middleware2, middleware3);
Output: Run the below command to start the server. After that go to http://localhost:5000 on browser to see output in console
node index.js
In browser.
Console:
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
Express.js req.params Property
JWT Authentication with Node.js
Mongoose Populate() Method
How to build a basic CRUD app with Node.js and ReactJS ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to restrict MySQL `LIKE` operator to begin with specific characters?

Let us first create a table −
mysql> create table DemoTable
(
   FirstName varchar(40)
);
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
|FirstName  |
+-----------+
| John      |
| Adam      |
| David     |
| Mike      |
| Sam       |
+-----------+
5 rows in set (0.00 sec)
Following is the query to restrict `LIKE` operator to begin with specific characters −
mysql> select *from DemoTable where FirstName LIKE 'D%' or FirstName LIKE 'S%';
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| David     |
| Sam       |
+-----------+
2 rows in set (0.00 sec)
Simplification - Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Simplification. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - 5852 / 28 * ? - 1653 = 1064
A - 9
B - 13
C - 15
D - 18
let 5852 / 28 * x ? 1653 = 1064.
Then , 5852 * 1/28 *x = ( 1064 + 1653 ) = 2717 ⇒ 209 x = 2717 ⇒ x = 2717 / 209 = 13.
Q 2 - 108 / 36 of  1/3 + 2/5 * 15/4 = ?
A - 35/4
B - 25/4
C - 5/2
D - 21/2
given exp. = 108 /36 of 1/3+ 2/5 *15/4
= 108/ 12+ 2/5 *15/4 = 9+ 3/2 = 21/2
Q 3 - 9 - (11/9) of (36/11)  /(36/7) of (7/9) = ?
A - 5/4
B - 8
C - 680/81
D - 9
given exp = 9- 11/9 of 36/11/ 36/7 of 7/9 =9-4/4=( 9-1) = 8
Q 4 - 6994/7 + 6995/7 +6996/7 +6997/7 +6998/7 +6999/7 =?
A - 2998
B - 5979
C - 5997
D - 5994
Give Exp. = (999 * 6 ) + (1/7 + 2/7 + 3/7+ 4/7+ 5/7+ 6/7)
= 5994 + ( 1+ 2+ 3+ 4 +5+ 6) / 7 = 5994 + 21/7
= 5994+ 3 = 5997.
Q 5 - If 1/ 1+ 1 / 1+ 1/x = 2 then x = ?
A - ? 1/3
B - ? 1
C - 1/3
D - 1
1/(1+ 1/ (1+1/x)) = 2
⇒ 1/(1+x/(x+1)) = 2
⇒ (x+1)/ (2x+1) = 2
⇒ x+1= 4x+2
⇒ 3x= -1
⇒ x= -1/3
Q 6 - (1+ 1/ x+1) (1+ 1/ x+2) (1+ 1/ x+3) (1+ 1/ x+4)= ?
A - x+5/  x+1
B - (x+ 1/ x+5 )
C - 1/ (x+5)
D - x+6/ x+5
given exp.=  (x+2)/ (x+1)* (x+3)/(x+2) *(x+4)/ (x+3)* (x+5) (x+4)
=  (x+5)/ (x+1)
Q 7 - if x/ 2y = 3/2  , then  (2x+y)/(x-2y) = ?
A - 1/7
B - 7
C - 7.1
D - none of these
x / 2y = 3/2 ⇒ x/y = ( 2 * 3/2 )  = 3.
2x +y / x - 2y = 2 ( x/y ) + 1 / (x/y) - 2 = 2* 3 + 1 / 3-2 = 7/1 = 7.
Q 8 - if x= (1-a), y=(2a+1) and x = y , then a = ?
A - 2
B - 1/2
C - 0
D - -1
x= y ⇒(1-a) = (2a+1) ⇒ 3a = 0 ⇒ a = 0.
Q 9 - ((856+167)2 +(856-167)2)/(856*856+ 167*167)= ?
A - 1
B - 2
C - 689
D - 1023
given exp.  = (a+b)2 +(a-b)2/ (a2+b2),   where a = 856 , b = 167
= 2 (a2+b2) /(a2+b2) = 2
Q 10 - An organization  have three share holder A, B and C.  all of the shareholder get  the share of profit in that way  1/3 share of the profit  gets A.  while  1/4  share of the profit  received by B and rest of the part of the profit Rs. 5000 becomes the share of  C. Find out the share of profit Received by A?
A - 2500 Rs
B - 3000 Rs
C - 3500 Rs
D - 4000 Rs
Let the total profit be rs. x. then,
x/3 + x/4 +5000   = x ⇒ 4x+ 3x+ 60000 = 12x
⇒  5x = 60000 ⇒  x = 12000.
Share of profit received by A = (1/3 * 12000) = 4000 Rs.

    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
atq command in linux with examples - GeeksforGeeks

04 Apr, 2019
atq displays the list of pending jobs which are scheduled by the user. If the user is the superuser then the pending jobs of all the users will be displayed. The output lines display Job number, date, hour, queue, and username for each job.
Syntax:
atq [-V] [-q queue]
Options:
-V: It will display the version number to standard error and exit successfully.
-q: Shows job of specified queue. A queue can be denoted by any single letter from a to z and A to Z. For ‘at’, a is the default queue and for ‘batch’, b queue is default. For a currently running job, queue name will be designated with “=”. If a job is submitted to a queue designated with an uppercase letter, the job is treated as if it were submitted to batch at the time of the job.atq without arguments display all pending jobs of User.atq without arguments display all pending jobs of all users if the root is the user.To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’.Alternative Command for atq:at -l Showing all the jobs.Showing all the jobs which belongs to queue ‘a’.My Personal Notes
arrow_drop_upSave
atq without arguments display all pending jobs of User.
atq without arguments display all pending jobs of all users if the root is the user.
To display jobs which belong to a specific queue:atq -q QueueBelow image is showing all the jobs which belongs to queue ‘m’.
atq -q Queue
Below image is showing all the jobs which belongs to queue ‘m’.
Alternative Command for atq:
at -l 
Showing all the jobs.
Showing all the jobs which belongs to queue ‘a’.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Getting last 5 character of a string with MySQL query?

To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.
The syntax for RIGHT() method is as follows −
SELECT RIGHT(yourColumnName, valueOfN) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table gettingLast5Characters
   −> (
   −> BookName varchar(100)
   −> );
Query OK, 0 rows affected (0.73 sec)
Now you can insert records in the table using insert command. The query is as follows −
mysql> insert into gettingLast5Characters values('Introduction to C');
Query OK, 1 row affected (0.19 sec)

mysql> insert into gettingLast5Characters values('C in Depth');
Query OK, 1 row affected (0.18 sec)

mysql> insert into gettingLast5Characters values('Introduction to Java');
Query OK, 1 row affected (0.18 sec)

mysql> insert into gettingLast5Characters values('Let us C');
Query OK, 1 row affected (0.51 sec)
Display all records from the table using select statement. The query to display all records is as follows −
mysql> select *from gettingLast5Characters;
The following is the output −
+----------------------+
| BookName             |
+----------------------+
| Introduction to C    |
| C in Depth           |
| Introduction to Java |
| Let us C             |
+----------------------+
4 rows in set (0.00 sec)
Here is the query that gets the last 5 character of string −
mysql> select RIGHT(BookName,5) as Last5Character from gettingLast5Characters;
The following is the output −
+----------------+
| Last5Character |
+----------------+
| to C           |
| Depth          |
| Java           |
| us C           |
+----------------+
4 rows in set (0.04 sec)
Look at the above sample output, space is counting also.
C program to delete a file

21 Nov, 2017
The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value.
#include<stdio.h>  int main(){   if (remove("abc.txt") == 0)      printf("Deleted successfully");   else      printf("Unable to delete the file");     return 0;}
Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed.
Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e. a.out file (executable file) created after compiling . Hence the program will be destroyed.
#include<stdio.h>#include<stdlib.h>  int main(int c, char *argv[]){    printf("By the time you will compile me I will be destroyed \n");         // array of pointers to command line arguments    remove(argv[0]);        // Note: argv[0] will contain the executable file i.e. 'a.out'      return 0;}  // This code is contributed by  MAZHAR IMAM KHAN.
Output:
By the time you will compile me I will be destroyed

After the output shown above, the a.out file will be removed.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype?
Java - The Stack Class

Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.
Stack( )

Apart from the methods inherited from its parent class Vector, Stack defines the following methods −
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
Object peek( )
Returns the element on the top of the stack, but does not remove it.
Object pop( )
Returns the element on the top of the stack, removing it in the process.
Object push(Object element)
Pushes the element onto the stack. Element is also returned.
int search(Object element)
Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned.
The following program illustrates several of the methods supported by this collection −
import java.util.*;
public class StackDemo {

   static void showpush(Stack st, int a) {
      st.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + st);
   }

   static void showpop(Stack st) {
      System.out.print("pop -> ");
      Integer a = (Integer) st.pop();
      System.out.println(a);
      System.out.println("stack: " + st);
   }

   public static void main(String args[]) {
      Stack st = new Stack();
      System.out.println("stack: " + st);
      showpush(st, 42);
      showpush(st, 66);
      showpush(st, 99);
      showpop(st);
      showpop(st);
      showpop(st);
      try {
         showpop(st);
      } catch (EmptyStackException e) {
         System.out.println("empty stack");
      }
   }
}
This will produce the following result −
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
TypeScript Number valueOf() Method

13 Aug, 2020
The valueOf() method in TypeScript is used to return the primitive value of the specified number object.Syntax:
number.valueOf()

Parameter values: This method does not accept any parameter.
Return Value: The valueOf() method in TypeScript returns the primitive value of the specified number object.
Below examples illustrates the working of valueOf() function in TypeScript:Example 1:
javascript
//valueOf()var num3 = new Number(30);console.log(num3.valueOf());
Output: 
30

Example 2:
javascript
// valueOf() methodlet num4 = new Number(563);console.log("Number Method: tovalueOf()");console.log(typeof num4 )console.log(num4 )console.log(num4 .valueOf())
Output: 
Number Method: tovalueOf()
number
[Number: 563]
563

TypeScript
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
Difference Between PUT and PATCH Request
C library function - clock()

The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.
On a 32 bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.
Following is the declaration for clock() function.
clock_t clock(void)
NA
NA
This function returns the number of clock ticks elapsed since the start of the program. On failure, the function returns a value of -1.
The following example shows the usage of clock() function.
#include <time.h>
#include <stdio.h>

int main () {
   clock_t start_t, end_t;
   double total_t;
   int i;

   start_t = clock();
   printf("Starting of the program, start_t = %ld\n", start_t);
    
   printf("Going to scan a big loop, start_t = %ld\n", start_t);
   for(i=0; i< 10000000; i++) {
   }
   end_t = clock();
   printf("End of the big loop, end_t = %ld\n", end_t);
   
   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total time taken by CPU: %f\n", total_t  );
   printf("Exiting of the program...\n");

   return(0);
}
Let us compile and run the above program that will produce the following result −
Starting of the program, start_t = 1194
Going to scan a big loop, start_t = 1194
End of the big loop, end_t = 26796
Total time taken by CPU: 0.025602
Exiting of the program...
Extract Data from Database using MySQL-Connector and XAMPP in Python

01 Nov, 2020
Prerequisites: MySQL-Connector, XAMPP Installation
A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server.
XAMPP: Database / Server to store and display data.
MySQL-Connector module: For connecting the database with the python file. Use the below command to install this module.
pip install mysql-connector

Wheel module: A command line tool for working with wheel files. Use the below command to install this module.
pip install wheel

Procedure to create a table in the database:
Start your XAMPP web server.
Type http://localhost/phpmyadmin/ in your browser.
Go to Database create database with name and click on Create.
Create a table with in GEEK database and click on Go.
Define column names and click on save.
Your table is created.
Insert data in your database by clicking on SQL tab then select INSERT.
The data in your table is:
Now you can perform operation IE display data in your web page using python
Procedure for writing Python program:
Import mysql connector module in your Python code.
import mysql.connector

Create connection object.
conn_object=mysql.connector.connect(hostname,username,password,database_name)
Here, you will need to pass server name, username, password, and database name)
Create a cursor object.
cur_object=conn_object,cursor()

Perform queries on database.
query=DDL/DML etc
cur_obj=execute(query)

Close cursor object.
cur_obj.close()

Close connection object.
conn_obj.close()

Below is the complete Python program based on the above approach:
Python3
# import required modulesimport mysql.connector  # create connection objectcon = mysql.connector.connect(  host="localhost", user="root",  password="", database="GEEK")  # create cursor objectcursor = con.cursor()  # assign data queryquery1 = "desc geeksdemo"  # executing cursorcursor.execute(query1)  # display all recordstable = cursor.fetchall()  # describe tableprint('\n Table Description:')for attr in table:    print(attr)  # assign data queryquery2 = "select * from geeksdemo"  # executing cursorcursor.execute(query2)  # display all recordstable = cursor.fetchall()  # fetch all columnsprint('\n Table Data:')for row in table:    print(row[0], end=" ")    print(row[1], end=" ")    print(row[2], end=" ")    print(row[3], end="\n")      # closing cursor connectioncursor.close()  # closing connection objectcon.close()
Output:
Note: XAMPP Apache and MySQL should be kept on during the whole process. 
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
char keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. char is a keyword that is used to declare a variable which store a character value from the range of +U0000 to U+FFFF. It is an alias of System.Char.
Syntax:
char variable_name = value;
char keyword occupies 2 bytes (16 bits) in the memory.
Example:
Input: S

Output: chr: S
        Size of a char variable: 2 

Input: G

Output: Type of chr: System.Char
        chr: G
        Size of a char variable: 2

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

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

Example 3:
// C# program for char keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // char variable declaration        char chr = 'Geeks';          // to print value        Console.WriteLine("chr: " + chr);          // to print size of a char        Console.WriteLine("Size of a char variable: " + sizeof(char));    }}
Error:
Too many characters in character literal
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
HTML | autoplay Attribute

31 May, 2022
The HTML autoplay Attribute is used to specify that the audio/video should automatically start playing when web page is loaded. It is a Boolean attribute. Syntax:  
<element autoplay> 
Uses It can be used with <audio> and <video> element. Example 1: Here the autoplay attribute is used with the <video> tag.  
html
<!DOCTYPE html><html> <head>    <title>HTML video autoplay Attribute</title></head> <body>    <center>        <h1 style="color:green;">GeeksforGeeks</h1>         <h3>HTML video autoplay Attribute</h3>         <video width="400" height="200" controls autoplay>            <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4"                    type="video/mp4">            <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg"                    type="video/ogg">        </video>    </center></body> </html>
Output:  
Example 2: Here the autoplay attribute is used with the <audio> tag.  
html
<!DOCTYPE html><html> <head>    <title>        HTML audio autoplay Attribute    </title></head> <body style="text-align: center">     <h1 style="color: green">        GeeksforGeeks    </h1>     <h2>HTML audio autoplay Attribute</h2>     <audio controls autoplay>        <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg"                        type="audio/ogg">        <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3"                    type=" audio/mpeg ">    </audio></body> </html>       
Output:  
Supported Browsers: The browser supported by HTML autoplay attributes are listed below:  
Google Chrome 3.0 and above
Internet Explorer 9.0
Firefox 3.5 and above
Safari 3.1 and above
Opera 10.5 and above
Edge 12 and above
 
hritikbhatnagar2182
kumargaurav97520
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a column to row name/index in Pandas

16 Jul, 2021
Pandas provide a convenient way to handle data and its transformation. Let’s see how can we convert a column to row name/index in Pandas. 
Create a dataframe first with dict of lists. 
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80","90","60", "30", "50"],       'Result': ["Pass","Pass","Pass","Fail","Fail"]} # creating a dataframedf = pd.DataFrame(data)  df
Output: 
Method #1: Using set_index() method. 
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80","90","60", "30", "50"],       'Result': ["Pass","Pass","Pass","Fail","Fail"]} # Creating a dataframedf = pd.DataFrame(data) # Using set_index() method on 'Name' columndf = df.set_index('Name') df
Output: 
Now, set index name as None.  
Python3
# set the index to 'None' via its name propertydf.index.names = [None] df
Output: 
Method #2: Using pivot() method.In order to convert a column to row name/index in dataframe, Pandas has a built-in function Pivot.Now, let’s say we want Result to be the rows/index, and columns be name in our dataframe, to achieve this pandas has provided a method called Pivot. Let us see how it works,
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80", "90", "60", "30", "50"],       'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]} df = pd.DataFrame(data) # pivoting the dataframedf.pivot(index ='Result', columns ='name') df
Output: 
 
surindertarika1234
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Find the Nth highest value of a vector in R

27 Jan, 2022
In this article, we will see how to find the Nth largest value of a vector in the R Programming Language.
Steps for finding nth largest element in vector R:
Step 1: Create a vector and take input from the user.
Syntax : variable name = readline()
Where 
Variable is the valid identifier.
readline() will take input from user.
Step 2: Convert our data from string to int.
Syntax: variable 1= as.integer(variable2);
Where
Variable1 is the valid identifier which will store integer value of variable 2
Variable 2 is string which is needed to convert to integer. 
Step 3: Finding nth largest number using 
Syntax: sort(vector name ,True) [n value])
Where 
Vector name is the vector that we created.
Here True is used as we needed this vector in descending order.
N value is which the largest number you want to print.
Example 1:
In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and nth largest element.Here we are passing True as we need it in descending order. 
R
a<- c(1000,3000,4000) x = readline(); # we are converting data from string to# int and storing in x.x = as.integer(x); # we are sorting vector and printing# nth element.As this vector is in sorted# way we will get xth largest numberprint(sort(a,TRUE)[x])
Output:
[1] 4000
Here user input is 1 so the output is 4000 as we need to find the first largest element.
Example 2: In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and yth the largest element.Here we are passing True as we need it in descending order. 
R
b<- c(1500, 334000, 33000) # we are storing value given by user into yy = readline(); # we are converting data from string to int and storing in y.y = as.integer(y); # we are sorting vector and printing yth element.# As this vector is in sorted way(descending order)# we will get yth largest numberprint(sort(b,TRUE)[y])
Output:
[1] 33000
Here user input is 2 so the output is 33000 as we need to find the second largest element.
as5853535
clintra
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
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?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Python – API.retweet() in Tweepy

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The API.retweet() method of the API class in Tweepy module is used to retweet a tweet.
Syntax : API.retweet(id)
Parameters :
id : The ID of the tweet which has to be retweeted.
Returns : an object of the class Status
Example 1 :Retweeting your own tweet. Retweet the following tweet :
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the tweet to be retweetedID =   # retweeting the tweetapi.retweet(ID)
Output :
Example 2 : Retweeting some other account’s tweet. Retweet the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet.
# the ID of the tweet to be retweetedID = 1263493041769394178  # retweeting the tweetapi.retweet(ID)
Output :
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
p5.js | textStyle() Function

16 Apr, 2019
The textStyle() function in p5.js is used to set or return the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC. This may be be overridden by CSS styling.
Syntax:
textStyle(style)
or
textStyle()
Parameters: This function accepts single parameter style which stores the styling Constant.
Below programs illustrate the textStyle() function in p5.js:
Example 1: This example uses textStyle() function to set the style of text.
function setup() {          // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          let string = "GeeksforGeeks";          // Set the background color    background(220);          // Set the text style    textStyle(ITALIC);          // Set the text size    textSize(16);          // Set the text     text(string, 20, 30);      // Set text styling    textStyle(BOLD);          text(string, 20, 70);      // Set text styling    textStyle(BOLDITALIC);          text(string, 20, 110);}
Output:
Example 2: This example uses textStyle() function to return the style of text.
function setup() {          // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          let string = "GeeksforGeeks";          // Set the background color    background(220);          // Set text style    textStyle(BOLD);          // Set the text size    textSize(16);      // Get the value of text style    var u = textStyle();          // Set the stroke color    stroke(255, 204, 0);          // Display the result    text("Value of Text Style is : " + u, 50, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/textStyle
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
How to get selected value from listbox in tkinter?

10 Jun, 2021
Prerequisites: Tkinter, Listbox
ListBox is one of the many useful widgets provided by Tkinter for GUI development. The Listbox widget is used to display a list of items from which a user can select one or more items according to the constraints. In this article, we’ll see how we can get the selected value(s) from a Listbox widget.
Code:
Python3
# Python3 program to get selected# value(s) from tkinter listbox # Import tkinterfrom tkinter import * # Create the root windowroot = Tk()root.geometry('180x200') # Create a listboxlistbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE) # Inserting the listbox itemslistbox.insert(1, "Data Structure")listbox.insert(2, "Algorithm")listbox.insert(3, "Data Science")listbox.insert(4, "Machine Learning")listbox.insert(5, "Blockchain") # Function for printing the# selected listbox value(s)def selected_item():         # Traverse the tuple returned by    # curselection method and print    # corresponding value(s) in the listbox    for i in listbox.curselection():        print(listbox.get(i)) # Create a button widget and# map the command parameter to# selected_item functionbtn = Button(root, text='Print Selected', command=selected_item) # Placing the button and listboxbtn.pack(side='bottom')listbox.pack() root.mainloop()
 
 
Output:
 
GUI window with output
 
Explanation: 
 
The curselection method on listbox returns a tuple containing the indices/line numbers of the selected item(s) of the listbox, starting from 0. The selected_item function that we made, traverses the tuple returned by the curselection method and prints the corresponding item of the listbox using the indices. It is executed when we press the “Print Selected” button.  In the case of no selected items, curselection method returns an empty tuple.
 
Note: You can change the selectmode parameter of the listbox widget to “SINGLE” for putting a constraint of choosing a single value only.
 
sumitgumber28
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
HTML DOM getAttribute() Method

22 Nov, 2021
In this article, we will learn about the HTML DOM getAttribute() method, along with understanding their implementation through the example.
HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.
Syntax:
Object.getAttribute(attributename)
Parameter value:
attributename: It is a required parameter with string type that specifies the name of the attribute that needs to retrieve the value.
Return value: It returns the value of a specified attribute on the element. It will return a null or an empty string if the specified attribute doesn’t exist.
Example 1: This example illustrates the DOM getAttribute() method that specifies the value of the attribute for the specified name, of an element.
HTML
<!DOCTYPE html><html> <head>    <title>DOM getAttribute() Method</title></head> <body>    <center>        <h1 style="color:green;width:50%;">            GeeksforGeeks        </h1>        <h2>DOM getAttribute() Method</h2>        <br>        <button id="button" onclick="geeks()">Submit</button>        <p id="gfg"></p>                  <script>        function geeks() {            var rk =            document.getElementById("button").getAttribute("onClick");            document.getElementById("gfg").innerHTML = rk;        }        </script>    </center></body> </html>
Output:
DOM getAttribute() Method
Example 2: This example illustrates the DOM getAttribute() method to retrieve the href attribute value of an element.
HTML
<!DOCTYPE html><html> <head>    <title>DOM getAttribute() Method</title></head> <body>    <center>        <h1 style="color:green;width:50%;">                GeeksforGeeks            </h1>        <h2>DOM getAttribute() Method</h2>        <a id="gfg" href="www.geeksforgeeks.com">          GeeksforGeeks        </a>        <br>        <br>        <button id="button" onclick="geeks()">Submit</button>        <br>        <p id="rk"></p>                  <script>        function geeks() {            var rk = document.getElementById("gfg").getAttribute("href");            document.getElementById("rk").innerHTML = rk;        }        </script>    </center></body> </html>
Output:
DOM getAttribute() Method
Supported Browsers: The browser supported by DOM getAttribute() method are listed below: 
Google Chrome 1.0
Internet Explorer 5.0
Microsoft Edge 12.0
Firefox 1.0
Opera 8.0
Safari 1.0
chhabradhanvi
bhaskargeeksforgeeks
HTML-DOM
HTML-Methods
Picked
Technical Scripter 2018
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js substr() function

14 Oct, 2021
The substr() function is a string function of Node.js which is used to extract sub-string from the given string.
Syntax:
string.substr(index, length)

Parameters: This function accepts two parameters as mentioned above and described below:
index: This parameter holds the starting index of the specified sub-string.
length: This parameter holds the length of sub-string.
Return Value: The function returns the sub-string from given string.
Below programs demonstrate the working of substr() function:
Program 1:
function findsubstr(str) {      var substring = str.substr(11, 13);          console.log(substring);}  var str = "Welcome to GeeksforGeeks";  findsubstr(str);
Output:
GeeksforGeeks
Program 2:
function findsubstr(str, index, length) {      var substring = str.substr(index, length);          console.log(substring);}  var str = "Welcome to GeeksforGeeks";  var index = 11, length = 13;  findsubstr(str, index, length);
Output:
GeeksforGeeks
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React