code-rag-bench/online-tutorials huggingface dataset:
Java Program for Longest Increasing Subsequence

Following is the Java program for longest increasing subsequence −
 Live Demo
public class Demo{
   static int incre_subseq(int my_arr[], int arr_len){
      int seq_arr[] = new int[arr_len];
      int i, j, max = 0;
      for (i = 0; i < arr_len; i++)
         seq_arr[i] = 1;
      for (i = 1; i < arr_len; i++)
      for (j = 0; j < i; j++)
      if (my_arr[i] > my_arr[j] && seq_arr[i] < seq_arr[j] + 1)
      seq_arr[i] = seq_arr[j] + 1;
      for (i = 0; i < arr_len; i++)
      if (max < seq_arr[i])
      max = seq_arr[i];
      return max;
   }
   public static void main(String args[]){
      int my_arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
      int arr_len = my_arr.length;
      System.out.println("The length of the longest increasing subsequence is " +  incre_subseq(my_arr, arr_len));
   }
}
The length of the longest increasing subsequence is 5
A class named Demo contains a static function named 'incre_subseq’ that takes the array and the length of the array as parameters. Inside this function, a new array is created that is empty. A 'max' variable is assigned the value 0. A 'for' loop iterates over the length of the array and every element is initialized to 1.
Again, 'for' loop is iterated, and another 'for' loop is initiated that checks if first element in the array is equal to the second element and if the array (seq_arr, that had all 1s initialized) has first element lesser than the second element + 1. The maximum of the elements in the seq_arr is found and returned. This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array.
How to apply antialiasing in HTML5 canvas drawImage()?

For antialiasing, you need to set resampling quality.
ctx.imageSmoothingQuality = "low|medium|high"
Use an off-screen canvas to reduce the image to half −
var c = document.createElement('canvas'),
ocx = c.getContext('2d');
c.width = img.width * 0.5;
c.height = img.height * 0.5;

ocxx.drawImage(img, 0, 0, c.width, c.height);
// drawing images reducing to half again and repeating it
ocx.drawImage(c, 0, 0, c.width * 0.5, cc.height * 0.5);
C/C++ Program to Count trailing zeroes in factorial of a number?

Here we will see how to calculate the number of trailing 0s for the result of factorial of any number. So if the n = 5, then 5! = 120. There is only one trailing 0. For 20!, it will be 4 zeros as 20! = 2432902008176640000.
The easiest approach is just calculating the factorial and count the 0s. But this approach fails for large value of n. So we will follow another approach. The trailing zeros will be there, if the prime factors are 2 and 5. If we count the 2s and 5s we can get the result. For that we will follow this rule.
Trailing 0s = Count of 5s in prime factors of factorial(n)
begin
   count := 0
   for i := 5, (n/i) >= 1, increase i := i * 5, do
      count := count + (n / i)
   done
   return count;
end
#include <iostream>
#include <cmath>
#define MAX 20
using namespace std;
int countTrailingZeros(int n) {
   int count = 0;
   for (int i = 5; n / i >= 1; i *= 5)
      count += n / i;
   return count;
}
main() {
   int n = 20;
   cout << "Number of trailing zeros: " << countTrailingZeros(n);
}
Number of trailing zeros: 4
Linking Files having same variables with different data types in C - GeeksforGeeks

23 May, 2018
Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c.Note that none of the variables is declared as extern.
What do you expect to be the output of the following command with given two programs?
$ gcc -o myprog foo1.c foo2.c
$ ./myprog

// foo1.c#include<stdio.h>void f(void);int x = 38;int y = 39;  int main() {    f();    printf("x = % d\n", x);    printf("y = % d\n", y);    return 0;}
// foo2.cdouble x;void f() {    x = 42.0;}
Output:
x = 0
y = 1078263808

