code-rag-bench/online-tutorials huggingface dataset:
Lodash _.findIndex() Method - GeeksforGeeks

14 Jul, 2020
Lodash is a module in Node.js that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The Loadsh.findIndex() method is used to find the index of the first occurrence of the element. It is different from indexOf because it takes the predicate function that iterates through each element of the array.
Syntax:
findIndex(array, [predicate=_.identity], fromIndex)
Parameter: This method accepts three parameters as mentioned above and described below:
array: It is the array in which the value is to be searched.
predicate: It is the function that iterate through each element.
fromIndex: It is the index after which the element is to be searched. If from index is not given by default it will be 0.
Return Value: It return the index of the element if found else -1 is returned.
Note: Please install lodash module by using command npm install lodash before using the code given below.
Example 1: When element is search start from index 0.
Javascript
// Requiring the lodash libraryconst _ = require('lodash');  // Original arraylet array1 = [4, 2, 3, 1, 4, 2]  // Using lodash.findIndexlet index = _.findIndex(array1, (e) => {    return e == 1;}, 0);  // Print original Arrayconsole.log("original Array: ", array1)  // Printing the indexconsole.log("index: ", index)
Output :
Example 2: When element is looked after some index “i”. Here element is present in the array but still the output is -1 because it is present at index 3 and the searching starts from index 5.
Javascript
// Requiring the lodash libraryconst _ = require('lodash');  // Original arraylet array1 = [4, 2, 3, 1, 4, 2]  // Using lodash.findIndexlet index = _.findIndex(array1, (e) => {    return e == 1;}, 5);  // Print original Arrayconsole.log("original Array: ", array1)  // Printing the indexconsole.log("index: ", index)
Output:
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Tryit Editor v3.7

Tryit: HTML table rows
Program for Volume and Surface Area of Cuboid in C++

Cuboid is a three-dimensional object with six faces of rectangle shape which means it has sides of different length and breadth. The difference between a cube and cuboid is that a cube has equal length, height and breadth whereas in cuboids these three are not same
Properties of cuboid are −
six faces
12 edges
8 vertices
Given below is the figure of cube
Given with the length, width and volume, the task is to find the total surface area and volume of a cuboid where surface area is the space occupied by the faces and volume is the space that a shape can contain.
To calculate surface area and volume of a cuboid there is a formula
Surface Area = 2(|*w + w * h + |*h )
Volume = L* W * H
Input-: L=3 H=2 W=3
Output-: Volume of cuboid is: 18
   Total Surface Area of cuboid is: 42
Start
Step 1 -> declare function to find volume of cuboid
   double volume(double l, double h, double w)
      return (l*h*w)
Step 2 -> declare function to find area of cuboid
   double surface_area(double l, double h, double w)
      return (2 * l * w + 2 * w * h + 2 * l * h)
Step 3 -> In main()
   Declare variable double l=3, h=2 and w=3
   Print volume(l,h,w)
   Print surface_area(l, h ,w)
Stop
#include <bits/stdc++.h>
using namespace std;
//function for volume of cuboid
double volume(double l, double h, double w){
   return (l * h * w);
}
//function for total surface area of cuboid
double surface_area(double l, double h, double w){
   return (2 * l * w + 2 * w * h + 2 * l * h);
}
int main(){
   double l = 3;
   double h = 2;
   double w = 3;
   cout << "Volume of cuboid is: " <<volume(l, h, w) << endl;
   cout << "Total Surface Area of cuboid is: "<< surface_area(l, h, w);
   return 0;
}
Volume of cuboid is: 18
Total Surface Area of cuboid is: 42
Underscore.js - GeeksforGeeks

17 Dec, 2021
Underscore.js is a lightweight JavaScript library and not a complete framework that was written by Jeremy Ashkenas. It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore.js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.js.
With just under six kilobytes in size, this library basically provides us with a whole bunch of useful JavaScript functions for making our life easier. There are literally hundreds of different functions available that support both our workaday functional helpers such as the map and filter functions, as well as more specialized ones such as JavaScript templating, function binding, deep equality testing, creating quick indexes, and many more. Underscore functions basically falls under four major categories which are functions that can be used for manipulating arrays, functions that can be used for manipulating objects, functions that can be used for manipulating both arrays as well as objects, and functions that can be used for manipulating other functions itself.
Installation Process: We can use Underscore.js directly inside the browser and also with node.js. We will discuss both of these methods.
 
