code-rag-bench/online-tutorials huggingface dataset:
Java Examples - Getting connected to Server

How to get connected with web server ?
Following example demonstrates how to get connected with web server by using sock.getInetAddress() method of net.Socket class.
import java.net.InetAddress;
import java.net.Socket;

public class WebPing {
   public static void main(String[] args) {
      try {
         InetAddress addr;
         Socket sock = new Socket("www.javatutorial.com", 80);
         addr = sock.getInetAddress();
         System.out.println("Connected to " + addr);
         sock.close();
      } catch (java.io.IOException e) {
         System.out.println("Can't connect to " + args[0]);
         System.out.println(e);
      }
   }
}
The above code sample will produce the following result.
Connected to www.javatutorial.com/69.172.201.153

 Print
 Add Notes
 Bookmark this page
How to Set the X and the Y Limit in Matplotlib with Python?

02 Dec, 2020
Prerequisites : Matplotlib
In this article, we will learn how to set the X limit and Y limit in matplotlib with Python. Before that some concepts need to be familiarized with:
Python : Python is a high-level, general-purpose and a very popular programming language. It is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. 
Matplotlib : Matplotlib is a visualization library in supported by Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
xlim() : It is a function in pyplot module of matplotlib library which is used to get or set the x-limits of the current axes.
ylim() : It is a function in pyplot module of matplotlib library which is used to get or set the y-limits of the current axes.
Import Library 
Load or create data
Plot a graph
Use xlim() / ylim() or both.
Let’s discuss these steps with the help of some examples :
Example 1: (By using xlim() method)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(-10, 10, 1000)y = np.sin(x)  # plot the graphplt.plot(x, y)  # limit x by -5 to 5plt.xlim(-5, 5)
Output :
Simple Plot
X limited Plot
Example 2: (By using ylim() method)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(-10, 10, 1000)y = np.cos(x)  # plot the graphplt.plot(x, y)  # limit y by 0 to 1plt.ylim(0, 1)
Output :
Simple Plot
Y Limited Plot
Example 3: (Using both xlim() and ylim() methods)
Python3
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax = np.linspace(-10, 10, 20)y = x  # plot the graphplt.plot(x, y)  # limited to show positive axesplt.xlim(0)plt.ylim(0)
Output :
Simple Plot
X and Y Limited Plot
Python-matplotlib
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to Add All Items From a Collection to an ArrayList in Java?

18 Nov, 2021
Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java.
Illustrations: 
Input: Collection = [1, 2, 3] 
Output: ArrayList = [1, 2, 3]
Input: Collection = [GFG, Geek, GeeksForGeeks] 
Output: ArrayList = [GFG, Geek, GeeksForGeeks] 
Approach:
Get the Collection whose items are to be added into the ArrayListCreate an ArrayListAdd all the items of Collection into this ArrayList using ArrayList.addAll() methodArrayList with all the items of Collections have been created.
Get the Collection whose items are to be added into the ArrayList
Create an ArrayList
Add all the items of Collection into this ArrayList using ArrayList.addAll() method
ArrayList with all the items of Collections have been created.
Example
Java
// Java Program to Add All Items from a collection// to an ArrayList // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classclass GFG {     // Method 1    // To add all items from a collection    // to an ArrayList    public static <T> ArrayList<T>    createArrayList(List<T> collection)    {         // Creating an ArrayList        ArrayList<T> list = new ArrayList<T>();         // Adding all the items of Collection        // into this ArrayList        list.addAll(collection);         return list;    }     // Method 2    // Main driver method    public static void main(String[] args)    {         // Getting array elements as list        // and storing in a List object        List<Integer> collection1 = Arrays.asList(1, 2, 3);         // Printing elements in above List object        System.out.println("ArrayList with all "                           + "elements of collection "                           + collection1 + ": "                           + createArrayList(collection1));         // Again creating another List class object        List<String> collection2 = Arrays.asList(            "GFG", "Geeks", "GeeksForGeeks");         // Printing elements in above List object        System.out.println("ArrayList with all"                           + " elements of collection "                           + collection2 + ": "                           + createArrayList(collection2));    }}
ArrayList with all elements of collection [1, 2, 3]: [1, 2, 3]
ArrayList with all elements of collection [GFG, Geeks, GeeksForGeeks]: [GFG, Geeks, GeeksForGeeks]
solankimayank
Java-ArrayList
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | shell_exec() vs exec() Function