Explanation of Output: Output of the program looks unpredictable but reason is: In foo1.c, there are two variables x and y each having 4 bytes(total 8 bytes). In foo2.c there is x variable as double.While execution, x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x and y (total 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes).
1078263808 value is floating point representation of 42 in double.
NOTE : x and y addresses in foo1.c are successive.
Related Article : External and Internal Linkages in C
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java?
Python | Convert list of tuples to list of strings - GeeksforGeeks

26 Feb, 2019
The interconversion between datatypes is quite useful utility and many articles have been written to perform the same. This article discusses the interconversion between a tuple of characters to individual strings. This kind of interconversion is useful in Machine Learning in which we need to give the input to train model in a specific format. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + join()The list comprehension performs the task of iterating the entire list of tuples and join function performs the task of aggregating the elements of tuple into a one list.
# Python3 code to demonstrate# conversion of list of tuple to list of list # using list comprehension + join()  # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'),                              ('G', 'E', 'E', 'K', 'S')]  # printing the original listprint ("The original list is : " + str(test_list))  # using list comprehension + join()# conversion of list of tuple to list of list res = [''.join(i) for i in test_list]  # printing resultprint ("The list after conversion to list of string : " + str(res))
Output :
The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]
 
Method #2 : Using map() + join()The task performed by the list comprehension can be performed by the map function which can perform extension of logic of one tuple to all tuple in list.
# Python3 code to demonstrate# conversion of list of tuple to list of list # using map() + join()  # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'),                              ('G', 'E', 'E', 'K', 'S')]  # printing the original listprint ("The original list is : " + str(test_list))  # using map() + join()# conversion of list of tuple to list of list res = list(map(''.join, test_list))  # printing resultprint ("The list after conversion to list of string : " + str(res))
Output :
The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]
Python list-programs
python-list
python-tuple
Python
Python Programs
python-list
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()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
OffsetDateTime format() method in Java with examples - GeeksforGeeks

13 Aug, 2021
The format() method of OffsetDateTime class in Java formats this date-time using the specified formatter. 
Syntax :  
public String format(DateTimeFormatter formatter)
Parameter : This method accepts a single parameter formatter which specifies the formatter to use, not null.Return Value: It returns the formatted date string, not null.Exceptions: The function throws a DateTimeException that is when an error occurs during printing. Below programs illustrate the format() method:Program 1 :  
Java
// Java program to demonstrate the format() methodimport java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG {    public static void main(String[] args)    {         // Parses the date1        OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00");         // Prints the date        System.out.println("Date1: " + date1);         DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;        System.out.println(formatter.format(date1));    }}
Date1: 2018-12-12T13:30:30+05:00
13:30:30+05:00
 
Program 2 : 
Java
// Java program to demonstrate the format() method// Exceptions import java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG {    public static void main(String[] args)    {        try {            // Parses the date1            OffsetDateTime date1 = OffsetDateTime.parse("2018-13-12T13:30:30+05:00");             // Prints the date            System.out.println("Date1: " + date1);             DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;            System.out.println(formatter.format(date1));        }        catch (Exception e) {            System.out.println(e);        }    }}
java.time.format.DateTimeParseException: Text '2018-13-12T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter-
akshaysingh98088
Java-Functions
Java-OffsetDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Python | Pandas dataframe.assign() - GeeksforGeeks

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Dataframe.assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. Existing columns that are re-assigned will be overwritten.
Length of newly assigned column must match the number of rows in the dataframe.
Syntax: DataFrame.assign(**kwargs)
Parameters:kwargs : keywords are the column names. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas don’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned.
Returns: A new DataFrame with the new columns in addition to all the existing columns.
For link to CSV file Used in Code, click here
Example #1: Assign a new column called Revised_Salary with 10% increment of the original Salary.
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # Printing the first 10 rows of# the data frame for visualizationdf[:10]
# increase the salary by 10 % df.assign(Revised_Salary = lambda x: df['Salary']                               + df['Salary']/10)
Output:
 Example #2: Assigning more than one column at a time
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # First column ='New_Team', this column# will append '_GO' at the end of each team name.# Second column ='Revised_Salary' will increase # the salary of all employees by 10 % df.assign(New_team = lambda x: df['Team']+'_GO',           Revised_Salary = lambda x: df['Salary']                              + df['Salary'] / 10)
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
PYGLET – Drawing Rectangle - GeeksforGeeks