Method 1: Use directly inside the browser. 
Visit the official website (https://underscorejs.org/) and download the latest underscore-min.js file UMD available. After that include the following CDN link inside your code in order to run the underscore.js code inside the browser.
Method 2: We can install it with npm. Make sure that you have Node.js and npm installed.
npm install underscore
You can also install with yarn
yarn install underscore
Now let’s understand the working of code through an example.
Example: In this example, we will simply see how to find the maximum element from the array list passed. For this, we will use _.max() Function.
HTML
Output:
Features of Underscore:
Perform common operations of data like arrays, objects, JSON files, etc.
Compatible with other JS libraries like jQuery to perform DOM operations.
Contains function for data manipulation.
Learn more about Underscore.js:
Introduction
Collections Complete Reference
Array Complete Reference
Functions Complete Reference
Objects Complete Reference
Utility Complete Reference
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Python Program for Breadth First Search or BFS for a Graph
Python Program for Find the number of islands | Set 1 (Using DFS)
Pandas - Number of Months Between Two Dates
7 Reasons Why You Should Learn SQL in 2022
Psycopg2 - Return dictionary like values
Java Program to Rotate bits of a number
How to connect MongoDB with ReactJS ?
How to use Material-UI with Next.js ?
Packaged Task | Advanced C++ (Multithreading & Multiprocessing)
How to Fix: ValueError: Operands could not be broadcast together with shapes?
How to store array values in MongoDB?

Let us first create a collection with documents wherein we are storing array values −
>db.demo321.insertOne({"UserDetails":[{"UserId":101,"UserName":"Chris"},{"UserId":102,"UserName":"Mike"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e511248f8647eb59e56206a")
}
>db.demo321.insertOne({"UserDetails":[{"UserId":103,"UserName":"Bob"},{"UserId":104,"UserName":"Sam"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e511259f8647eb59e56206b")
}
Display all documents from a collection with the help of find() method −
> db.demo321.find();
This will produce the following output −
{ "_id" : ObjectId("5e511248f8647eb59e56206a"), "UserDetails" : [ { "UserId" : 101, "UserName" : "Chris" }, { "UserId" : 102, "UserName" : "Mike" } ] }
{ "_id" : ObjectId("5e511259f8647eb59e56206b"), "UserDetails" : [ { "UserId" : 103, "UserName" : "Bob" }, { "UserId" : 104, "UserName" : "Sam" } ] }
C program to compare the structure variables

In C programming language, a structure is a collection of different datatype variables, which are grouped together under a single name.
Declaration and initialization of structures
The general form of a structure declaration is as follows −
datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};
Here,
struct is a keyword.
tagname specifies the name of structure.
member1, member2 specifies the data items that make up structure.
For example,
struct book{
   int pages;
   char author [30];
   float price;
};
There are three methods of declaring structure variables, which are as follows −
First method
struct book{
   int pages;
   char author[30];
   float price;
}b;
Second method
struct{
   int pages;
   char author[30];
   float price;
}b;
Third method
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;
Initialization and accessing of structures
The link between a member and a structure variable is established by using a member operator (or) a dot operator.
Initialization can be done in the following methods −
First method
struct book{
   int pages;
   char author[30];
   float price;
} b = {100, “balu”, 325.75};
Second method
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b = {100, “balu”, 325.75};
Third method by using a member operator
struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;
Following is the C program for the comparison of structure variables −
 Live Demo
struct class{
   int number;
   char name[20];
   float marks;
};
main(){
   int x;
   struct class student1 = {001,"Hari",172.50};
   struct class student2 = {002,"Bobby", 167.00};
   struct class student3;
   student3 = student2;
   x = ((student3.number == student2.number) &&
   (student3.marks == student2.marks)) ? 1 : 0;
   if(x == 1){
      printf("\nstudent2 and student3 are same\n\n");
      printf("%d %s %f\n", student3.number,
      student3.name,
      student3.marks);
   }
   else
   printf("\nstudent2 and student3 are different\n\n");
}
When the above program is executed, it produces the following output −
student2 and student3 are same
2 Bobby 167.000000
Delete duplicates in a Pandas Dataframe based on two columns - GeeksforGeeks

11 Dec, 2020
A dataframe is a two-dimensional, size-mutable tabular data structure with labeled axes (rows and columns). It can contain duplicate entries and to delete them there are several ways. 
Let us consider the following dataset.
The dataframe contains duplicate values in column order_id and customer_id. Below are the methods to remove duplicate values from a dataframe based on two columns.
Method 1: using drop_duplicates() 
Approach:
We will drop duplicate columns based on two columns
Let those columns be ‘order_id’ and ‘customer_id’
Keep the latest entry only
Reset the index of dataframe
Below is the python code for the above approach.
Python3
# import pandas libraryimport pandas as pd  # load datadf1 = pd.read_csv("super.csv")  # drop rows which have same order_id# and customer_id and keep latest entrynewdf = df1.drop_duplicates(  subset = ['order_id', 'customer_id'],  keep = 'last').reset_index(drop = True)  # print latest dataframedisplay(newdf)
Output:
Method 2: using groupby()
Approach:
We will group rows based on two columns
Let those columns be ‘order_id’ and ‘customer_id’
Keep the first entry only
The python code for the above approach is given below.
Python3
# import pandas libraryimport pandas as pd  # read datadf1 = pd.read_csv("super.csv")  # group data over columns 'order_id'# and 'customer_id' and keep first entry onlynewdf1 = df1.groupby(['order_id', 'customer_id']).first()  # print new dataframeprint(newdf1)
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
DAX Aggregation - TOPN function

Returns the top specified number of rows of the table.
TOPN (<n_value>, <table>, <orderBy_expression>, [<order>],
   [<orderBy_expression>, [<order>]] ...) 

n_value
The number of rows to return.
It is any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context).
table
Any DAX expression that returns a table of data from where to extract the top n_value number of rows.
orderBy_expression
Any DAX expression where the result value is used to sort the table and it is evaluated for each row of table.
order
Optional.
A value that specifies how to sort orderBy_expression values, ascending or descending −
0 (zero) or FALSE − Sorts in a descending order of values of orderBy_expression.
1 or TRUE − Sorts in an ascending order of orderBy_expression. If omitted, default is 0.
Returns a table with the top n_value number of rows of table, if n_value > 0.
Returns an empty table, if n_value <= 0.
Rows are not necessarily sorted in any particular order.
If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows.
If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows.
TOPN does not guarantee any sort order for the results.
TOPN does not guarantee any sort order for the results.
= SUMX (TOPN (15,Sales,Sales[Salesperson],ASC),Sales[Sales Amount]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Max Chunks To Make Sorted II in C++

Suppose we have an array arr of integers, we have to split the array into some number of partitions, and individually sort each partition. Now after concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made?
So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], [4], [5], [5].
To solve this, we will follow these steps −
cnt := 1
cnt := 1
n := size of arr
n := size of arr
Define an array maxOfLeft of size n
Define an array maxOfLeft of size n
Define an array minOfRight of size n
Define an array minOfRight of size n
maxOfLeft[0] := arr[0]
maxOfLeft[0] := arr[0]
for initialize i := 1, when i < n, update (increase i by 1), do −maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]
for initialize i := 1, when i < n, update (increase i by 1), do −
maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]
maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]
minOfRight[n - 1] = arr[n - 1]
minOfRight[n - 1] = arr[n - 1]
for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]
for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −
minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]
minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]
for initialize i := 0, when i < n - 1, update (increase i by 1), do −if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1)
for initialize i := 0, when i < n - 1, update (increase i by 1), do −
if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1)
if minOfRight[i + 1] >= maxOfLeft[i], then −
(increase cnt by 1)
(increase cnt by 1)
return cnt
return cnt
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxChunksToSorted(vector<int>& arr) {
      int cnt = 1;
      int n = arr.size();
      vector<int> maxOfLeft(n);
      vector<int> minOfRight(n);
      maxOfLeft[0] = arr[0];
      for (int i = 1; i < n; i++)
         maxOfLeft[i] = max(maxOfLeft[i - 1], arr[i]);
         minOfRight[n - 1] = arr[n - 1];
      for (int i = n - 2; i >= 0; i--)
         minOfRight[i] = min(minOfRight[i + 1], arr[i]);
      for (int i = 0; i < n - 1; i++) {
         if (minOfRight[i + 1] >= maxOfLeft[i])
         cnt++;
      }
      return cnt;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,2,4,5,5};
   cout << (ob.maxChunksToSorted(v));
}
{3,2,4,5,5}
4
PyQtGraph – Plot Window

