code-rag-bench/online-tutorials huggingface dataset:
How to Check if PySpark DataFrame is empty? - GeeksforGeeks

30 May, 2021
In this article, we are going to check if the Pyspark DataFrame or Dataset is Empty or Not.
At first, let’s create a dataframe
Python3
# import modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, StringType  # defining schemaschema = StructType([    StructField('COUNTRY', StringType(), True),    StructField('CITY', StringType(), True),    StructField('CAPITAL', StringType(), True)])  # Create Spark Objectspark = SparkSession.builder.appName("TestApp").getOrCreate()  # Create Empty DataFrame with Schema.df = spark.createDataFrame([], schema)  # Show schema and datadf.printSchema()df.show(truncate=False)
Output:
We have Multiple Ways by which we can Check :
Method 1: isEmpty()
The isEmpty function of the DataFrame or Dataset returns true when the DataFrame is empty and false when it’s not empty. If the dataframe is empty, invoking “isEmpty” might result in NullPointerException.
Note : calling df.head() and df.first() on empty DataFrame returns java.util.NoSuchElementException: next on empty iterator exception.
Python3
print(df.head(1).isEmpty)print(df.first(1).isEmpty)print(df.rdd.isEmpty())
Output:
True
True
True
Method 2: count()
  It calculates the count from all partitions from all nodes
Code:
Python3
print(df.count() > 0)print(df.count() == 0)
False
True
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
HTML <data> Tag - GeeksforGeeks

17 Mar, 2022
The <data> element gives an address to a given content with a machine-readable translator. This element provides a machine-readable value for the processors and a human-readable value that rendered in the browser. 
Syntax: 
<data value=""> Contents... </data>
Attributes: This tag accepts a single attribute as mentioned above and described below.
value: It contains a single machine-readable translation of the content.
Note: If the content is a date or time-related content, then use <time> element instead of the data element.Example: 
HTML
<!DOCTYPE html><html>    <body>        <h1>GeeksforGeeks</h1>        <h2><data> Tag</h2>          <p>GeeksforGeeks Subject List:</p>          <ul>          <!-- data Tag starts here -->             <li><data value="009">Data Structure</data></li>             <li><data value="010">Algorithm</data></li>             <li><data value="011">HTML</data></li>             <li><data value="019">Operating System</data></li>             <li><data value="110">Computer Network</data></li>             <li><data value="111">DBMS</data></li>          <!-- data Tag ends here -->        </ul>    </body></html>
Output:  
Supported Browsers: 
Google Chrome 62.0
Internet Explorer
Apple Safari 10 and above
Firefox 22.0
Opera 49.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
arorakashish0911
shubhamyadav4
chhabradhanvi
HTML-Tags
Technical Scripter 2018
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
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 ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Python PIL | paste() and rotate() method - GeeksforGeeks

30 Dec, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities.
PIL.Image.Image.paste() method is used to paste an image on another image. This is where the new() method comes in handy.
Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None) OR image_object.paste(image_2, box=None, mask=None)Parameters: image_1/image_object : It the image on which other image is to be pasted. image_2: Source image or pixel value (integer or tuple). box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image.mask: An optional mask image. 
Python3
# Importing Image module from PIL packagefrom PIL import Image # creating a image object (main image)im1 = Image.open(r"C:\Users\Admin\Pictures\network.PNG") # creating a image object (image which is to be paste on main image)im2 = Image.open(r"C:\Users\Admin\Pictures\geeks.PNG") # pasting im2 on im1Image.Image.paste(im1, im2, (50, 125)) # to show specified imageim1.show()
Output: 
This method is used to rotate a given image to the given number of degrees counter clockwise around its centre.
Syntax: new_object = PIL.Image.Image.rotate(image_object, angle, resample=0, expand=0) OR new_object = image_object.rotate(angle, resample=0, expand=0)Either of the syntax can be usedParameters: image_object: It is the real image which is to be rotated. angle: In degrees counter clockwise. resample: An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbor), PIL.Image.BILINEAR (linear interpolation in a 2×2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4×4 environment). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST. expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image.Return Value: Returns a copy of rotated image.  
Python3
# Importing Image module from PIL packagefrom PIL import Imageimport PIL # creating a image object (main image)im1 = Image.open(r"C:\Users\Admin\Pictures\network.PNG") # rotating a image 90 deg counter clockwiseim1 = im1.rotate(90, PIL.Image.NEAREST, expand = 1) # to show specified imageim1.show()
Output: 
Images used –
 
 
sagar0719kumar
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python program to swap two elements in a list - GeeksforGeeks

