code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.axis.Axis.set_minor_locator() function in Python

03 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. 
The Axis.set_minor_locator() function in axis module of matplotlib library is used to set the locator of the minor ticker. 
Syntax: Axis.set_minor_locator(self, locator)
Parameters: This method accepts the following parameters. 
formatter: This parameter is the locator.
Return value: This method does not returns any value.  
Below examples illustrate the matplotlib.axis.Axis.set_minor_locator() function in matplotlib.axis:Example 1: 
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker           x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4]      tick_spacing = 0.4     fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_minor_locator(ticker.MultipleLocator(tick_spacing))    fig.suptitle("Matplotlib.axis.Axis.set_minor_locator()\n\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output:  
Example 2: 
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport datetime import matplotlib.pyplot as plt from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange import numpy as np     date1 = datetime.datetime(2020, 4, 2) date2 = datetime.datetime(2020, 4, 6) delta = datetime.timedelta(hours = 6) dates = drange(date1, date2, delta)     y = np.arange(len(dates))     fig, ax = plt.subplots() ax.plot_date(dates, y ** 2)     ax.set_xlim(dates[0], dates[-1])     ax.xaxis.set_major_locator(DayLocator()) Axis.set_minor_locator(ax.xaxis, HourLocator(range(0, 25, 6))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))     ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate()  fig.suptitle("Matplotlib.axis.Axis.set_minor_locator()\n\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output:  
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write an JDBC example for inserting value for Clob data type into a table?

Assume we already have a table named MyData in the database with the following description.
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| Name    | varchar(255) | YES  |     | NULL    |       |
| Article | longtext     | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
If you need to insert value int to the clob data type using a JDBC program you need to use the methods which reads the contents of a file and sets to the database rows. PreparedStatement interface provides such methods.
The void setCharacterStream(int parameterIndex, Reader reader) method sets the contents of the reader object as a value to the parameter at the given index. Other variant of this method are:
void setCharacterStream(int parameterIndex, Reader reader, int length)
void setCharacterStream(int parameterIndex, Reader reader, int length)
void setCharacterStream(int parameterIndex, Reader reader, long length)
void setCharacterStream(int parameterIndex, Reader reader, long length)
The void setClob(int parameterIndex, Clob x) method sets the given java.sql.Clob object as a value to the parameter at the given index. Other variant of this method are:
void setClob(int parameterIndex, Reader reader)
void setClob(int parameterIndex, Reader reader)
void setClob(int parameterIndex, Reader reader, long length)
void setClob(int parameterIndex, Reader reader, long length)
You can set value to the Clob data type using either of these methods.
Following example sets value to a Clob datatype using the setClob() method.
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertingValueInClob {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Inserting values
      String query = "INSERT INTO MyData(Name, Article ) VALUES (?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "JavaFX");
      FileReader reader = new FileReader("E:\\images\\javafx.txt");
      pstmt.setClob(2, reader);
      pstmt.execute();
      System.out.println("Data inserted");
   }
}
Connection established......
Table Created......
Contents of the table are:
JavaFX
E:\images\MyData_clob_output1.txt
If you try to view the clob value in the record using the MySQL work bench you can see the inserted text data as shown below:
jQuery | ready() with Examples

26 Sep, 2018
The ready() method is an inbuilt method in jQuery which helps to load the whole page then execute the rest code. This method specify the function to execute when the DOM is fully loaded.
Syntax:
$(document).ready(function)
Parameters: This method accepts single parameter function which is mandatory. It is used to specify the function to run after the document is loaded.
Return Value: This method returns the document after performing the ready() method.Below example illustrates the ready() method in jQuery:
Example:
<!DOCTYpe html><html>    <head>        <title>The ready Method</title>        <script src=        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">        </script>                  <!-- jQuery code to show the working of this method -->        <script>            $(document).ready(function(){                $("button").click(function(){                     $("p").css("color", "green");                     $("p").css("font-size", "40px");                     $("p").css("font-weight","bold")                 });         });      </script>      <style>         div {             text-align:center;             width: 60%;             min-height: 100px;             padding: 10px;             border: 2px solid green;         }      </style>   </head>   <body>      <div>         <p>Welcome to</p>         <p>GeeksforGeeks!</p>         <!-- click on this button -->         <button>Click Here!</button>      </div>   </body></html>
Output:
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Fast Walsh Hadamard Transform