09 Jul, 2021
In this article we will see how we can draw rectangle on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A rectangle is a four-sided shape where every angle is a right angle (90°). Also opposite sides are parallel and of equal length. Rectangle is drawn with the help of shapes module in pyglet.We can create a window with the help of command given below  
# creating a window
window = pyglet.window.Window(width, height, title)
 
In order to create window we use Rectangle method with pyglet.shapesSyntax : shapes.Rectangle(x, y, width, height, color=(255, 255, 255), batch=None)Argument : It takes position i.e pair of integer, width and height of rectangle, color of rectangle and last is batch objectReturn : It returns Line object  
Below is the implementation  
Python3
# importing pyglet moduleimport pyglet # importing shapes from the pygletfrom pyglet import shapes # width of windowwidth = 500   # height of windowheight = 500   # caption i.e title of the windowtitle = "Geeksforgeeks"   # creating a windowwindow = pyglet.window.Window(width, height, title) # creating a batch objectbatch = pyglet.graphics.Batch()  # properties of rectangle# co-ordinates of rectangleco_x = 150co_y = 150 # width of rectanglewidth = 300 # height of rectangleheight = 200 # color = greencolor = (50, 225, 30) # creating a rectanglerec1 = shapes.Rectangle(co_x, co_y, width, height, color = color, batch = batch) # changing opacity of the rect1# opacity is visibility (0 = invisible, 255 means visible)rec1.opacity = 250  # creating another rectangle with properties# x, y co ordinate : 50, 250# width, height of rectangle : 300, 200# color = redcolor = (255, 25, 25) # creating rectanglerec2 = shapes.Rectangle(50, 250, 300, 200, color = color, batch = batch) # changing opacity of the rec2# opacity is visibility (0 = invisible, 255 means visible)rec2.opacity = 100  # window draw event to draw rectangles@window.eventdef on_draw():         # clear the window    window.clear()         # draw the batch    batch.draw() # run the pyglet applicationpyglet.app.run()
sagartomar9927
Python-gui
Python-Pyglet
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Selection Sort Program in C

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
#include <stdio.h>
#include <stdbool.h>

#define MAX 7

int intArray[MAX] = {4,6,3,2,1,9,7};

void printline(int count) {
   int i;
	
   for(i = 0;i < count-1;i++) {
      printf("=");
   }
	
   printf("=\n");
}

void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf("%d ", intArray[i]);
   }
	
   printf("]\n");
}

void selectionSort() {
   int indexMin,i,j;
	
   // loop through all numbers 
   for(i = 0; i < MAX-1; i++) { 
	
      // set current element as minimum 
      indexMin = i;
		
      // check the element to be minimum 
      for(j = i+1;j < MAX;j++) {
         if(intArray[j] < intArray[indexMin]) {
            indexMin = j;
         }
      }

      if(indexMin != i) {
         printf("Items swapped: [ %d, %d ]\n" , intArray[i], intArray[indexMin]); 
			
         // swap the numbers 
         int temp = intArray[indexMin];
         intArray[indexMin] = intArray[i];
         intArray[i] = temp;
      }          

      printf("Iteration %d#:",(i+1));
      display();
   }
}  