14 May, 2021
Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list.Examples:  
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output : [19, 65, 23, 90]

Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
Output : [1, 5, 3, 4, 2]
Approach #1: Simple swap, using comma assignment Since the positions of the elements are known, we can simply swap the positions of the elements. 
Python3
# Python3 program to swap elements# at given positions # Swap functiondef swapPositions(list, pos1, pos2):         list[pos1], list[pos2] = list[pos2], list[pos1]    return list # Driver functionList = [23, 65, 19, 90]pos1, pos2  = 1, 3 print(swapPositions(List, pos1-1, pos2-1))
Output:  
[19, 65, 23, 90]
  Approach #2 : Using Inbuilt list.pop() function Pop the element at pos1 and store it in a variable. Similarly, pop the element at pos2 and store it in another variable. Now insert the two popped element at each other’s original position. 
Python3
# Python3 program to swap elements# at given positions # Swap functiondef swapPositions(list, pos1, pos2):         # popping both the elements from list    first_ele = list.pop(pos1)      second_ele = list.pop(pos2-1)        # inserting in each others positions    list.insert(pos1, second_ele)     list.insert(pos2, first_ele)          return list # Driver functionList = [23, 65, 19, 90]pos1, pos2  = 1, 3 print(swapPositions(List, pos1-1, pos2-1))
Output:  
[19, 65, 23, 90]
  Approach #3 : Using tuple variableStore the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those elements with pos2 and pos1 positions in that list. Now, both the positions in that list are swapped.  
Python3
# Python3 program to swap elements at# given positions # Swap functiondef swapPositions(list, pos1, pos2):     # Storing the two elements    # as a pair in a tuple variable get    get = list[pos1], list[pos2]          # unpacking those elements    list[pos2], list[pos1] = get          return list # Driver CodeList = [23, 65, 19, 90] pos1, pos2  = 1, 3print(swapPositions(List, pos1-1, pos2-1))
Output:  
[19, 65, 23, 90]
Vijay Sirra
inboxofanirban
user_suyp
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Double Pointer (Pointer to Pointer) in C - GeeksforGeeks

05 Dec, 2019
Prerequisite : Pointers in C and C++
We already know that a pointer points to a location in memory and thus used to store the address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.
How to declare a pointer to pointer in C?Declaring Pointer to Pointer is similar to declaring pointer in C. The difference is we have to place an additional ‘*’ before the name of pointer.Syntax:
int **ptr;    // declaring double pointers

Below diagram explains the concept of Double Pointers:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The above diagram shows the memory representation of a pointer to pointer. The first pointer ptr1 stores the address of the variable and the second pointer ptr2 stores the address of the first pointer.
Let us understand this more clearly with the help of the below program:
#include <stdio.h>  // C program to demonstrate pointer to pointerint main(){    int var = 789;      // pointer for var    int *ptr2;      // double pointer for ptr2    int **ptr1;      // storing address of var in ptr2    ptr2 = &var;          // Storing address of ptr2 in ptr1    ptr1 = &ptr2;          // Displaying value of var using    // both single and double pointers    printf("Value of var = %d\n", var );    printf("Value of var using single pointer = %d\n", *ptr2 );    printf("Value of var using double pointer = %d\n", **ptr1);      return 0;} 
Output:
Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789

This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cup_to_kohli_hi_laega
tony99019
C-Pointers
cpp-double-pointer
cpp-pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Converting Strings to Numbers in C/C++
Enumeration (or enum) in C
Command line arguments in C/C++
Python OpenCV: Capture Video from Camera - GeeksforGeeks