31 Jan, 2022
Fast Walsh Hadamard Transform, is an Hadamard ordered efficient algorithm to compute the Walsh Hadamard transform (WHT). Normal WHT computation has N = 2m complexity but using FWHT reduces the computation to O(n2). The FWHT requires O(n logn) additions and subtraction operations. It is a divide and conquer algorithm which breaks down the WHT recursively.  
sympy.discrete.transforms.fwht( ) : It can perform Walsh Hadamard Transform (WHT). This method uses Hadamard sequence ordering. Automatically the sequence is padded with zero to the right because the radix-2 FWHT requires the sample point number as a power of 2.  
Parameters : 
-> seq : [iterable] sequence on which WHT is to be applied.

Returns : 
Fast Walsh Hadamard Transform Transform
Example #1 :  
Python3
# import sympyfrom sympy import fwht # sequenceseq = [23,       56,       12,       555] # hwhttransform = fwht(seq)print ("Transform  : ", transform)
Output :  
Transform  :  [646, -576, -488, 510]
Example #2 :  
Python3
# import sympyfrom sympy import fwht # sequenceseq = [15, 21, 13, 44] # hwhttransform = fwht(seq)print ("Transform  : ", transform)
Output :  
Transform  :  [93, -37, -21, 25]
 
varshagumber28
Maths
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Difference between string and StringBuffer in Java.

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.
Whereas, StringBuffer class is a thread-safe, mutable sequence of characters.
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
Live Demo
public class Sample {
   public static void main(String args[]) {
      String str = new String("Hi welcome to tutorialspoint");
      System.out.println(str);StringBuffer sBuffer = new StringBuffer("test");
      sBuffer.append(" String Buffer");
      System.out.println(sBuffer);
   }
}
Hi welcome to tutorialspoint
test String Buffer
HTML | placeholder Attribute

08 Dec, 2021
The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Syntax:  
<element placeholder="">
Elements: This method can have following attributes:  
<input> placeholder Attribute
<textarea> placeholder Attribute
Attribute: The attribute for each of the above element is placeholder. Example: With <input> element  
html
<!DOCTYPE html><html> <body>    <center>        <h1 style="font-size:25px;font-style:italic;">            GeeksforGeeks        </h1>        <h2 style="font-size:25px;font-style:italic;">        Placeholder Attribute in Input Element        </h2>        <form action=" ">            <input type="text" name="fname"                            placeholder="First name">            <br>            <input type="text" name="lname"                            placeholder="Last name">            <br>            <input type="submit" value="Submit">        </form></center></body> </html>
Output:  
Example: With <textarea> element  
html
<!DOCTYPE html><html> <body>    <center>        <h1 style="font-size:25px;font-style:italic;">        GeeksForGeeks        </h1>        <h2 style="font-size:25px;font-style:italic;">        Placeholder Attribute in Textarea Element        </h2>        Give your Intro:        <textarea rows="4" cols="40"        placeholder="Write something here about yourself...">        </textarea></center></body> </html>
Output:  
Supported Browsers: The browser supported by placeholder Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
GATE | GATE CS 2019 | Question 30

15 Feb, 2019
An array of 25 distinct elements is to be sorted using quicksort. Assume that the pivot element is chosen uniformly at random. The probability that the pivot element gets placed in the worst possible location in the first round of partitioning (rounded off to 2 decimal places) is _________.
Note: This was Numerical Type question.(A) 0.08(B) 0.0016(C) 0.04(D) 0.0008Answer: (A)Explanation: Given an array of 25 distinct elements, and pivot element is chosen uniformly randomly. So, there are only 2 worst case position in the pivot element is either first (or) last.
Therefore, required probability is,
= 2/25
= 0.08
So, option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find depth of a dictionary - GeeksforGeeks

27 Nov, 2018
Prerequisite: Nested dictionary
The task is to find the depth of given dictionary in Python. Let’s discuss all different methods to do this task.
Examples:
Input : {1:'a', 2: {3: {4: {}}}}
Output : 4

Input : {'a':1, 'b': {'c':'geek'}}
Output : 3