void main() {
   printf("Input Array: ");
   display();
   printline(50);
   selectionSort();
   printf("Output Array: ");
   display();
   printline(50);
}
If we compile and run the above program, it will produce the following result −
Input Array: [4 6 3 2 1 9 7 ]
==================================================
Items swapped: [ 4, 1 ]
Iteration 1#:[1 6 3 2 4 9 7 ]
Items swapped: [ 6, 2 ]
Iteration 2#:[1 2 3 6 4 9 7 ]
Iteration 3#:[1 2 3 6 4 9 7 ]
Items swapped: [ 6, 4 ]
Iteration 4#:[1 2 3 4 6 9 7 ]
Iteration 5#:[1 2 3 4 6 9 7 ]
Items swapped: [ 9, 7 ]
Iteration 6#:[1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
MongoDB query to add new array element in document

To add new array element in a MongoDB document, use $(projection) along with update(). Let us create a collection with documents −
>db.demo222.insertOne({"details":[{"StudentName":"Chris","StudentMarks":78},{"StudentName":"David","StudentMarks":89}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee31703d395bdc213472f")
}
Display all documents from a collection with the help of find() method −
> db.demo222.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e3ee31703d395bdc213472f"),
   "details" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 78
      },
      {
         "StudentName" : "David",
         "StudentMarks" : 89
      }
   ]
}
Following is the query to add new array element in document −
> db.demo222.update({"details.StudentName" : "Chris"},{"$set" : {"details.$.SubjectName":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo222.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e3ee31703d395bdc213472f"),
   "details" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 78,
         "SubjectName" : "MongoDB"
      },
      {
         "StudentName" : "David",
         "StudentMarks" : 89
      }
   ]
}
Java DIP - Understand Convolution

Convolution is a mathematical operation on two functions f and g. The function f and g in this case are images, since an image is also a two dimensional function.
In order to perform convolution on an image, following steps are taken −
Flip the mask (horizontally and vertically) only once.
Slide the mask onto the image.
Multiply the corresponding elements and then add them.
Repeat this procedure until all values of the image has been calculated.
We use OpenCV function filter2D to apply convolution to images. It can be found under Imgproc package. Its syntax is given below −
filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );

The function arguments are described below −
src
It is source image.
dst
It is destination image.
depth
It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
kernel
It is the kernel to be scanned through the image.
anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
delta
It is a value to be added to each pixel during the convolution. By default it is 0.
BORDER_DEFAULT
We let this value by default.
The following example demonstrates the use of Imgproc class to perform convolution on an image of Grayscale.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class convolution {
   public static void main( String[] args ) {
   
      try {
         int kernelSize = 3;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,0);
               put(0,1,0);
               put(0,2,0);

               put(1,0,0);
               put(1,1,1);
               put(1,2,0);

               put(2,0,0);
               put(2,1,0);
               put(2,2,0);
            }
         };
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("original.jpg", destination);
         
      } catch (Exception e) {
          System.out.println("Error:" + e.getMessage());
      }
   }
}
In this example we convolve our image with the following filter(kernel). This filter results in producing original image as it is −

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to convert list elements into a single string in R?

To convert list elements into a single string, we can use paste function but firstly we would need to unlist the elements. Also, since we want to create a single string double quotes will be required at the end of the output. For example, if we have a list that contains 5 elements say 1, 2, 3, 4, 5 then conversion of these elements into a single string would be "12345".
 Live Demo
List1<−list(1,2,3,2,2,1,2,1,4,2,2,2,2,2,2,3,2,2)
List1
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 2
[[5]]
[1] 2
[[6]]
[1] 1
[[7]]
[1] 2
[[8]]
[1] 1
[[9]]
[1] 4
[[10]]
[1] 2
[[11]]
[1] 2
[[12]]
[1] 2
[[13]]
[1] 2
[[14]]
[1] 2
[[15]]
[1] 2
[[16]]
[1] 3
[[17]]
[1] 2
[[18]]
[1] 2
Converting List1 elements into a single string element −
List1<−paste(unlist(List1),collapse="")
List1
[1] "123221214222222322"
class(List1)
[1] "character"

 Live Demo