06 Sep, 2021
In this article we will see how we can create plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics (by default, at the top), and the Control Panel (by default, at the bottom). The Control Panel is where you configure what will be plotted. For a simple scatter plot it may just be a case of selecting what columns to plot against each other, but it can get quite detailed. 
In order to do this we use plot method with the pyqtgraphSyntax : pg.plot() Argument : It takes no argumentReturn : It returns PlotWindow object  
Below is the implementation  
Python3
# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = "GeeksforGeeks PyQtGraph" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g',                           symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b',                             symbolBrush = 0.2, name ='blue')   # main methodif __name__ == '__main__':         # importing system    import sys         # Start Qt event loop unless running in interactive mode or using    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):        QtGui.QApplication.instance().exec_()
Output :  
 
sagar0719kumar
Python-gui
Python-PyQtGraph
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
numpy.nan_to_num() in Python

28 Nov, 2018
numpy.nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number.
Syntax : numpy.nan_to_num(arr, copy=True)
Parameters :arr : [array_like] Input data.copy : [bool, optional] Whether to create a copy of arr (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True.
Return : [ndarray] New Array with the same shape as arr and dtype of the element in arr with the greatest precision. If arr is inexact, then NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype. If arr is not inexact, then a copy of arr is returned.
Code #1 : Working
# Python program explaining# numpy.nan_to_num() function  import numpy as geekin_num = geek.nan  print ("Input  number : ", in_num)    out_num = geek.nan_to_num(in_num) print ("output  number : ", out_num) 
Output :
Input  number :  nan
output  number :  0.0

 Code #2 :
# Python program explaining# numpy.nan_to_num function  import numpy as geek  in_arr = geek.array([[2, geek.inf, 2], [2, 2, geek.nan]])   print ("Input array : ", in_arr)     out_arr = geek.nan_to_num(in_arr) print ("output array: ", out_arr) 
Output :
Input array :  [[  2.  inf   2.]
 [  2.   2.  nan]]
output array:  [[  2.00000000e+000   1.79769313e+308   2.00000000e+000]
 [  2.00000000e+000   2.00000000e+000   0.00000000e+000]]

 Code #3 :
# Python program explaining# numpy.nan_to_num function  import numpy as geek  in_arr = geek.array([[2, 2, 2], [2, 2, 6]])   print ("Input array : ", in_arr)     out_arr = geek.nan_to_num(in_arr) print ("Output array: ", out_arr) 
Output :
Input array :  Input array :  [[2 2 2]
 [2 2 6]]
Output array:  [[2 2 2]
 [2 2 6]]

Python numpy-Mathematical Function
Python-numpy
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
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Select rows of a matrix in R that meet a condition

26 Sep, 2021
A large dataset is often required to be filtered according to our requirements. In this article, we will be discussing how we can select a row from a matrix in R that meets the condition. For better understanding let’s understand the problem statement with the help of an example.
Example:
Data in use:
1
Maruti
Diesel
Red
2001
2
Hyundai
Petrol
Blue
2011
3
Tata
Petrol
Red
2013
4
Ford
Diesel
Red
2012
5
Nissan
Petrol
Blue
2021
6
Toyota
Diesel
Red
2021
Now, as the problem statement is that we want to select the rows of the matrix that meets the given condition. Suppose we want to select the rows from the matrix whose car_color = Red.
Then, the output must look like this:
            
    car_models   
    car_type   
    car_color   
   year  
1
Maruti
Diesel
Red
2001
2
Tata
Petrol
Red
2013
3
Ford
Diesel
Red
2012
4
Toyota
Diesel
Red
2021
Approach:
Create dataset
Specify the condition
Pass it to the matrix
Select rows which specify this condition
Syntax:
dataset[condition]
Example:
mat[mat[,”car_color”]==”Red”,]
Here, Comma(‘,’) is used to return all the matrix rows.
Copy the resultant dataset to auxiliary dataset
Display dataset
Example:
R
# Creating Dataset car_models <- c('Maruti','Hyundai','Tata',                'Ford','Nissan','Toyota') car_type <- c('Diesel','Petrol','Petrol',              'Diesel','Petrol','Diesel') car_color <- c('Red','Blue','Red',               'Red','Blue','Red') year <- c(2001,2011,2013,2012,2021,2021) # Storing matrix in mat (variable)mat <- cbind(car_models,car_type,car_color,year) # condition to select only rows with# color = Redmat <- mat[mat[,"car_color"]=="Red",] # displaying the resultant matrixmat
Output:
Resultant Matrix
akshaysingh98088
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Google Colab - Graphical Outputs

Colab also supports rich outputs such as charts. Type in the following code in the Code cell.
import numpy as np
from matplotlib import pyplot as plt

y = np.random.randn(100)
x = [x for x in range(len(y))]

plt.plot(x, y, '-')
plt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6)