28 Jan, 2020
Python provides various libraries for image and video processing. One of them is OpenCV. OpenCV is a vast library that helps in providing various functions for image and video operations. With OpenCV, we can capture a video from the camera. It lets you create a video capture object which is helpful to capture videos through webcam and then you may perform desired operations on that video.
Steps to capture a video:
Use cv2.VideoCapture() to get a video capture object for the camera.
Set up an infinite while loop and use the read() method to read the frames using the above created object.
Use cv2.imshow() method to show the frames in the video.
Breaks the loop when the user clicks a specific key.
Below is the implementation.
# import the opencv libraryimport cv2    # define a video capture objectvid = cv2.VideoCapture(0)  while(True):          # Capture the video frame    # by frame    ret, frame = vid.read()      # Display the resulting frame    cv2.imshow('frame', frame)          # the 'q' button is set as the    # quitting button you may use any    # desired button of your choice    if cv2.waitKey(1) & 0xFF == ord('q'):        break  # After the loop release the cap objectvid.release()# Destroy all the windowscv2.destroyAllWindows()
Output:
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python
How to call function within function in C or C++ - GeeksforGeeks

02 May, 2020
When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function always acts as a driver function and calls other functions.
// C++ program to call a function in main#include <iostream>using namespace std;  // Function called inside mainint add(int num1, int num2){    return (num1 + num2);}  // Driver codeint main(){    int num1 = 12, num2 = 34;    cout << add(num1, num2);    return 0;}
46

We can also write function call as a parameter to function. In the below code, first add(num1, num2) is evaluated, let the result of this be r1. The add(r1, num3) is evaluated. Let the result of this be r2. Finally add(r2, num4) is evaluated and its result is printed.
// C++ program to call a function in main#include <iostream>using namespace std;  int add(int num1, int num2){    return (num1 + num2);}  int main(){    int num1 = 12, num2 = 34, num3 = 67, num4 = 12;      // The innermost add() is computed first, then middle    // add(), then the outermost add()    cout << add(add(add(num1, num2), num3), num4);      return 0;}
125

Another example of function calling function are as follows : –
#include <iostream>using namespace std;  int add(int num1, int num2);int sub(int num1, int num2);int mul(int num1, int num2);  int calculator(int num1, int num2, int option){    // calling add function within calculator function    if (option == 1) {        return add(num1, num2);     }      // calling sub function within calculator function    if (option == 2) {        return sub(num1, num2);     }      // calling mul function within calculator function    if (option == 3) {        return mul(num1, num2);     }    }  // function for adding two numbersint add(int num1, int num2) {    return (num1 + num2);}  // function for subtracting numbersint sub(int num1, int num2) {    return (num1 - num2);}  // function for multiplying two numberint mul(int num1, int num2) {    return (num1 * num2);}  int main(){    int num1 = 10, num2 = 5; // variable      // giving options for different     // calculation(add, sub, mul, div)    int option;      option = 1; // Assuming that user inputs 1          cout << calculator(num1, num2, option);      return 0;}
15

CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
How to convert factor levels into character in R?

To convert factor levels into character then we can use as.character function by accessing the column of the data frame that contain factor values. For example, if we have a data frame df which contains a factor column named as Gender then this column can be converted into character column as as.character(df$Gender).
 Live Demo
Consider the below data frame −
set.seed(121)
x1<−as.factor(sample(LETTERS[1:5],20,replace=TRUE))
x2<−rnorm(20,1,0.4)
df1<−data.frame(x1,x2)
df1
   x1   x2
1  D 0.7827428
2  D 0.5519596
3  D 0.3852095
4  D 0.3349047
5  A 1.1618117
6  C 0.4082440
7  A 1.5988801
8  C 0.9368104
9  C 1.0383650
10 E 0.2883935
11 D 0.3859827
12 E 1.5254714
13 D 1.2963078
14 A 0.2446046
15 E 0.4702711
16 B 1.1655974
17 B 0.9342977
18 C 0.9110071
19 A 1.3317495
20 B 1.6616840
str(df1)
'data.frame': 20 obs. of 2 variables:
$ x1: Factor w/ 5 levels "A","B","C","D",..: 4 4 4 4 1 3 1 3 3 5 ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...
Converting x1 to character column −
df1$x1<−as.character(df1$x1)
str(df1)
'data.frame': 20 obs. of 2 variables:
$ x1: chr "D" "D" "D" "D" ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...
Let’s have a look at another example −
 Live Demo
y1<−as.factor(sample(c("India","Canada","Russia"),20,replace=TRUE))
y2<−rpois(20,3)
df2<−data.frame(y1,y2)
df2
    y1   y2