List2<−list(x1<−rpois(5,5),x2=rpois(5,2),x3=rpois(5,5),x4=rpois(10,4))
List2
[[1]]
[1] 6 2 8 3 5
$x2
[1] 2 4 3 2 5
$x3
[1] 8 1 12 1 4
$x4
[1] 7 5 4 3 6 2 5 3 2 2
Converting List2 elements into a single string element −
List2<−paste(unlist(List2),collapse="")
List2
[1] "62835243258112147543625322"
MongoDB AND operator ( $and )

05 Jun, 2022
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements.
This operator performs short-circuit evaluation.
If the first expression of $and operator evaluates to false, then MongoDB will not evaluate the remaining expressions in the array.
You can also use AND operation implicitly with the help of comma(, ).
You can use AND operation explicitly (i.e., $and) when the same field or operator specified in multiple expressions.
Syntax: 
{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}
Examples: In the following examples, we are working with:
Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018. 
Python3
db.contributor.find({$and: [{branch: "CSE"},                            {joiningYear: 2018}]}).pretty()
In this example, we are retrieving only those employee’s documents whose branch is CSE. 
Python3
db.contributor.find({$and: [{branch: {$eq: "CSE"}},                            {branch: {$exists: true}}]}).pretty()
or 
Python3
db.contributor.find({branch: {$eq: "CSE", $exists: true}}).pretty()
In this example, we are retrieving only those employee’s documents whose satisfy the given conditions. 
Python3
db.contributor.find({$and: [{$or: [{branch: "ECE"}, {joiningYear: 2017}]},                            {$or: [{"personal.state": "UP"},                                   {"personal.age": 25}]}]}).pretty()
vinayedula
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Fuzzy Logic | Introduction
Mounting a Volume Inside Docker Container
How to get attribute of element from Selenium?

We can get the attribute of element in Selenium webdriver. The getAttribute() method is used to obtain the value of an attribute in an html document. In an html code, attribute and its value appear as a key value pair.
Some of the commonly known html attributes are disabled, alt, id, href, style, title and src. The value of the attribute that we want to fetch is passed as an argument to the method.
Let us consider an html code, for which we shall obtain the src attribute. The value of the src attribute should be /about/images/logo.png.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class GetSrcAttribute{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u = "https://www.tutorialspoint.com/about/about_careers.htm"driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
      // get src attribute with getAttribute()
      System.out.println("Src attribute is : " + t.getAttribute("src"));
      driver.close();
   }
}
Output
Downloading PDFs with Python using Requests and BeautifulSoup

13 Apr, 2021
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object.
Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.
This article deals with downloading PDFs using BeautifulSoup and requests libraries in python. Beautifulsoup and requests are useful to extract the required information from the webpage.
Approach:
To find PDF and download it, we have to follow the following steps:
Import beautifulsoup and requests library.
Request the URL and get the response object.
Find all the hyperlinks present on the webpage.
Check for the PDF file link in those links.
Get a PDF file using the response object.
Implementation:
Python3
# Import librariesimport requestsfrom bs4 import BeautifulSoup  # URL from which pdfs to be downloadedurl = "https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/"  # Requests URL and get response objectresponse = requests.get(url)  # Parse text obtainedsoup = BeautifulSoup(response.text, 'html.parser')  # Find all hyperlinks present on webpagelinks = soup.find_all('a')  i = 0  # From all links check for pdf link and# if present download filefor link in links:    if ('.pdf' in link.get('href', [])):        i += 1        print("Downloading file: ", i)          # Get response object for link        response = requests.get(link.get('href'))          # Write content in pdf file        pdf = open("pdf"+str(i)+".pdf", 'wb')        pdf.write(response.content)        pdf.close()        print("File ", i, " downloaded")  print("All PDF files downloaded")
Output:
Downloading file:  1
File  1  downloaded
All PDF files downloaded
The above program downloads the PDF files from the provided URL with names pdf1, pdf2, pdf3 and so on respectively.
Picked
Python BeautifulSoup
Python-requests
Web-scraping
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
Neo4j Drop Index