plt.title("Sample Plot")
plt.show()

Now, if you run the code, you will see the following output −
Note that the graphical output is shown in the output section of the Code cell. Likewise, you will be able to create and display several types of charts throughout your program code.
Now, as you have got familiar with the basics of Colab, let us move on to the features in Colab that makes your Python code development easier.
Java | Date format validation using Regex

30 Oct, 2018
We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled.
// Java program to check if given date is// valid or not.import java.util.regex.Matcher;import java.util.regex.Pattern;  public class GeeksforGeeks {      // Returns true if d is in format    // /dd/mm/yyyy    public static boolean isValidDate(String d)    {        String regex = "^(1[0-2]|0[1-9])/(3[01]"                       + "|[12][0-9]|0[1-9])/[0-9]{4}$";        Pattern pattern = Pattern.compile(regex);        Matcher matcher = pattern.matcher((CharSequence)d);        return matcher.matches();    }      public static void main(String args[])    {        System.out.println(isValidDate("10/12/2016"));        System.out.println(isValidDate("10/02/18"));    }}
true
false

More ways to validate a date :
SimpleDateFormat class. We can use parse method of this class to validate the date.Writing our own method to check if a date is valid.
SimpleDateFormat class. We can use parse method of this class to validate the date.
Writing our own method to check if a date is valid.
date-time-program
Java-Date-Time
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
JSF - ui:remove Tag