1 Russia  4
2 Canada  1
3 India   5
4 India   3
5 India   3
6 Canada  3
7 Canada  1
8 Canada  1
9 Canada  0
10 India  4
11 Canada 4
12 Canada 5
13 Canada 3
14 India  3
15 Russia 4
16 India  4
17 Canada 3
18 Russia 7
19 India  2
20 Canada 3
str(df2)
'data.frame': 20 obs. of 2 variables:
$ y1: Factor w/ 3 levels "Canada","India",..: 3 1 2 2 2 1 1 1 1 2 ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...
Converting y1 to character column −
df2$y1<−as.character(df2$y1)
str(df2)
'data.frame': 20 obs. of 2 variables:
$ y1: chr "Russia" "Canada" "India" "India" ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...
Insert data from one table to another in MySQL?

To insert data from one table to another, use the INSERT INTO SELECT statement. Let us first create a table −
mysql> create table DemoTable1
   -> (
   -> Id int,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(101,'Adam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(102,'John');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | Adam      |
|  102 | John      |
+------+-----------+
2 rows in set (0.00 sec)
Following is the query to create the second table −
mysql> create table DemoTable2
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20)
   -> );
Query OK, 0 rows affected (0.42 sec)
Here is the query to insert data from one table to another in MySQL −
mysql> insert into DemoTable2(EmployeeId,EmployeeName) select Id,FirstName from DemoTable1;
Query OK, 2 rows affected (0.15 sec)
Records: 2 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|        101 | Adam         |
|        102 | John         |
+------------+--------------+
2 rows in set (0.00 sec)
org.json - XML

XML class provides static methods to convert a XML text into a JSONObject, and vice versa.
Following methods are covered in the example.
toJSONObject(String) − Converts a XML to JSONArray Object.
toJSONObject(String) − Converts a XML to JSONArray Object.
toString(JSONObject) − Gives a XML from a JSONObject Object.
toString(JSONObject) − Gives a XML from a JSONObject Object.
import org.json.JSONObject;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Details", JSONObject.NULL);

      //Convert a JSONObject to XML
      String xmlText = XML.toString(jsonObject);
      System.out.println(xmlText);

      //Convert an XML to JSONObject
      System.out.println(XML.toJSONObject(xmlText));
   }
}
<Active>true</Active><Details>null</Details><ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>
{"Active":true,"Details":null,"ID":1,"Fees":1000.21,"Name":"Robert"}


    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    107 Lectures 
     13.5 hours 

 Arnab Chakraborty

    75 Lectures 
     5 hours 

 Revathi Ramachandran

    14 Lectures 
     44 mins

 Zach Miller

    12 Lectures 
     54 mins

 Prof. Paul Cline, Ed.D

    54 Lectures 
     4 hours 

 Gilad James, PhD
 Print
 Add Notes
 Bookmark this page
MySQL - SUM Function

MySQL SUM function is used to find out the sum of a field in various records.
To understand SUM function, consider an employee_tbl table, which is having the following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to calculate total of all the dialy_typing_pages, then you can do so by using the following command −
mysql> SELECT SUM(daily_typing_pages)
   -> FROM employee_tbl;
+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
|          1610           |
+-------------------------+
1 row in set (0.00 sec)
You can take sum of various records set using GROUP BY clause. Following example will sum up all the records related to a single person and you will have total typed pages by every person.
mysql> SELECT name, SUM(daily_typing_pages)
   -> FROM employee_tbl GROUP BY name;
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack |           270           |
| Jill |           220           |
| John |           250           |
| Ram  |           220           |
| Zara |           650           |
+------+-------------------------+
5 rows in set (0.17 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Python - How to Concatenate Two or More Pandas DataFrames along columns?


To concatenate more than two Pandas DataFrames, use the concat() method. Set the axis parameter as axis = 1 to concatenate along columns. At first, import the required library −
import pandas as pd
Let us create the 1st DataFrame −
dataFrame1 = pd.DataFrame(
   {
      "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90],
   },
   index=[0, 1, 2],
)
Let us create the 2nd DataFrame −
dataFrame2 = pd.DataFrame(
   {
      "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180],
   },
   index=[3, 4, 5],
)
Let us create the 3rd DataFrame −
dataFrame3 = pd.DataFrame(
   {
      "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280],
   },
   index=[6, 7, 8],
)
Concatenate all the 3 DataFrames using concat() and set “axis=1” to concatenate along columns −
res = [dataFrame1, dataFrame2, dataFrame3]
pd.concat(res, axis=1))
Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90],
   },
   index=[0, 1, 2],
)