27 Aug, 2019
In neo4j you can drop index for both property and nodes. Indexing is data structure that helps faster performance on retrieval operation on database. There is special features in neo4j indexing once you create indexing that index will manage itself and keep it up to date whenever changes made on the database. Similarly DROP INDEX ON statement will provide the indexing.Syntax:
DROP INDEX ON:label(node)
Example: In the below example we drop index on the Tag property of all nodes with the GeeksforGeeks label.
$ DROP INDEX ON:GeeksforGeeks(Tag)
Output:
$ DROP INDEX ON:GeeksforGeeks(Tag)

Output:
View Schema: You can use the :schema command to see applicable index is removed from the schema.
:schemaOutput:
:schema
Output:
Note: If there is others indexing available then it will show those, basically this command will show all the schema.
Remember few things to remove anything fast off all remove the relationship first after try the DELETE clause or REMOVE clause it is a good practice. To remove any node you have to remove the relationships, but in case of indexing that is not required. Indexing is the different things that does not effect on database it just increase the accessibility of your database. by removing the index you lost the fast accessing capability.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
SQL Interview Questions
Introduction of ER Model
Data Preprocessing in Data Mining
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Indexing in Databases | Set 1
Convert Text File to CSV using Python Pandas

02 Sep, 2020
Let’s see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding.
Original Text File
Dataframe created from upper text file will look as follows: 
CSV File formed from given text file
Note: The first column in dataframe is indexing which is by default when a text file is read.
Once the dataframe is created, we will store this dataframe into a CSV file format using Dataframe.to_csv() Method.
Syntax: Dataframe.to_csv(parameters)
Return: None
Let’s see examples:
Example 1:
Python3
# importing panda libraryimport pandas as pd  # readinag given csv file# and creating dataframedataframe1 = pd.read_csv("GeeksforGeeks.txt")  # storing this dataframe in a csv filedataframe1.to_csv('GeeksforGeeks.csv',                   index = None)
Output:
CSV File formed from given text file
The text file read is same as above. After successful run of above code, a file named “GeeksforGeeks.csv” will be created in the same directory. 
Example 2: Suppose the column heading are not given and the text file looks like:
Text File without headers
Then while writing the code you can specify headers. 
Python3
# importing pandas libraryimport pandas as pd  # reading given csv file # and creating dataframewebsites = pd.read_csv("GeeksforGeeks.txt"                       ,header = None)  # adding column headingswebsites.columns = ['Name', 'Type', 'Website']  # store dataframe into csv filewebsites.to_csv('GeeksforGeeks.csv',                 index = None)
 Output:
CSV file with headers
We see that headers have been added successfully and file has been converted from ‘.txt’ format to ‘.csv’ format.
Example 3: In this example, the fields in the text file are separated by user defined delimiter “/”. 
‘/’ Delimited Text File
Python3
# importing pandas libraryimport pandas as pd  # reading the given csv file # and creating dataframeaccount = pd.read_csv("GeeksforGeeks.txt",                      delimiter = '/')  # store dataframe into csv fileaccount.to_csv('GeeksforGeeks.csv',               index = None)
Output:
CSV File
While reading data we specify that data should be tokenized using specified delimiter. In this case ‘/’.
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
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
Working with zcat, zmore and zless Command in Linux

10 Oct, 2021
Compression means to keep files together in an archive and to reduce the size of files. Gzip a.k.a. Gunzip is a command in Linux which is used to compress and decompress the files. So in case, you compressed a very large file with gzip and you just want to see what are the contents of the file. As in this case decompression of the file is going to take a lot of time, so in order to save time and view files without decompressing them “zcat” command is used. 
 