31 Jul, 2021
shell_exec() Function
The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.
Syntax:
string shell_exec( $cmd )
Parameters: This function accepts single parameter $cmd which is used to hold the command that will be executed.
Return Value: This function returns the executed command or NULL if an error occurred.
Note: This function is disabled when PHP is running in safe mode.
Example:
<?php  // Use ls command to shell_exec// function$output = shell_exec('ls');  // Display the list of all file// and directoryecho "<pre>$output</pre>";?>
Output:
gfg.php
index.html
geeks.php
exec() Function
The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.
Syntax:
string exec( $command, $output, $return_var )
Parameters: This function accepts three parameters as mentioned above and described below:
$command: This parameter is used to hold the command which will be executed.
$output: This parameter is used to specify the array which will be filled with every line of output from the command.
$return_var: The $return_var parameter is present along with the output argument, then it returns the status of the executed command will be written to this variable.
Return Value: This function returns the executed command, be sure to set and use the output parameter.
Example:
<?php// (on a system with the "iamexecfunction" executable in the path)echo exec('iamexecfunction');?>
Output:
geeks.php
References:
http://php.net/manual/en/function.shell-exec.php
http://php.net/manual/en/function.exec.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find all elements in a given array except for the first one using JavaScript ?

18 Aug, 2021
In this article, we will learn how to find all elements in a given array except for the first one.
Method 1: Using for loopIn this method, we will use a for loop to grab all the elements except first. We know that in an array the first element is present at index ‘0’. We will run a loop from 1 to array.length and saving those remaining elements to another array.
Example:
Javascript
<script>    //Javascript program to find all    //element of an array except first     //function which takes an array as argument    const print = (arr) => {         //creating a dummy array to store result        const find = []         //a counter for adding result        let k = 0         for (let i = 1; i < arr.length; i++) {            find[k] = arr[i]            k++        }        //returning resultant array        return find    }     //input array    const arr = [1, 2, 3, 4, 5]     //printing the result    console.log(print(arr))</script>
Output:
[ 2, 3, 4, 5 ]
Method 2: Using slice() method
The slice()It is a method that returns a slice of an array. It takes two arguments, the start and end index.
Example: 
Javascript
<script>    //Javascript program to find all    //element of array except first     //function which takes an array as argument    const print = (arr) => {         //returning resultant array        return arr.slice(1)    }     //input array    const arr = [10, 20, 30, 40, 50]    //printing the result    console.log(print(arr))</script>
Output :
[20, 30, 40, 50]
arorakashish0911
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
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 ?
SQL Query to Remove Decimal Values

23 Sep, 2021
Decimal values are those values that have “float” as a datatype.
There are various methods to remove decimal values in SQL:
Using ROUND() function: This function in SQL Server is used to round off a specified number to a specified decimal places
Using FLOOR() function: It returns the largest integer value that is less than or equal to a number. 
Using CAST() function: The explicit conversion has to be done in SQL Server using Cast or Convert function.
STEP 1: Creating a database
Use the below SQL statement to create a database called geeks:
Query: 
CREATE DATABASE geeks;
Step 2:  Using the database 
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have the following geeks for geeks table in our geek’s database.
Query:
CREATE TABLE geeksforgeeks(
NAME VARCHAR(10),
MARKS float);
Step 4: Insert data into a table
Query:
INSERT INTO geeksforgeeks VALUES ('ROMY',80.9),('MEENAKSHI',86.89),('SHALINI',85.9),('SAMBHAVI', 89.45);
Step 5:Check value of the table
Content of the table can be viewed using the SELECT command.
Query:
SELECT * FROM geeksforgeeks;
Step 6:Use function to remove decimal values
ROUND(): This function rounds a number to the specified decimal places. If we want to remove all the decimal values, we will round it to decimal place 0.
Syntax:
ROUND(Value, decimal_place)
Query:
SELECT NAME, ROUND(MARKS,0) AS MARKS FROM geeksforgeeks;
Output:
80.0 is rounded to 81 as 81 is the nearest integer value.
FLOOR(): This function returns the largest integer value which is less than or equal to the value used as a parameter.
Syntax:
 FLOOR(value)