# DataFrame1
print"DataFrame1...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180],
   },
   index=[3, 4, 5],
)

# DataFrame2
print"DataFrame2...\n",dataFrame2

dataFrame3 = pd.DataFrame(
   {
      "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280],
   },
   index=[6, 7, 8],
)

# DataFrame3
print"DataFrame3...\n",dataFrame3

# concatenating more than 3 dataframes
# set "axis=1" for concatenation along columns
res = [dataFrame1, dataFrame2, dataFrame3]
print"\n Concatenating all the 3 DataFrames (along columns)...\n", pd.concat(res, axis=1)


This will produce the following output −
DataFrame1...
    Col1   Col2   Col3
0    10     40     70
1    20     50     80
2    30     60     90
DataFrame2...
    Col1   Col2   Col3
3   100    130    160
4   110    140    170
5   120    150    180
DataFrame3...
    Col1   Col2   Col3
6   200    230    260
7   210    240    270
8   220    250    280

Concatenating all the 3 DataFrames (along columns)...
   Col1   Col2   Col3   Col1   Col2   Col3   Col1   Col2   Col3
0  10.0   40.0   70.0   NaN    NaN    NaN    NaN    NaN    NaN
1  20.0   50.0   80.0   NaN    NaN    NaN    NaN    NaN    NaN
2  30.0   60.0   90.0   NaN    NaN    NaN    NaN    NaN    NaN
3  NaN    NaN    NaN    100.0  130.0  160.0  NaN    NaN    NaN
4  NaN    NaN    NaN    110.0  140.0  170.0  NaN    NaN    NaN
5  NaN    NaN    NaN    120.0  150.0  180.0  NaN    NaN    NaN
6  NaN    NaN    NaN    NaN    NaN    NaN    200.0  230.0  260.0
7  NaN    NaN    NaN    NaN    NaN    NaN    210.0  240.0  270.0
8  NaN    NaN    NaN    NaN    NaN    NaN    220.0  250.0  280.0
Interesting Examples of algorithms in everyday life - GeeksforGeeks

23 Aug, 2018
            Ever found shortest path from Place A to Place B on Google Maps? Ever rolled a dice just by a click in an online game? Ever used search functionality in a website? One thing which is common to all these scenarios is that one or other algorithm is being run and results are being delivered.
         Simply stated, Algorithm is a set of instructions to reach a result based on given inputs. To take a current world scenario, encryption has become almost a minimum requirement for any application. For example, a popular encryption technique is MD5 Encryption Algorithm.
Examples of MD5:
Input : HelloWorld
MD5 Hash : 68e109f0f40ca72a15e05cc22786f8e6

Input : GeeksForGeeks
MD5 Hash : f1e069787ece74531d112559945c6871

         Google when showing search results uses page ranking techniques. Facebook when showing news feed uses a similar ranking algorithm to make it more relevant to you. All these use a modification of Link Analysis, an interesting branch in Data Mining.Let’s consider a small example.
Sample network graph with edges indicating friendships.
The above image shows a sample network graph in which each node represents a different profile and an edge showing a friendship.Considering this scenario, Facebook algorithms may determine that the number of mutual friends between A and F is 2 and may update your feed and friend suggestions.
         So, whenever you press a key on your keyboard, make a call, perform a calculation, start an application or press a remote button, always an algorithms is triggered. So, there are countless examples of many algorithms in our daily life and making our life easier.
CBSE - Class 11
Picked
Programming Basics
school-programming
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
Difference between Algorithm, Pseudocode and Program
What are Hash Functions and How to choose a good Hash Function?
Difference between Informed and Uninformed Search in AI
How to Export DataFrame to CSV in R ? - GeeksforGeeks

26 Mar, 2021
R Programming language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to Export DataFrame to CSV file in R Programming Language.
Approach: 
Write Data in column wise format
Create DataFrame for these data
Write Data to the CSV file
Print the success message
Function used:
dataframe() is used to create data frame
Syntax:
data.frame(column1, column2, column3)
write.csv() function is used create csv file from the data set.
Syntax:
 write.csv(dataframe, path) 