1. To display contents of a Gzipped file. 
$zcat filename.gz
This will print all the contents of the compressed file. 
Note: In this case the, name of file is filename.gz. 
2. To display contents of multiple compressed files. 
$zcat file1.gz file2.gz
It display contents of multiple files together. 
Note: In this case the, name of file is file1.gz and file2.gz. 
3. To read compressed data even from a terminal and even it is compressed or not. 
$zcat -f filename.gz
This displays the content of the file even if the content is binary or is in an encrypted form. 
Note: In this case the, name of file is filename.gz. 
4. To paginate the output. 
$zless filename.gz
$zmore filename.gz
These are the commands used for paginating the output. 
Note: In this case the, name of file is filename.gz. 
5. To get the properties of the compressed file.  
$zcat -l filename.gz
This will display the properties of files like compressed and uncompressed ratio and uncompressed name etc. 
Note: In this case the, name of file is filename.gz. 
6. To suppress all warnings.  
$zcat -q filename.gz
This will suppress all the warnings that will occur in between the execution of the command.
surindertarika1234
sooda367
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
How to catch IndentationError Exception in python?

A IndentationError occurs any time the parser finds source code that does not follow indentation rules. We can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except block, because with this exception, Python won't be able to finish compiling the module, and no code in the module will be run.
We rewrite the given code as follows to handle the exception
try:
def f():
z=['foo','bar']
for i in z:
if i == 'foo':
except IndentationError as e:
print e
"C:/Users/TutorialsPoint1/~.py", line 5
if i == 'foo':
^
IndentationError: expected an indented block
Duration minusDays() method in Java

An immutable copy of a duration where some days are removed from it can be obtained using the minusDays() method in the Duration class in Java. This method requires a single parameter i.e. the number of days to be subtracted and it returns the duration with the subtracted days.
A program that demonstrates this is given as follows −
 Live Demo
import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      Duration d = Duration.ofDays(5);
      System.out.println("The duration is: " + d);
      System.out.println("A copy with 2 days removed from the duration is: " + d.minusDays(2));
   }
}
The duration is: PT120H
A copy with 2 days removed from the duration is: PT72H
Now let us understand the above program.
First the duration is displayed. Then an immutable copy of the duration where 2 days are removed is obtained using the minusDays() method and this is displayed. A code snippet that demonstrates this is as follows −
Duration d = Duration.ofDays(5);
System.out.println("The duration is: " + d);
System.out.println("A copy with 2 days removed from the duration is: " + d.minusDays(2));
ReactJS – getDerivedStateFromError() Method

In this article, we are going to see how to execute a function if some error occurs in the component.
This method is called when a component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application. To avoid performance issues, don’t set up any side-effects in this method.
static getDerivedStateFromError(error)
It accepts the error as a parameter that was thrown as a component.
In this example, we will build a React application that displays the contained Comp1 component if no error occurs; otherwise it displays some text. But here, in Comp1 component, error is defined to occur, as the state is not defined which fires the getDerivedStateFromError in the parent component.
App.jsx
import React, { Component } from 'react';

class App extends Component {
   constructor(){
      super();
      this.state = {
         err: false
      };
   }
   static getDerivedStateFromError(error) {
      // Changing the state if some error occurs
      return {
         err: true,
      };
   }
   render() {
      return (
         <div>
            {this.state.err ? <div>Some Error Occurred</div> : <Comp1 />}
         </div>
      );
   }
}
class Comp1 extends Component {
   render() {
      return <h1>{this.state.data}</h1>;
   }
}
export default App;
This will produce the following result.
Blob object in JavaScript