Query:
SELECT NAME, FLOOR(MARKS) AS MARKS FROM geeksforgeeks;
Output:
Here, 80.9 gets converted to 80, as FLOOR() returns a value less than or equal to the given value but can not return the value greater than the given one. 
CAST(): This function is used to convert the value into a specific data type.
Syntax:
CAST( value as datatype)
Query:
SELECT NAME, CAST(MARKS as INT) AS MARKS FROM geeksforgeeks;
Output:
This gives results similar to the FLOOR() function. Results vary slightly according to the function used. One should choose according to the need.
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Consensus Problem of Distributed Systems
Scraping Reddit using Python
Ccat – Colorize Cat Command Output command in Linux with Examples
Wired Communication Media
How to Build a Simple Auto-Login Bot with Python
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
Difference between DELETE, DROP and TRUNCATE
CTE in SQL
How to Fix: NameError name ‘pd’ is not defined

28 Nov, 2021
In this article we will discuss how to fix NameError pd is not defined in Python.
When we imported pandas module without alias and used pd in the code, the error comes up.
Example: Code to depict error
Python3
# import pandas moduleimport pandas  # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})  # displaydata
Output:
—————————————————————————
NameError                                 Traceback (most recent call last)
<ipython-input-1-a37aacbaa7a7> in <module>()
      3 
      4 #create dataframe
—-> 5 data=pd.DataFrame({‘a’:[1,2],’b’:[3,4]})
      6 
      7 #display
NameError: name ‘pd’ is not defined
Here pd is an alias of the pandas module so we can either import pandas module with alias or import pandas without the alias and use the name directly.
we can use alias at the time of import to resolve the error
Syntax:
import pandas as pd
Example: Program to import pandas as alias
Python3
# import pandas moduleimport pandas as pd  # create dataframedata = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})  # displaydata
Output:
    a    b
0    1    3
1    2    4
We can use pandas module directly to use in a data structure.
Syntax:
import pandas
Example: Using Pandas directly
Python3
# import pandas moduleimport pandas  # create dataframedata = pandas.DataFrame({'a': [1, 2], 'b': [3, 4]})  # displaydata
Output:
    a    b
0    1    3
1    2    4
Picked
Python How-to-fix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Find Size of an Array in C/C++ Without Using sizeof() Operator?

23 May, 2022
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown:
// Finds size of arr[] and stores in 'size'
int size = sizeof(arr)/sizeof(arr[0]);
Can we do the same without using the sizeof() operator? 
Given an array (you don’t know the type of elements in the array), find the total number of elements in the array without using the sizeof() operator?
Approach 1: Implement our own sizeof
CPP
// C++ program to find size of// an array by writing our// own sizeof operator#include <bits/stdc++.h>using namespace std;  // User defined sizeof macro# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))  int main(){    int arr[] = {1, 2, 3, 4, 5, 6};    int size = my_sizeof(arr)/my_sizeof(arr[0]);      cout << "Number of elements in arr[] is "        << size;      return 0;}
Output:
Number of elements in arr[] is 6
Approach 2: Using a pointer hack
 The following solution is very short when compared to the above solution. The number of elements in an array A can be found using the expression:
int size = *(&arr + 1) - arr; // &arr returns a pointer 
CPP
// C++ program to find size // of an array by using a // pointer hack#include <bits/stdc++.h>using namespace std;  int main(){    int arr[] = { 1, 2, 3, 4, 5, 6 };    int size = *(&arr + 1) - arr;    cout << "Number of elements in arr[] is " << size;    return 0;}
Output:
Number of elements in arr[] is 6
How does this work? 
Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations to character pointers.
&arr – Pointer to an array of 6 elements. [See this for difference between &arr and arr]
(&arr + 1) – Address of 6 integers ahead as pointer type is a pointer to an array of 6 integers. In simple words, (&arr + 1) is the address of integers ahead.
*(&arr + 1) – Same address as (&arr + 1), but type of pointer is “int *”.
*(&arr + 1) – arr – Since *(&arr + 1) points to the address 6 integers ahead of arr, the difference between two is 6.
This article is contributed by Nikhil Chakravartula. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
harsh_shokeen
cpp-array
cpp-operator
cpp-sizeof
C Language
C++
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.ndarray.itemsize() method | Python

26 Mar, 2020
numpy.ndarray.itemsize() function return the length of one array element in bytes.
Syntax : numpy.ndarray.itemsize(arr)
Parameters :arr : [array_like] Input array.
Return : [int] The length of one array element in bytes
Code #1 :
# Python program explaining# numpy.ndarray.itemsize() function  # importing numpy as geek import numpy as geek  arr = geek.array([1, 2, 3, 4], dtype = geek.float64)  gfg = arr.itemsize  print (gfg)
Output :
8

 Code #2 :
# Python program explaining# numpy.ndarray.itemsize() function  # importing numpy as geek import numpy as geek  arr = geek.array([1, 2, 3, 4],  dtype = geek.complex128)  gfg = arr.itemsize  print (gfg)
Output :
16

Python numpy-ndarray
Python-numpy
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
GATE | GATE-CS-2015 (Set 1) | Question 20 - GeeksforGeeks

28 Jun, 2021
Which of the following is/are correct inorder traversal sequence(s) of binary search tree(s)?
1. 3, 5, 7, 8, 15, 19, 25
2. 5, 8, 9, 12, 10, 15, 25
3. 2, 7, 10, 8, 14, 16, 20
4. 4, 6, 7, 9, 18, 20, 25 
(A) 1 and 4 only(B) 2 and 3 only(C) 2 and 4 only(D) 2 onlyAnswer: (A)Explanation: An Inorder traversal of a Binary Search Tree must be in increasing order.Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Basics of Docker Networking - GeeksforGeeks

31 Oct, 2020
Docker Networking allows you to create a Network of Docker Containers managed by a master node called the manager. Containers inside the Docker Network can talk to each other by sharing packets of information. In this article, we will discuss some basic commands that would help you get started with Docker Networking.
The Docker Network command is the main command that would allow you to create, manage, and configure your Docker Network. Let’s see what are the sub-commands that can be used with the Docker Network command.
sudo docker network

We will see all the Network sub-commands one by one.
The Create sub-command allows you to create a Docker Network. 
sudo docker network create --driver <driver-name> <bridge-name>

Using Connect sub-command, you can connect a running Docker Container to an existing Network.
sudo docker network connect <network-name> <container-name or id>

In this example, we will connect an Ubuntu Container to the Bridge Network we created in the last step.
Using the Network Inspect command, you can find out the details of a Docker Network.
sudo docker network inspect <network-name>

You can also find the list of Containers that are connected to the Network.
To list all the Docker Networks, you can use the list sub-command.
sudo docker network ls

The disconnect sub-command can be used to remove a Container from the Network.
sudo docker network disconnect <network-name> <container-name>

You can remove a Docker Network using the rm sub-command.
sudo docker network rm <network-name>

Note that if you want to remove a network, you need to make sure that no container is currently referencing the network.
To remove all the unused Docker Networks, you can use the prune sub-command. 
sudo docker network prune

Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Getting Started with System Design
Deep Learning | Introduction to Long Short Term Memory
How to create Hex color generator using HTML CSS and JavaScript ? - GeeksforGeeks