ui:remove tag is used to prevent the JSF specific code to be rendered on the client side. It is used especially to prevent commented out code to be rendered on the client side.
<!-- JSF code commented out -->
<!-- 
<h:commandButton value = "Ok" />  
-->

<!-- JSF code commented out -->
<!-- 
&lt;h:commandButton value = "Ok" /&gt;  
-->

Now using remove tag we'll see the following change in rendered output.
<!-- JSF code commented out -->
<ui:remove>
   <h:commandButton value = "Ok" />  
</ui:remove>
<!-- JSF code commented out -->

Let us create a test JSF application to test the template tags in JSF.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:ui = "http://java.sun.com/jsf/facelets">
   
   <h:head>
      <title>JSF tutorial</title>			
   </h:head>
   
   <h:body>	
      <ui:remove>
         <h:commandButton value = "Ok" />  
      </ui:remove>
      
      <!--
         <h:commandButton value = "Cancel" />  
      -->
   </h:body> 
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, you'll see an empty page.
View source of the page and you will see the following html text.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
   <head>
      <title>JSF tutorial</title>
   </head>
   
   <body>
      <!--
         &lt;h:commandButton value = "Cancel" /&gt;  
      -->
   </body>
</html>

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
SQLAlchemy ORM - Creating Session

In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
The session object is then set up using its default constructor as follows −
session = Session()
Some of the frequently required methods of session class are listed below −
begin()
begins a transaction on this session
add()
places an object in the session. Its state is persisted in the database on next flush operation
add_all()
adds a collection of objects to the session
commit()
flushes all items and any transaction in progress
delete()
marks a transaction as deleted
execute()
executes a SQL expression
expire()
marks attributes of an instance as out of date
flush()
flushes all object changes to the database
invalidate()
closes the session using connection invalidation
rollback()
rolls back the current transaction in progress
close()
Closes current session by clearing all items and ending any transaction in progress

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
How to get file link from google cloud storage using Node.js ? - GeeksforGeeks