The blob object is used for representing a blob object which is immutable and is used for representing raw data. The blob has a size and mime type property just like a file has. File is a derivation of blob and blob can be used in places where the file is used.
Following is the code showing blob object in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result{
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Blob object in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to create and display a blob object</h3>
<script>
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      let blob = new Blob(["This is a sample blob"], { type: "text/plain" });
      resEle.innerHTML = "blob.type = " + blob.type + "<br>";
      resEle.innerHTML += "blob.size = " + blob.size;
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Splitting a dataset. Here I explain how to split your data... | by Nischal Madiraju | Towards Data Science

To train any machine learning model irrespective what type of dataset is being used you have to split the dataset into training data and testing data. So, let us look into how it can be done?
Here I am going to use the iris dataset and split it using the ‘train_test_split’ library from sklearn
from sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_iris
Then I load the iris dataset into a variable.
iris = load_iris()
Which I then use to store the data and target value into two separate variables.
x, y = iris.data, iris.target
Here I have used the ‘train_test_split’ to split the data in 80:20 ratio i.e. 80% of the data will be used for training the model while 20% will be used for testing the model that is built out of it.
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=123)
As you can see here I have passed the following parameters in ‘train_test_split’:
x and y that we had previously definedtest_size: This is set 0.2 thus defining the test size will be 20% of the datasetrandom_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code.
x and y that we had previously defined
test_size: This is set 0.2 thus defining the test size will be 20% of the dataset
random_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code.
When splitting a dataset there are two competing concerns:-If you have less training data, your parameter estimates have greater variance.-And if you have less testing data, your performance statistic will have greater variance.The data should be divided in such a way that neither of them is too high, which is more dependent on the amount of data you have. If your data is too small then no split will give you satisfactory variance so you will have to do cross-validation but if your data is huge then it doesn’t really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data as otherwise, it might be more computationally intensive).
How do you copy a Lua table by value?

Copying a table means that we want all the values or pairs that are present in one table in another table. In Lua, there’s no standard library function that we can use to create such a table but we can create our own function to do so.
Let’s create a function in Lua that will take a table as an argument and will create a new table that will be the exact copy of the table passed as an argument to the function.
Consider the example shown below as reference −
 Live Demo
a = {}
a["name"] = "mukul"
a["age"] = 23
a["isWorking"] = true
function table.table_copy(t)
   local t2 = {}
   for k,v in pairs(t) do
      t2[k] = v
   end
   return t2
end
copy = table.table_copy(a)
for _,v in pairs(a) do print(v) end
for _,v in pairs(copy) do print(v) end
In the above example, we have a table named a which we later pass as an argument to the function named table.table_copy() and that function returns us a copy of the same table that we passed and finally I printed the values inside these tables to check whether the copied table is accurate or not.
mukul
true
23
mukul
true
23
How to use multiple for and while loops together in Python?

You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example,
for i in range(5):
   j = i
   while j != 0:
      print(j, end=', ')
      j -= 1
   print("")
This will give the output
1,
2, 1,
3, 2, 1,
4, 3, 2, 1,
You can take this nesting to as many levels as you like.
React Events

Just like HTML DOM events, React can perform actions based on user events.
React has the same events as HTML: click, change, mouseover etc.
React events are written in camelCase syntax:
onClick
instead of onclick.
React event handlers are written inside curly 
braces:
onClick={shoot}  instead of
onClick="shoot()". 
<button onClick={shoot}>Take the Shot!</button>

<button onclick="shoot()">Take the Shot!</button>

Put the shoot function inside the
  Football component:
function Football() {
  const shoot = () => {
    alert("Great Shot!");
  }

  return (
    <button onClick={shoot}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);


Run 
Example »

To pass an argument to an event handler, use an arrow function.
Send "Goal!" as a parameter to the shoot 
  function, using arrow 
  function:
function Football() {
  const shoot = (a) => {
    alert(a);
  }

  return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);


Run 
Example »

Event handlers have access to the React event that triggered the function.
In our example the event is the "click" event.
Arrow Function: Sending the event object manually:
function Football() {
  const shoot = (a, b) => {
    alert(b.type);
    /*
    'b' represents the React event that triggered the function,
    in this case the 'click' event
    */
  }

  return (
    <button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
 


Run 
Example »

This will come in handy when we look at Form in 
a later chapter.
Complete this statement to include a click event handler.
<button ={clicked()}>Click Me!</button>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.