Example:
R
Rollno <- c("5", "6", "7")Name <- c("John Doe","Jane Doe", "Bill Gates")Marks <- c("80", "75", "95")Age <- c("13", "13", "14")    df <- data.frame(Rollno,Name,Marks,Age)  write.csv(df,"C:\\Users\\...YOUR PATH...\\agedata.csv", row.names = FALSE)  print ('CSV created Successfully :)')
Output: 
Example:
R
Country <- c("China", "India", "United States", "Indonesia", "Pakistan")  Population <- c("1,407,068,600","1,374,506,881", "331,329,046",                 "270,203,917", "225,200,000")  Date <- c("15 Mar 2021", "15 Mar 2021", "15 Mar 2021",           "30 Sep 2020", "1 Jul 2021")  df <- data.frame(Country, Population, Date)  write.csv(df,"C:\\Users\\...YOUR PATH...\\population.csv", row.names = FALSE)  print ('CSV created Successfully :)')
Output: 
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
How to change the colorbar size of a seaborn heatmap figure in Python?

23 Dec, 2020
Prerequisites: Seaborn
A colorbar is a rectangular color scale that is used to interpret the data of a heatmap. By default, it is of the same size as the heatmap but its size can be changed using the cbar_kws parameter of the heatmap() function. This parameter accepts dictionary type values and to change the size of the colorbar, its shrink parameter needs to be accordingly. By default, it is 1, which makes the colorbar of the same size as the heatmap. To make the colorbar small, shrink should be given a value smaller than 1 and to increase its size it should be given a value greater than 1.
Syntax of heatmap():
Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)
Important Parameters:
data: 2D dataset that can be coerced into an ndarray.
vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.
cmap: The mapping from data values to color space.
center: The value at which to center the colormap when plotting divergent data.
annot: If True, write the data value in each cell.
fmt: String formatting code to use when adding annotations.
linewidths: Width of the lines that will divide each cell.
linecolor: Color of the lines that will divide each cell.
cbar: Whether to draw a colorbar.
All the parameters except data are optional.
Returns: An object of type matplotlib.axes._subplots.AxesSubplot 
Import modules
Load or create data
Create a heatmap using appropriate values, within this function itself, set cbar_kws with shrink and its required value.
Display plot
Implementation using this approach is given below:
Database in use: Bestsellers
Example 1: Decreasing the size of the colorbar
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb  # load datadata = pd.read_csv("bestsellers.csv")  # plotting heatmapsb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 0.6})  # displaying heatmapmp.show()
Output:
Example 2: Increasing the size of the colorbar
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb  # load datadata = pd.read_csv("bestsellers.csv")  # plotting heatmapsb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 1.3})  # displaying heatmapmp.show()
Output:
Picked
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
How to Install Linux Packages Inside a Docker Container?

06 Oct, 2021
Once you understand how to pull base Docker Images from the Docker registry, you can now simply pull OS distributions such as Ubuntu, CentOS, etc directly from the Docker hub. However, the OS Image that you have pulled simply contains a raw file system without any packages installed inside it. When you work on projects inside Docker Containers, you will definitely need some libraries and packages either right from the beginning of the development phase or on the go. 
In this article, we will see how to install packages and libraries inside Docker Containers using 2 different methods. We will also try to install Firefox and vim text editor inside Ubuntu Docker Container.
Step 1: Open the terminal of your local system and run the Ubuntu Docker Image from the Docker Registry. If your system has no previous pulls, it will start pulling from the registry.
sudo docker run -it ubuntu bash

Running Ubuntu Container
Step 2: Now, you have opened the bash of your Ubuntu Docker Container. To install any packages, you first need to update the OS.
apt-get -y update

Updating the Container
Step 3: After you have updated the Docker Container, you can now install the Firefox and Vim packages inside it.
apt-get -y install firefox
apt-get -y install vim

Installing Firefox
Installing Vim
You can now easily use these packages through the bash itself.
You can also directly specify the packages you need to install in the dockerfile using the RUN instruction. This method is preferable over the CLI method because building a dockerfile is very essential if you are working on projects inside Docker. It gives better version control and provides a blueprint of the entire Docker Image.
Step 1: Write your instructions inside a dockerfile.
FROM ubuntu:latest
RUN apt-get -y update && apt-get -y install firefox && apt-get -y install vim