Approach #1 : Naive Alpproach
A naive approach in order to find the depth of a dictionary is to count the number of opening curly braces. But, one drawback of this approach is that it would only work if the input is correct.
# Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1):           str_dic = str(dic)    counter = 0    for i in str_dic:        if i == "{":            counter += 1    return(counter)   # Driver code dic = {1:'Geek', 2: {3: {4: {}}}}print(dict_depth(dic))
4

 Approach #2: Using recursion
In this method we use recursion with max() function which picks the greatest depth for the current dictionary under scrutiny at each level.
# Python3 Program to find depth of a dictionarydef dict_depth(dic, level = 1):          if not isinstance(dic, dict) or not dic:        return level    return max(dict_depth(dic[key], level + 1)                               for key in dic)  # Driver code dic = {1:'a', 2: {3: {4: {}}}}  print(dict_depth(dic))
4

Another version of the recursive solution is to use map() function by which the values of the inner dictionary is mapped to the called function.
# Python3 Program to find depth of a dictionarydef dict_depth(my_dict):    if isinstance(my_dict, dict):                  return 1 + (max(map(dict_depth, my_dict.values()))                                    if my_dict else 0)              return 0  # Driver code my_dict = {1:'a', 2: {3: {4: {}}}}print(dict_depth(my_dict))
4

 Approach #3: Iterative Solution