03 Feb, 2021
Hex color is a six-digit code representing the amount of red, green, and blue that makes up the color. Hex color generator gives the hex code of selected color.
Approach:
To select a color, we will use <input type=”color”> which creates a color picker.Get the value returned by color picker.(Color picker returns hex value)Set the color as background and display the hex code.
To select a color, we will use <input type=”color”> which creates a color picker.
Get the value returned by color picker.(Color picker returns hex value)
Set the color as background and display the hex code.
HTML
<!DOCTYPE html><html>  <head>    <title>Hex color generator</title>      <style>        body {            margin: 0;            padding: 0;            display: grid;            place-items: center;            height: 100vh;            font-size: 20px;        }                  .main {            height: 400px;            width: 250px;            background: #3A3A38;            border-radius: 10px;            display: grid;            place-items: center;            color: #fff;            font-family: verdana;            border-radius: 15px;        }                  #colorPicker {            background-color: none;            outline: none;            border: none;            height: 40px;            width: 60px;            cursor: pointer;        }                  #box {            outline: none;            border: 2px solid #333;            border-radius: 50px;            height: 40px;            width: 120px;            padding: 0 10px;        }    </style></head>  <body>    <h1>Hex Color Generator</h1>      <div class="main">          <!-- To select the color -->        Color Picker: <input type="color"             id="colorPicker" value="#6a5acd">          <!-- To display hex code of the color -->        Hex Code: <input type="text" id="box">    </div>      <script>        function myColor() {              // Get the value return by color picker            var color = document.getElementById('colorPicker').value;              // Set the color as background            document.body.style.backgroundColor = color;              // Take the hex code            document.getElementById('box').value = color;        }          // When user clicks over color picker,        // myColor() function is called        document.getElementById('colorPicker')            .addEventListener('input', myColor);    </script></body>  </html>
Output:
CSS-Questions
HTML-Questions
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to Remove All Directories and Files in Golang? - GeeksforGeeks

23 Mar, 2020
In Go language, you are allowed to remove all the directories and files from a directory or folder with the help of RemoveAll() function. This function removes all the directories and files from the path you will pass to this function. It will remove everything from the specified path, but returns the first error it encounters. If the specified path does not exist, then this method returns nil. If this method throws an error, then it will be of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing RemoveAll() function.
Syntax:
func RemoveAll(path string) error
Example 1:
// Golang program to illustrate how to // remove all the files and directories// from the default directorypackage main  import (    "log"    "os")  func main() {      // Remove all the directories and files    // Using RemoveAll() function    err := os.RemoveAll("/Users/anki/Documents/go")    if err != nil {        log.Fatal(err)    }}
Output:
Before:
After:
Example 2:
// Golang program to illustrate how to remove// all the files and directories from the// new directorypackage main  import (    "log"    "os")  func main() {      // Remove all the directories and files    // Using RemoveAll() function    err := os.RemoveAll("/Users/anki/Documents/new_folder/files")    if err != nil {        log.Fatal(err)    }}
Output:
Before:
After:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
Draw a line on an image using OpenCV

In this program, we will draw a simple line on an image using the OpenCV function line().
Step 1: Import cv2.
Step 2: Read the image using imread().
Step 3: Get the dimensions of the image using the image.shape method.
Step 4: Define starting point of the line.
Step 5: Define the end point of the line.
Step 6: Define the thickness of the line.
Step 7: Draw the line using the cv2.line() function and pass Step 3 to Step 4 as parameters.
import cv2

image = cv2.imread('testimage.jpg')
height, width, channels = image.shape
startpoint = (0, 0)
endpoint = (height, width)
thickness = 9
color = (255, 0, 0)
image = cv2.line(image, startpoint, endpoint, color, thickness)
cv2.imshow('Line', image)
As you can see, a blue line is drawn on the image.
Using User-Defined Variables in MySQL

Let us understand what user variables are and how they can be used in MySQL. We will also see the rules −
User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $.
User variables are written as @var_name. Here, the ‘var_name’ refers to variable name, which consists of alphanumeric characters, ., _, and $.
A user variable name can contain other characters if they are quoted as a string or identifier.
A user variable name can contain other characters if they are quoted as a string or identifier.
User-defined variables are session specific.
User-defined variables are session specific.
A user variable which is defined by one client can’t be seen or used by other clients.
A user variable which is defined by one client can’t be seen or used by other clients.
But the only exception is that if a user has access to the Performance Schema
user_variables_by_thread table, then that user can see all user variables for all sessions.All variables for a given client session are automatically made free when that client exits.User variable names are not case-sensitive. The names have a maximum length of 64
characters.
But the only exception is that if a user has access to the Performance Schema
user_variables_by_thread table, then that user can see all user variables for all sessions.
All variables for a given client session are automatically made free when that client exits.
User variable names are not case-sensitive. The names have a maximum length of 64
characters.
One way to set a user-defined variable is by issuing a SET statement. Let us see how it can be done using the below command −
SET @var_name = expr [, @var_name = expr] ...
While using SET, use either = or := as the assignment operator.
User variables can be assigned a value from a limited set of data types. These include integer, decimal, floating-point, binary or nonbinary string, or NULL value.
Assignment of decimal and real values won’t preserve the precision or scale of the value.
Assignment of decimal and real values won’t preserve the precision or scale of the value.
A value of a type other than which is permissible gets converted to a permissible type.
A value of a type other than which is permissible gets converted to a permissible type.
This is the same coercibility that is used for table column values.
This is the same coercibility that is used for table column values.
MySQL user variables can be used to remember results without storing them in temporary variables in the client.
MySQL user variables can be used to remember results without storing them in temporary variables in the client.
They are used to store data without explicitly assigning a memory location to them.
They are used to store data without explicitly assigning a memory location to them.
Difference between datetime and datetime-local in HTML5

A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.
Let us see an example:
<!DOCTYPE HTML>
<html>
   <body>
      <form action = "/cgi-bin/html5.cgi" method = "get">
         Date and Time : <input type = "datetime" name = "newinput" />
         <input type = "submit" value = "submit" />
      </form>
   </body>
</html>
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information.
Let us see an example:
<!DOCTYPE HTML>
<html>
   <body>
      <form action = "/cgi-bin/html5.cgi" method = "get">
         Local Date and Time : <input type = "datetime-local" name = "newinput" />
         <input type = "submit" value = "submit" />
      </form>
   </body>
</html>
How to check if a file already exists in R ? - GeeksforGeeks

08 May, 2021
In this article, we will discuss how to check if a file already exists or not using R Programming Languague.
Directory in use:
The function file.exists() returns a logical vector indicating whether the file mentioned in the function existing or not. 
Note: Make sure that to provide a file path for those, not in the current working directory.
Syntax: File.exists(“file_path”)
Return value: The function file.exists() returns a logical vector indicating whether the files named by its argument exist.
TRUE- file exists
FALSE- file does not  exists
Example:
R
file.exists("Akshit.R")
Output:
[1] TRUE
Example 2:
R
file.exists("GFG.R")
Output:
[1] FALSE
This function can also be used to check whether the file is existing or not.
Syntax: file_test(op, x, y)
Parameter:
op: a character string specifying the test to be performed. Unary tests (only x is used) are “-f” (existence and not being a directory), “-d” (existence and directory) and “-x” (executable as a file or searchable as a directory). Binary tests are “-nt” (strictly newer than, using the modification dates) and “-ot” (strictly older than): in both cases the test is false unless both files exist.
x, y: character vectors giving file paths.
Returns: The function file_test() returns a logical vector indicating whether the files named by its argument exist.
TRUE- file exists
FALSE- file does not  exists
Example
R
#"-f" (existence and not # being a directory)file_test("-f","Akshit.R")
Output
[1] TRUE
Example 2:
R
file_test("-f","GFG.R") 
Output
[1] TRUE
Picked
R-FileHandling
R Language
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?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
EasyGUI – Text Box - GeeksforGeeks

14 Mar, 2022
Text Box : It is used to show and get the text to/from the user, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to enter text but used to show large text and it word-wrap the given text, below is how the enter box looks like  
 
In order to do this we will use textbox methodSyntax : textbox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed  
Example : In this we will create a text box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation  
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # long texttext = ["EasyGUI is a module for very simple, very easy GUI ","programming in Python. EasyGUI is different from other","GUI generators in that EasyGUI is NOT event-driven."]         # creating a multi password boxoutput = textbox(message, title, text) # showing the outputprint("Altered Text ")print("================")print(output)
Output :  
 
Altered Text 
================
EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from otherGUI generators in that EasyGUI is NOT event-driven. geeksforgeeks
Another Example : In this we will create a text box without any editable text, and will show the specific text on the screen according to the altered text, below is the implementation  
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG"          # creating a multi password boxoutput = textbox(message, title) # showing the outputprint("Altered Text ")print("================")print(output)
Output :  
 
Altered Text 
================
Welcome to geeksforgeeks ajkbkjbajxblcblc;c
 
sumitgumber28
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to merge rows in MySQL?

To merge rows in MySQL, use GROUP_CONCAT().
Let us first create a table−
mysql> create table DemoTable734 (
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command−
mysql> insert into DemoTable734 values(101,'John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable734 values(102,'John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable734 values(103,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement−
mysql> select *from DemoTable734;
This will produce the following output -
+------+-------+
| Id   | Name  |
+------+-------+
| 101  | John  |
| 102  | John  |
| 103  | Chris |
| 104  | Chris |
| 104  | Chris |
+------+-------+
5 rows in set (0.00 sec)
Following is the query to merge rows−
mysql> select Name,group_concat(Distinct Id SEPARATOR ',') from DemoTable734 group by Name;
This will produce the following output -
+-------+-----------------------------------------+
| Name  | group_concat(Distinct Id SEPARATOR ',') |
+-------+-----------------------------------------+
| Chris | 103,104                                 |
| John  | 101,102                                 |
+-------+-----------------------------------------+
2 rows in set (0.04 sec)
Python | os.getpid() method

06 Nov, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getpid() method in Python is used to get the process ID of the current process.
Syntax: os.getpid()
Parameter: Not required
Return Type: This method returns a integer value denoting process ID of current process. The return type of this method is of class ‘int’.
Code #1: use of os.getpid() method
# Python program to explain os.getpid() method     # importing os module import os  # Get the process ID of# the current processpid = os.getpid()    # Print the process ID of# the current processprint(pid) 
2699

Akanksha_Rai
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
How to Pass Additional Context into a Class Based View (Django)?

02 Nov, 2021
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one.
Explanation:
Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in django.

       How to Create Basic Project using MVT in Django?
       How to Create an App in Django ?
Inside the models.py add the following code:
Python3
from django.db import models # Create your models here.class YourModel(models.Model):    first_name = models.CharField(max_length=30)    last_name = models.CharField(max_length=30)    def __str__(self):        return self.first_name
After creating this model, we need to run two commands in order to create database for the same.
python manage.py makemigrations
python manage.py migrate
Create the folder named templates inside the app directory(geeks) , inside this folder add the file named Intro.html and add the following code:
HTML
<!-- Intro.html --><!DOCTYPE html><html lang="en" dir="ltr">  <head>    <meta charset="utf-8">    <title>Intro</title>  </head>  <body>    <h1>All users name </h1>    {% for user in users %}    {{user.first_name}}    {% endfor %}  </body></html>
Inside the views.py file  add the following code:
Python3
from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView):    template_name = 'Intro.html'    def get_context_data(self,*args, **kwargs):        context = super(Intro, self).get_context_data(*args,**kwargs)        context['users'] = YourModel.objects.all()        return context
Inside the urls.py file of project named geeksforgeeks add the following code:
Python3
from django.contrib import adminfrom django.urls import pathfrom geeks.views import Intro urlpatterns = [    path('admin/', admin.site.urls),    path('',Intro.as_view(),name="intro")]
Rewrite the views.py flle by adding the following code:
Python3
from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView):    template_name = 'Intro.html'    extra_context={'users': YourModel.objects.all()}
By both the methods you will see the same output. Let’s check what is there on http://localhost:8000/, before doing this don’t forget to add some data to your model.
How to add data to your model
   Django ORM – Inserting, Updating & Deleting Data
sumitgumber28
Django-views
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.openSync() Method

11 Oct, 2021
The fs.openSync() method is an inbuilt application programming interface of fs module which is used to return an integer value that represents the file descriptor.
Syntax:
fs.openSync( path, flags, mode )
Parameters: This method accepts three parameters as mentioned above and described below:
path: It holds the path of the file. It is of type string, Buffer, or URL.
flags: It holds either a string or a number value. Its default value of it is ‘r’.
mode: It holds either a string or an integer value and its default value of it is 0o666.
Return Value: It returns a number which represents the file descriptor.
Below examples illustrate the use of fs.openSync() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // fs.openSync() method    // Including fs modulevar fs = require('fs');  // Defining filenamevar filename = './myfile';  // Calling openSync method// with its parametersvar res = fs.openSync(filename, 'r');  // Prints outputconsole.log(res);
Output:
23

Here, the flag ‘r’ indicates that the file is already created and it reads the created file.
Example 2:
// Node.js program to demonstrate the     // fs.openSync() method    // Including fs modulevar fs = require('fs');  // Defining pathvar path = require('path');  // Calling openSync method with// all its parametersvar fd = fs.openSync(path.join(    process.cwd(), 'input.txt'), 'w', 0o666);  // This will append the content// of file created abovefs.writeSync(fd, 'GeeksforGeeks');  // Setting timeoutsetTimeout(function () {    // Its printed after the file is closed  console.log('closing file now');    // closing file descriptor  fs.closeSync(fd);}, 10000);console.log("Program done!");
Output:
Program done!
closing file now

Here, the flag ‘w’ indicates that the file is created or overwritten.
Reference: https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Installation of Node.js on Windows
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
Python String rfind() Method

19 Aug, 2021
Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1.
Syntax: 
str.rfind(sub, start, end)
Parameters: 
sub: It’s the substring that needs to be searched in the given string. 
start: Starting position where the sub needs to be checked within the string. 
end: Ending position where suffix needs to be checked within the string. 
Note: If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
Return: 
Returns the highest index of the substring if it is found in the given string; if not found, then it returns -1.
Exception: 
ValueError: This error is raised in the case when the argument string is not found in the target string.
Python3
# Python program to demonstrate working of rfind()# in whole stringword = 'geeks for geeks'  # Returns highest index of the substringresult = word.rfind('geeks')print ("Substring 'geeks' found at index :", result )  result = word.rfind('for')print ("Substring 'for' found at index :", result )  word = 'CatBatSatMatGate'  # Returns highest index of the substringresult = word.rfind('ate')print("Substring 'ate' found at index :", result)
Output: 
Substring 'geeks' found at index : 10
Substring 'for' found at index : 6
Substring 'ate' found at index : 13
Python3
# Python program to demonstrate working of rfind()# in a sub-stringword = 'geeks for geeks'  # Substring is searched in 'eeks for geeks'print(word.rfind('ge', 2))  # Substring is searched in 'eeks for geeks' print(word.rfind('geeks', 2))  # Substring is searched in 'eeks for geeks' print(word.rfind('geeks ', 2))  # Substring is searched in 's for g'print(word.rfind('for ', 4, 11))
Output: 
10
10
-1
6
Useful in string checking. To check if the given substring is present in some string or not. 
Python3
# Python program to demonstrate working of rfind()# to search a stringword = 'CatBatSatMatGate'  if (word.rfind('Ate') != -1):    print ("Contains given substring ")else:    print ("Doesn't contains given substring")
Output: 
Doesn't contains given substring
AmiyaRanjanRout
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?