08 Jan, 2021
To get the signed public link of a file from the firebase storage, we need a reference to the file in Google cloud storage. As we just have a path to that file in storage we would first need to create a reference to that object and then get a signed link to that file.
Steps to generate a public link to a file in storage using the file path:
Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage.Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step.
Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage.
Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step.
Module Installation: Install the module using the following command:
npm install @google-cloud/storage
The method getSignedUrl() tasks a config object as input and returns a Promise that resolves with the download URL or rejects if the fetch failed, including if the object did not exist.
Example: Filename: index.js 
Javascript
// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');  // Creates a clientconst storage = new Storage();  var bucketName = 'geeksforgeeks'; var fileName = 'gfg.png';  // Create a reference to the file to generate linkvar fileRef = storage.bucket(bucketName).file(fileName);  fileRef.exists().then(function(data) {  console.log("File in database exists ");});  const config = {  action: 'read',    // A timestamp when this link will expire  expires: '01-01-2026',};  // Get the link to that filefileRef.getSignedUrl(config, function(err, url) {  if (err) {    console.error(err);    return;  }      // The file is now available to  // read from this URL  console.log("Url is : " + url);});
Run the index.js file using the following command:
node index.js
Output: 
File in database existsUrl is : https://storage.googleapis.com/geeksforgeeks/gfg.png?X-Goog-Algorithm=[token]
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Product of all leaf nodes of binary tree in C++

Given with a binary tree containing nodes and the task is to find the product of all the leaf nodes of a given binary tree.
Leaf nodes are the end nodes which don’t have any children. In a tree, a node can act as a parent node or child node except the root node which can only be a parent node. So the nodes with right and left pointer as NULL are the leaf nodes.
Input 
Output 
Leaf nodes are -: 23, 34, 25
Product-: 23*34*25 = 19550
Input the node data
Input the node data
Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal.
Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal.
Store those nodes with right and left pointer being NULL into a temporary variable to find the product.
Store those nodes with right and left pointer being NULL into a temporary variable to find the product.
Print the value of a temporary variable holding the multiplied values.
Print the value of a temporary variable holding the multiplied values.
Start
Step 1 → create structure of a node and temp, next and head as pointer to a
   structure node
      struct node
         int data
         Create node *left, *right
      End
Step 2 → declare function to insert a node in a tree
   node* new_node(int data)
      Set node* temp = new node()
      Set temp→data = data
      Set temp→left = temp→right = NULL
      return temp
   End
Step 3 → Declare a function to find product of all the leaf nodes
   void leaf(node* root, int &product)
      IF (!root)
         Return
      End
      IF (!root→left && !root→right)
         Set product *= root→data
         Call leaf(root→left, product)
         Call leaf(root→right, product)
Step 4 → In main()
   Create node* root = new_node(10)
   Set root→left = new_node(20)
   Set root→left→left = new_node(30)
   Set int product = 1
   Call leaf(root, product)
   Display product
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//structure of a node
struct node{
   int data;
   node *left, *right;
};
//function to create a new leaf of a tree
node* new_node(int data){
   node* temp = new node();
   temp→data = data;
   temp→left = temp→right = NULL;
   return temp;
}
//function to find the product of all leaf nodes of a tree
void leaf(node* root, int &product){
   if (!root)
      return;
   if (!root→left && !root->right)
      product *= root→data;
   leaf(root→left, product);
   leaf(root→right, product);
}
int main(){
   node* root = new_node(10);
   root→left = new_node(20);
   root→left→left = new_node(30);
   root→left→right = new_node(40);
   root→right = new_node(50);
   root→right→right = new_node(60);
   root→right→left = new_node(70);
   int product = 1;
   leaf(root, product);
   cout<<"product of a leaf nodes are :"<<product;
   return 0;
}
If run the above code it will generate the following output −
product of a leaf nodes are :5040000
Can I get Age using BirthDate column in a MySQL query?