Step 2: Build the Image using the Docker Build command.
sudo docker build -t sample-image .

Building the Image
Step 3: Run the container and verify the installed packages
sudo docker run -it sample-image bash
vim
firefox

Running the Container
Vim Text Editor running inside Container
Docker Container
how-to-install
linux
Advanced Computer Subject
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Markov Decision Process
Getting Started with System Design
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
Python string | printable()

15 Oct, 2019
In Python3, string.printable is a pre-initialized string used as string constant. In Python, string.printable will give the all sets of punctuation, digits, ascii_letters and whitespace.
Syntax : string.printable
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return all sets of punctuation, digits, ascii_letters and whitespace.
Note : Make sure to import string library function inorder to use string.printable
Code #1 :
# import string library function import string     # Storing the sets of punctuation,# digits, ascii_letters and whitespace# in variable result result = string.printable    # Printing the set of values print(result) 
Output :
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+, -./:;<=>?@[\]^_`{|}~ 

Code #2 : Given code tests for the printable values.
# import string library function import string     # An input string.Sentence = "Hey, Geeks !, How are you?"  for i in Sentence:          # checking whether the char is printable value    if i in string.printable:                  # Printing the printable values         print("printable Value is: " + i)
Output:
printable Value is: H
printable Value is: e
printable Value is: y
printable Value is:,
printable Value is:  
printable Value is: G
printable Value is: e
printable Value is: e
printable Value is: k
printable Value is: s
printable Value is: !
printable Value is:,
printable Value is:  
printable Value is: H
printable Value is: o
printable Value is: w
printable Value is:  
printable Value is: a
printable Value is: r
printable Value is: e
printable Value is:  
printable Value is: y
printable Value is: o
printable Value is: u
printable Value is: ?

shubham_singh
python-string
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
Node.js Buffer.readUInt8() Method

13 Oct, 2021
The Buffer.readUInt8() method is used to read an unsigned 8 bit integer from a Buffer object.
Syntax:
buffer.readUInt8( offset )
Parameters: This method accepts a single parameter offset which specifies the position of buffer object. It represents the number of bytes to skip before starting to read. The value of offset lies between the range 0 to buffer.length – 1. The default value is 0.
Return value: It returns the integer value specified by the offset.
Example 1:
// Node.js program to demonstrate the// buffer.readUInt8() method const ob=Buffer.from([1, 2, 3]);  // It reads the first valueconsole.log(ob.readUInt8(0));  // It reads the second valueconsole.log(ob.readUInt8(1));  // It throws an errorconsole.log(ob.readUInt8(4));
Output:
1
2
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.
It must be >= 0 and <= 2. Received 3
    at boundsError (internal/buffer.js:53:9)
    at Buffer.readUInt8 (internal/buffer.js:141:5)



Example 2:
// Node.js program to demonstrate the// buffer.readUInt8() method const ob1 = Buffer.from([0X32, 0X44, 0X48]);  // It returns the first valueconsole.log(ob1.readUInt8(0));  // It returns the third valueconsole.log(ob1.readUInt8(2));const t = Buffer.from("abc");  // It returns the ASCII value of 'a'console.log(t.readUInt8(0));
Output:
68
72
97

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_readuint8_offset
Node.js-Buffer-module
Picked
Node.js
Technical Scripter
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
How to display dropdown in ReactNative?

The React native picker component is similar to a dropdown that allows you to select a value from the multiple options given.
The basic Picker component is as follows −
<Picker selectedValue = {selectedelement} onValueChange = {updatefunc}>
   <Picker.Item label = "ItemLabel" value = "ItemValue" />
      ...
      ...
      ...
   <Picker.Item label = "ItemLabel" value = "ItemValue" />
</Picker>
To work with picker component, you need to import it first from react-native as follows −
import { Picker } from 'react-native'
This example shows the dropdown using the Picker component.
The code is as follows −
<Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
      <Picker.Item label = "Steve" value = "steve" />
      <Picker.Item label = "Ellen" value = "ellen" />
      <Picker.Item label = "Maria" value = "maria" />
   </Picker>
There are 3 values given to the Picker Steve, Ellen and Maria. Here is a complete code to display it.
import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'
class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
            <Picker.Item label = "Steve" value = "steve" />
            <Picker.Item label = "Ellen" value = "ellen" />
            <Picker.Item label = "Maria" value = "maria" />
         </Picker>
         <Text style = {styles.text}>{this.state.user}</Text>
            </View>
         )
      }
   }
   export default PickerExample
   const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})
The this.state.user is used for picker control. The updateUser function will be triggered when a user is picked.
When you open the name from picker you should see as below −
Why String class is immutable or final in Java?

The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.
Security Parameters are typically represented as String in network connections, database connection URLs, usernames/passwords, etc. If it was mutable, these parameters could be changed easily.
Synchronization and Concurrency making String immutable automatically makes them thread safe thereby solving the synchronization issues.
Caching when compiler optimizes our String objects, it seems that if two objects have the same value (a =" test", and b =" test") and thus we need only one string object (for both a and b, these two will point to the same object).
Class loading String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state).
public class StringImmutableDemo {
   public static void main(String[] args) {
      String st1 = "Tutorials";
      String st2 = "Point";
      System.out.println("The hascode of st1 = " + st1.hashCode());
      System.out.println("The hascode of st2 = " + st2.hashCode());
      st1 = st1 + st2;
      System.out.println("The Hashcode after st1 is changed : "+ st1.hashCode());
   }
}
The hascode of st1 = -594386763
The hascode of st2 = 77292912
The Hashcode after st1 is changed : 962735579
Adjusting gridlines and ticks in Matplotlib imshow

To adjust gridlines and ticks in matplotlib imshow(), we can take the following steps−
Create data, a 2D array, using numpy.
Using imshow() method, display data as an image.
Set xticks and yticks using set_xticks and set_yticks method.
To set the xticklabels and yticklabels, use set_xticklabels and set_yticklabels method.
Lay out a grid in current line style. Supply the list of x an y positions using grid() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(9, 9)
plt.imshow(data, interpolation="nearest")
ax = plt.gca()
ax.set_xticks(np.arange(-.5, 9, 1))
ax.set_yticks(np.arange(-.5, 9, 1))
ax.set_xticklabels(np.arange(0, 10, 1))
ax.set_yticklabels(np.arange(0, 10, 1))
ax.grid(color='red', linestyle='-.', linewidth=1)
plt.show()
MongoDB $subtract Operator - GeeksforGeeks

18 Oct, 2021
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and an $subtract operator is one of them. This operator is used to subtract two numbers and return the difference in the numbers or to subtract two dates and return the difference in the milliseconds, or subtracts date and number in milliseconds and returns the date. 
Syntax: 
{ $subtract: [ <expression1>, <expression2> ] }
Here, the given arguments must be a valid expression like numbers or a date, and the second argument is subtracted from the first argument.  If you are subtracting a number from a date, then the first argument of this operator is a date.
 Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: Employee
Document: four documents that contain the details of the employees in the form of field-value pairs.
Using $subtract operator subtract two numbers:
In this example, we are going to subtract the value of firstSalary field from the value of secondSalary field using $subtract operator.
db.Employee.aggregate([{$match: {department: "Development"}},
... {$project: {result:
... {$subtract:["$secondSalary", "$firstSalary"]}}}])
Using $subtract operator subtract two dates:
In this example, we are going to subtract two dates, i.e, the value of projectStartDate field from the value of projectEndDate field using a $subtract operator.
db.Employee.aggregate([{$match: {department: "Testing"}},
... {$project:{diffResult:
... {$subtract:["$projectEndDate", "$projectStartDate"]}}}])
Using $subtract operator subtracts milliseconds from a date:
In this example, we are going to subtract 5*24*60*60000 milliseconds (i.e., 5 days) from the value of projectEndDate field using a $subtract operator.
db.Employee.aggregate([{$match: {department: "Testing"}},
... {$project: {newprojectEndDate:
... {$subtract:["$projectEndDate", 5*24*60*60000]}}}])
singghakshay
sweetyty
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Spring Boot JpaRepository with Example
Aggregation in MongoDB
How to build a basic CRUD app with Node.js and ReactJS ?
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
MongoDB - Check the existence of the fields in the specified collection
MongoDB - Distinct() Method
Upsert in MongoDB
How to connect MongoDB with ReactJS ?
MongoDB: An introduction