In this approach, we save the nested key and its initial depth in a variable, say p_dict. Now, start a loop for p_dict, and keep popping values while digging deeper for nested dictionaries.
# Python3 Program to find depth of a dictionarydef dict_depth(myDict):      Ddepth = 1    obj = [(k, Ddepth + 1) for k in myDict.values()                          if isinstance(k, dict)]    max_depth = 0          while(obj):        n, Ddepth = obj.pop()        max_depth = max(max_depth, Ddepth)                  obj = obj + [(k, Ddepth + 1) for k in n.values()                                 if isinstance(k, dict)]              return max_depth      # Driver code myDict = {1:'a', 2: {3: {4:{}}}}print(dict_depth(myDict))
4

Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Remove Multiple Columns from data.table in R - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to remove multiple columns from data.table in the R Programming language.
Create data.table for demonstration:
R
# load the data.table packagelibrary("data.table")  # create a data.table with 4 columns# they are id,name,age and address  data = data.table(id = c(1,2,3) ,                  name = c("sravan","bobby","satwik"),                  age = c(23,21,17),                  address = c("kakumanu","ponnur","hyd"))  # displaydata
Output:
Here we are going to remove multiple columns by using the index operator []
Syntax: data[ ,’:='(column1 = NULL, column2 = NULL, column n=NULL)]  
where
data is the input data.table
column is the columns to be removed
:= is the operator to be loaded in the data.table
Example 1: R program to remove multiple columns from data.table
R
# load the data.table packagelibrary("data.table")  # create a data.table with 4 columns# they are id,name,age and address  data = data.table(id = c(1,2,3),                  name = c("sravan","bobby","satwik"),                  age = c(23,21,17),                  address = c("kakumanu","ponnur","hyd"))  # remove age , name and address columnsdata[ ,':='(age = NULL, address = NULL, name=NULL)]    # displaydata
Output:
Example 2: Remove only one column from data.table
R
# load the data.table packagelibrary("data.table")  # create a data.table with 4 columns# they are id,name,age and address  data = data.table(id = c(1,2,3),                  name = c("sravan","bobby","satwik"),                  age = c(23,21,17),                  address = c("kakumanu","ponnur","hyd"))  # remove id columndata[ ,':='(id=NULL)]    # displaydata
Output:
Example 3: R program to remove all columns
R
# load the data.table packagelibrary("data.table")  # create a data.table with 4 columns# they are id,name,age and address  data = data.table(id = c(1,2,3),                  name = c("sravan","bobby","satwik"),                  age = c(23,21,17),                  address = c("kakumanu","ponnur","hyd"))  # remove all columnsdata[ ,':='(id=NULL,age = NULL, address = NULL, name=NULL)]    # displaydata
Output:
Null data.table (0 rows and 0 cols)
Picked
R DataTable
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
Difference between Relative and Absolute Deadline of Real-time Task - GeeksforGeeks

28 Jan, 2022
1. Relative Deadline :The time interval between the start of the task and the completion of the real-time task is known as Relative deadline. It is basically the time interval between arrival and corresponding deadline of the real-time task.If the arrival time of task is ‘t’ and corresponding deadline of task is ‘t+d’ then,
Relative deadline = d 
2. Absolute Deadline :The time interval between the time 0 and the completion of the real-time task is known as Absolute deadline. It is basically the time interval between time 0 and corresponding deadline of the real-time task.If the arrival time is ‘t’ and corresponding deadline of task is ‘t+d’ then,
Absolute deadline = t+d 
Difference between Relative and Absolute Deadline of Real-time task :
shivambhat45
Difference Between
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Banker's Algorithm in Operating System
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Python | Pandas dataframe.at_time() - GeeksforGeeks

06 Aug, 2021
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.Pandasdataframe.at_time() function is used to select all the values in a row corresponding to the input time of the day. If the input time is not present in the dataframe then an empty dataframe is returned. 
Syntax: DataFrame.at_time(time, asof=False)Parameters: time : datetime.time or stringReturns: values_at_time : type of caller 
Note: at_time() function raises exception when the index of the dataframe is not a DatetimeIndexExample #1: Create a datetime indexed dataframe and retrieve the values at any specific time  
Python3
# importing pandas as pdimport pandas as pd # Creating row index values for dataframe# Taken time frequency to be of 12 hours interval # Generating five index value using "period = 5" parameterind = pd.date_range('01/ 01/2000', periods = 5, freq ='12H') # Creating a dataframe with 2 columns# using "ind" as the index for our dataframe df = pd.DataFrame({"A":[1, 2, 3, 4, 5],                   "B":[10, 20, 30, 40, 50]},                                 index = ind) # Printing the dataframe# for visualizationdf
Now find out the values at time “12:00” 
Python3
df.at_time('12:00')
Output :  
 Example #2: Set the frequency of date_time index for 30 minute duration and query for both valid and invalid time (Not present in the dataframe) . 
Python3
# importing pandas as pdimport pandas as pd # Creating row index values for our data frame# We have taken time frequency to be of 30 minutes interval# We are generating eight index value using "period = 8" parameter ind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using "ind" as the index for our dataframedf = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8],                   "B":[10, 20, 30, 40, 50, 60, 70, 80]},                                             index = ind) # Printing the dataframedf
Now let’s query for time “02:00” 
Python3
# Find the row values at time "02:00"df.at_time('02:00')
Output :  
 
saurabh1990aror
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
Python String | replace()
*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
How to Install Numpy on Linux? - GeeksforGeeks

30 Sep, 2021
Python NumPy is a general-purpose array processing package that provides tools for handling n-dimensional arrays. It provides various computing tools such as comprehensive mathematical functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive for programmers from any background.
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (Depending upon the user preference)
If you want the installation to be done through conda, you can use the below command:
conda install -c anaconda numpy
Type in “y” for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Use the below command to verify if the above package has successfully installed:
conda list numpy 
You will get a similar message as shown below if the installation has been successful:
Users who prefer to use pip can use the below command to install NumPy:
pip install numpy
You will get a similar message once the installation is complete:
It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment:
python3 -m venv my-env
Activate the virtual environment (ie, my-env) using the below command:
source my-env/bin/activate
Use the below command to check if the package has been successfully installed:
python3 -m pip show numpy
You will get a similar message as shown below if the installation is successful:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Lambda Function - Ruby - GeeksforGeeks

16 Aug, 2021
In Computer Programming, Lambda functions are anonymous functions. Lambda functions in Ruby are no different. Since everything in Ruby is treated as an object, lambdas are also objects in Ruby. Lambdas in Ruby allow us to wrap data and logic in a portable package.  
Syntax to create Lambda function in Ruby:
lambda = lambda {}  
Alternatively, we can also use literal lambda.  
lambda = ->() {}  
Lambda function is an instance of the Proc class of Ruby. 
# Creating a lambda function
my_lambda_function = lambda { puts " GeeksforGeeks " }

# Getting class of lambda
my_lambda_function.class
On Execution : 
Proc
Let’s define a lambda function 
my_lambda_function = lambda { puts "Hello, Geeks !" }
We have different ways to call this function. We can use my_lambda.call, my_lambda.() , my_lambda.[] or my_lambda.=== to call the lambda function . Example : 
Ruby
# Creating a lambda functionmy_lambda_function = lambda { puts "Hello, Geeks" }  # Different ways to call a lambda functionmy_lambda_function.call my_lambda_function.() my_lambda_function.[] my_lambda_function.===
Output:
Hello, Geeks
Hello, Geeks
Hello, Geeks
Hello, Geeks
To pass arguments in the lambda function, we can either use normal lambda syntax or use the literal lambda operator ” -> ” Example 1: 
# Creating lambda function with arguments 
# Using lambda keyword

lambda_with_args = lambda {| s | puts "Hello "+ s }

# Calling lambda function by passing arguments
lambda_with_args.call("Geeks")
Output: 
Hello Geeks
Example 2: 
Ruby
# Creating lambda function with arguments# Using literal lambda function lambda_with_args = -> (s) { puts "Hello "+ s } # Calling lambda function by passing argumentslambda_with_args.call("Geeks")
Output:
Hello Geeks
To use lambda functions along with a normal function, we can pass lambda function as an argument. Example: 
Ruby
# Lambda function to add 10add_10 = lambda { |num| num + 10 } # Lambda function to multiply with 2multiply_2 = lambda { |num| num * 2 } # A Function using lambdadef using_lambda_with_functions(lambda, number)   puts lambda.call(number) end  # Passing lambda to functionusing_lambda_with_functions(add_10, 10) using_lambda_with_functions(multiply_2, 20)
Output: 
20
40
simmytarika5
Picked
Ruby Function
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
Ruby | String gsub! Method
Any All in Python - GeeksforGeeks

25 Nov, 2020
Any and All are two built ins provided in python used for successive And/Or.
AnyReturns true if any of the items is True. It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.It short circuit the execution i.e. stop the execution as soon as the result is known.
Syntax : any(list of iterables)
# Since all are false, false is returnedprint (any([False, False, False, False]))  # Here the method will short-circuit at the# second item (True) and will return True.print (any([False, True, False, False]))  # Here the method will short-circuit at the# first (True) and will return True.print (any([True, False, False, False]))
Output :
False
True
True

 
AllReturns true if all of the items are True (or if the iterable is empty). All can be thought of as a sequence of AND operations on the provided iterables. It also short circuit the execution i.e. stop the execution as soon as the result is known.
Syntax : all(list of iterables)
# Here all the iterables are True so all# will return True and the same will be printedprint (all([True, True, True, True]))  # Here the method will short-circuit at the # first item (False) and will return False.print (all([False, True, True, False]))  # This statement will return False, as no# True is found in the iterablesprint (all([False, False, False]))
Output :
True
False
False

Practical Examples
# This code explains how can we # use 'any' function on list list1 = []list2 = []  # Index ranges from 1 to 10 to multiplyfor i in range(1,11):    list1.append(4*i)   # Index to access the list2 is from 0 to 9for i in range(0,10):    list2.append(list1[i]%5==0)  print('See whether at least one number is divisible by 5 in list 1=>')print(any(list2))
Output:
See whether at least one number is divisible by 5 in list 1=>
True

# Illustration of 'all' function in python 3  # Take two lists list1=[]list2=[]  # All numbers in list1 are in form: 4*i-3for i  in range(1,21):    list1.append(4*i-3)  # list2 stores info of odd numbers in list1for i in range(0,20):    list2.append(list1[i]%2==1)  print('See whether all numbers in list1 are odd =>')print(all(list2))
Output:
See whether all numbers in list1 are odd =>
True

Truth table :-
This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
pintusaini
Python-Built-in-functions
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Interfaces in Java
NFA machines accepting all strings that ends or not ends with substring 'ab' - GeeksforGeeks

24 Jun, 2019
Prerequisite: Finite Automata Introduction
Problem-1:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language ends with ‘ab’.
Explanation:The desired language will be like:
L1 = {ab, abbab, abaab, ...........}
Here as we can see that each string of the above language ends with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language does not end with ‘ab’.
L2 = {bba, abb, aaabbbb, .............}
The state transition diagram of the desired language will be like below:
In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself. The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’.
Problem-2:Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not ending with ‘ab’.
Explanation: The desired language will be like:
L1 = {bba, abb, aaabbbb, .............}
Here as we can see that each string of the above language is not ending with ‘ab’ but the below language is not accepted by this NFA because some of the string of below language is ending with ‘ab’.
L2 = {ab, abab, ababaab..............}
The state transition diagram of the desired language will be like below:
In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it remains in the state of itself and on getting ‘b’ as the input it transmits to a state ‘Y’. The state ‘Y’ on getting ‘b’ as the input it either remains in the state of itself or transmits to a final state ‘Z’. The final state ‘Z’ on getting ‘a’ as the input it remains in the state of itself.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between DFA and NFA
Introduction of Finite Automata
Construct Pushdown Automata for given languages
How to Right-align flex item? - GeeksforGeeks

01 Dec, 2020
CSS | flex-box
Flex-box is simply a web layout method that allows developers to align the elements easily and much more. The whole concept of flex-box depends on two major pillars: main-axis and cross-axis.
Representation of flex-box
To align the flex items left/right, We need to deal with the main-axis, which can be done using flex-box properties. A detailed explanation is given below:
Example 1:  Right aligning flex item using flex-direction property
<!DOCTYPE html><html><head><title>Right Alignment</title><style>  #container        {             width:600px;            height: 300px;             border: 5px solid black;             display: flex;             flex-direction: row-reverse;        }   #container div         {             width: 100px;             height: 50px;         } </style>  </head><body><div id="container">         <div style="background-color:#389900;">one</div>         <div style="background-color:#08ebb2;">two</div>         <div style="background-color:#dd2289;">three</div>         <div style="background-color:#fcff66;">four</div>      </div> </body></html>
When flex-direction is set as “row-reverse” it not only right aligns the flex items but reverses the order of the items also. In simple words, flex-items now expand from right to left as shown in the given figure.
Output:
Figure-1
Example 2:  Right aligning flex item using justify-content property
<!DOCTYPE html><html><head><title>Right alignment</title><style>  #container        {             width:600px;            height: 300px;             border: 5px solid black;             display: flex;             justify-content: flex-end;        }   #container div        {             width: 100px;             height: 50px;         } </style></head><body><div id="container">         <div style="background-color:#389900;">one</div>         <div style="background-color:#08ebb2;">two</div>         <div style="background-color:#dd2289;">three</div>         <div style="background-color:#fcff66;">four</div> </div></body></html>
When justify-content is set to “flex-end”, it instantly shifts all the flex-items to the end of the flex-container along the main-axis, i.e flex items get right aligned. It is different from the above-used method in terms of direction only as in this, flex-items will expand from left to right only. It will be more clear with the given figure.
Output:
Figure-2
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to convert timestamp string to datetime object in Python? - GeeksforGeeks

29 Aug, 2020
Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC.
You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.
Syntax:
fromtimestamp(timestamp, tz=None)
Example: Python timestamp to DateTime
Python3
from datetime import datetime    timestamp = 1545730073dt_obj = datetime.fromtimestamp(1140825600)  print("date_time:",dt_obj)print("type of dt:",type(dt_obj))
Output:
date_time: 2006-02-25 05:30:00
type of dt_obj: <class 'datetime.datetime'>

Here, we have imported the DateTime class from DateTime module. Then we have used datetime.fromtimestamp() class method which returns the local DateTime. 
To get a DateTime in a particular form in you can use strftime function. The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.
Example:
Python3
from datetime import datetime    timestamp = 1553367060dt_obj = datetime.fromtimestamp(timestamp).strftime('%d-%m-%y')  print("date:",dt_obj)
Output:
date: 24-03-19

Python-datetime
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
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
get_window_position driver method - Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_window_position driver method in Selenium. get_window_position method gets the x, y position of the current window.
Syntax –
driver.get_window_position(windowHandle='current')
Example –Now one can use get_window_position method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.get_window_position(windowHandle='current')

To demonstrate, get_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get window position,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")    # get window positionprint(driver.get_window_position(windowHandle ='current'))
Output –Screenshot added –
Terminal output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
PostgreSQL – Import CSV File Into Table

28 Aug, 2020
In this article, we will discuss the process of importing a .csv file into a PostgreSQL table.
To do so we will require a table which can be obtained using the below command:
CREATE TABLE persons
(
  id serial NOT NULL,
  first_name character varying(50),
  last_name character varying(50),
  dob date,
  email character varying(255),
  CONSTRAINT persons_pkey PRIMARY KEY (id)
);
Now we create a .csv file in our sheet manager (eg: MS Excel or notepad) as shown below:
Our file is located as persons.csv at C:\Users\RajuExample :To import this CSV file into the persons table, you use COPY statement as follows:
COPY persons(first_name, last_name, dob, email) 
FROM 'C:\Users\Raju' DELIMITER ', ' CSV HEADER;
Now, let us check the person table as follows:
SELECT * FROM persons;
It will lead to the below Output:
It is important to put the CSV file path after the FROM keyword. Because CSV file format is used, you need to mention the DELIMITER as well as ‘CSV’ keywords. The HEADER keyword indicates that the CSV file comprises a header line with column names. When importing data, PostgreSQL neglects the first line as they are the header line of the file.
The file must be read directly by the PostgreSQL server and not by the client application. Therefore, it must be accessible to the PostgreSQL server machine. Also, you can execute the COPY statement successfully if you have superusers access.
postgreSQL-utilities
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Compare Two Dates

26 Sep, 2021
In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in ‘yyyy-mm-dd’ format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.
Syntax:
 IF Boolean_expression    
   { sql_statement | statement_block }  
[ ELSE    
   { sql_statement | statement_block } ]  
We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @.
Syntax:
DECLARE @variable_name datatype;
Set values to the variable: We can assign values to the variables using the SET keyword.
Syntax:
SET @variable_name;
Now we take different cases to demonstrate of comparison between dates.
Query 1:
DECLARE @date1 DATE, @date2 DATE;                               
SET @date1='2021-01-01';
SET @date2='2021-02-02';                                       
IF @date1=@date2                                                
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'              
ELSE SELECT 'date1 is greater';                         
Output:
Query 2: 
DECLARE @date1 DATE, @date2 VARCHAR(20);
SET @date1='2021-01-01';
SET @date2='2021-01-01';
IF @date1=@date2
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'
ELSE SELECT 'date1 is greater';
Output:
Query 3:
DECLARE @date1 DATE, @date2 VARCHAR(20);
SET @date1='2022-01-01';
SET @date2='2021-01-01';
IF @date1=@date2
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'
ELSE SELECT 'date1 is greater';
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
How we can put two divisions <div> side by side in HTML?

With CSS properties, you can easily put two <div> side by side in HTML. Use the CSS property float to achieve this.
With that, add height:100px and set margin.
You can try to run the following code to place two <div> side by side
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML div</title>
   </head>
   <body>
      <div style="width: 100px; float:left; height:100px; background:gray; margin:10px">
         First DIV
      </div>
      <div style="width: 100px; float:left; height:100px; background:yellow; margin:10px">
         Second DIV
      </div>
   </body>
</html>
What does javascript:void(0) mean?

11 Oct, 2019
You might have occasionally came across “javascript:void(0)” in an HTML Document. It is often used when inserting an expression in a web page might produce some unwanted effect. To remove this effect, “javascript:void(0)” is used. This expression returns undefined primitive value.This is often used with hyperlinks.Sometimes, you will decide to call some JavaScript from inside a link. Normally, when you click a link, the browser loads a brand new page or refreshes the same page (depending on the URL specified).But you most likely don’t desire this to happen if you have hooked up some JavaScript thereto link.
To prevent the page from refreshing, you could use void(0).
Using “#” in anchor tag: When writing the following code in the editor, the web page is refreshed after the alert message is shown.Example:
<!DOCTYPE html><html>  <head>    <title>without JavaScript:void(0)</title></head>  <body>    <center>        <h1 style="color:green">GeksforGeeks</h1>        <h3>without JavaScript:void(0)</h3>        <a href="#"            ondblclick="alert('Welcome to Geeks for Geeks')"> Double click on me </a>    </center></body>  </html>
Output:
Using “javascript:void(0);” in anchor tag: Writing “javascript:void(0);” in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily.Example:
<!DOCTYPE html><html>  <head>    <title>JavaScript:void(0)</title></head>  <body>    <center>        <h1 style="color:green">GeksforGeeks</h1>        <h3>JavaScript:void(0)</h3>        <a href="javascript:void(0);"            ondblclick="alert('Welcome to Geeks for Geeks')">Double click on me </a>    </center></body>  </html>
Output:
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.