To get Age using BirthDate column in a MySQL query, you can use datediff(). Let us first create a table:
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   DateOfBirth date
);
Query OK, 0 rows affected (1.46 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(DateOfBirth) values('2010-01-21');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(DateOfBirth) values('1993-04-02');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(DateOfBirth) values('1999-12-01');
Query OK, 1 row affected (1.53 sec)
mysql> insert into DemoTable(DateOfBirth) values('1998-11-16');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(DateOfBirth) values('2004-03-19');
Query OK, 1 row affected (0.11 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+----+-------------+
| Id | DateOfBirth |
+----+-------------+
|  1 | 2010-01-21  |
|  2 | 1993-04-02  |
|  3 | 1999-12-01  |
|  4 | 1998-11-16  |
|  5 | 2004-03-19  |
+----+-------------+
5 rows in set (0.00 sec)
Let us now get Age using birthdate column with DATEDIFF() method:
mysql> select cast(DATEDIFF(curdate(),DateOfBirth) / 365.25 AS UNSIGNED) AS AGE from DemoTable;
This will produce the following output:
+------+
| AGE  |
+------+
|    9 |
|   26 |
|   19 |
|   20 |
|   15 |
+------+
5 rows in set (0.00 sec)
Let us now write a query to get the DOB and ID where Age is between 20 and 26:
mysql> SELECT *FROM DemoTable WHERE YEAR(CURDATE())-YEAR(DateOfBirth)
BETWEEN 20 AND 26;
This will produce the following output:
+----+-------------+
| Id | DateOfBirth |
+----+-------------+
|  2 | 1993-04-02  |
|  3 | 1999-12-01  |
|  4 | 1998-11-16  |
+----+-------------+
3 rows in set (0.00 sec)
Explain the concept of an array within a structure in C programming

An array of structure in C programming is a collection of different datatype variables, grouped together under a single name.
General form of structure declaration
The structural declaration is as follows −
struct tagname{
   datatype member1;
   datatype member2;
   datatype member n;
};
Here, struct is the keyword.
tagname specifies the name of structure.
member1, member2 specifies the data items that make up structure.
The following example shows the usage of array within a structure in C programming −
struct book{
   int pages;
   char author [30];
   float price;
};
Following is the C program to demonstrate the use of an array within a structure −
 Live Demo
#include <stdio.h>
// Declaration of the structure candidate
struct candidate {
   int roll_no;
   char grade;
   // Array within the structure
   float marks[4];
};
// Function to displays the content of
// the structure variables
void display(struct candidate a1){
   printf("Roll number : %d\n", a1.roll_no);
   printf("Grade : %c\n", a1.grade);
   printf("Marks secured:\n");
   int i;
   int len = sizeof(a1.marks) / sizeof(float);
   // Accessing the contents of the
   // array within the structure
   for (i = 0; i < len; i++) {
      printf("Subject %d : %.2f\n",
      i + 1, a1.marks[i]);
   }
}
// Driver Code
int main(){
   // Initialize a structure
   struct candidate A= { 1, 'A', { 98.5, 77, 89, 78.5 } };
   // Function to display structure
   display(A);
   return 0;
}
When the above program is executed, it produces the following result −
Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00
Subject 3 : 89.00
Subject 4 : 78.50
JSF - f:validateDoubleRange

f:validateDoubleRange tag is used to validate a value to a range of float values.
<f:validateDoubleRange minimum = "1000.50" maximum = "10000.50" />

minimum
Minimum long value within an optional range
maximum
Maximum long value within an optional range
Let us create a test JSF application to test the above tag.
package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   private double salary;
 
   public double getSalary() {
      return salary;
   }
   
   public void setSalary(double salary) {
      this.salary = salary;
   }
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:f = "http://java.sun.com/jsf/core">
   
   <h:head>
      <title>JSF tutorial</title>			
   </h:head>
   
   <h:body>  
      <h2>h:validateDoubleRange Example</h2>
   
      <h:form>
         <h:inputText id = "salaryInput" value = "#{userData.salary}" 
            label = "salary" >
            <f:validateDoubleRange minimum = "1000.50" maximum = "10000.50" />
         </h:inputText>			
         <h:commandButton value = "submit" action = "result"/>
         <h:message for = "salaryInput" style = "color:red" />
      </h:form>  
   
   </h:body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:f = "http://java.sun.com/jsf/core"    
   xmlns:h = "http://java.sun.com/jsf/html">
   
   <h:head>
      <title>JSF Tutorial!</title>   
   </h:head>
   
   <h:body>
      <h2>Result</h2>
      Salary: #{userData.salary}
   </h:body>
</html>  
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Enter an invalid value. Following will be the output.
Enter a valid value. Following will be the output.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
Java Delete Files

To delete a file in Java, use the delete() method:
import java.io.File;  // Import the File class

public class DeleteFile {
  public static void main(String[] args) { 
    File myObj = new File("filename.txt"); 
    if (myObj.delete()) { 
      System.out.println("Deleted the file: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the file.");
    } 
  } 
}
The output will be:
You can also delete a folder. However, it must be empty:
import java.io.File; 

public class DeleteFolder {
  public static void main(String[] args) { 
    File myObj = new File("C:\\Users\\MyName\\Test"); 
    if (myObj.delete()) { 
      System.out.println("Deleted the folder: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the folder.");
    } 
  } 
}
The output will be:
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.
Scala String endsWith() method with example - GeeksforGeeks

03 Oct, 2019
The endsWith() method is utilized to check if the stated string ends with the suffix stated in the argument.
Method Definition: Boolean endsWith(String suffix)Return Type: It returns true if the string ends with the suffix stated else it returns false.
Example #1:
// Scala program of endsWith()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1= "Nidhi"                  // Applying endsWith() method        val result = m1.endsWith("i")                  // Displays output        println(result)          }} 
true

Example #2:
// Scala program of endsWith()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1= "Nidhi"                  // Applying endsWith() method        val result = m1.endsWith("y")                  // Displays output        println(result)          }} 
false

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List filter() method with example
Scala Map
Type Casting in Scala
Scala Lists
Class and Object in Scala
Scala List contains() method with example
Break statement in Scala
Operators in Scala
numpy.random.gamma() in Python - GeeksforGeeks

15 Jul, 2020
With the help of numpy.random.gamma() method, we can get the random samples of gamma distribution and return the random samples of numpy array by using this method.
gamma distribution
Syntax : numpy.random.gamma(shape, scale=1.0, size=None)
Return : Return the random samples of numpy array.
Example #1 :
In this example we can see that by using numpy.random.gamma() method, we are able to get the random samples from gamma distribution and return the random samples by using this method.
Python3
# import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt  # Using gamma() methodgfg = np.random.gamma(3, 20, 1000)  count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt  # Using gamma() methodgfg = np.random.gamma(4.98, 12, 40000)gfg1 = np.random.gamma(gfg, 13.46, 40000)  count, bins, ignored = plt.hist(gfg1, 50, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
Using Time datatype in MySQL without seconds?

You need to use DATE_FORMAT() for this. The syntax is as follows −
SELECT DATE_FORMAT(yourColumnName,'%k:%i') as anyAliasName FROM yourTableName;
You can use ‘%H:%i’ for the same result. To understand the above syntax, let us create a table.
The query to create a table is as follows −
mysql> create table TimeDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> LastLoginTime time
   -> );
Query OK, 0 rows affected (0.56 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into TimeDemo(LastLoginTime) values('09:30:35');
Query OK, 1 row affected (0.20 sec)
mysql> insert into TimeDemo(LastLoginTime) values('10:45:30');
Query OK, 1 row affected (0.19 sec)
mysql> insert into TimeDemo(LastLoginTime) values('13:33:58');
Query OK, 1 row affected (0.24 sec)
mysql> insert into TimeDemo(LastLoginTime) values('15:45:31');
Query OK, 1 row affected (0.21 sec)
mysql> insert into TimeDemo(LastLoginTime) values('16:40:36');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from TimeDemo;
The following is the output −
+----+---------------+
| Id | LastLoginTime |
+----+---------------+
|  1 | 09:30:35      |
|  2 | 10:45:30      |
|  3 | 13:33:58      |
|  4 | 15:45:31      |
|  5 | 16:40:36      |
+----+---------------+
5 rows in set (0.00 sec)
Here is the query to get time without seconds. The query is as follows −
mysql> select DATE_FORMAT(LastLoginTime,'%k:%i') as `Time` from TimeDemo;
The following is the output −
+-------+
| Time  |
+-------+
| 9:30  |
| 10:45 |
| 13:33 |
| 15:45 |
| 16:40 |
+-------+
5 rows in set (0.00 sec)
You can change the format specifier like %H:%i to get the same result without seconds. The query is as follows −
mysql> select DATE_FORMAT(LastLoginTime,' %H:%i') as `Time` from TimeDemo;
The following is the output −
+--------+
| Time   |
+--------+
| 09:30  |
| 10:45  |
| 13:33  |
| 15:45  |
| 16:40  |
+--------+
5 rows in set (0.00 sec)