code-rag-bench/online-tutorials huggingface dataset:
Python Program for Iterative Merge Sort - GeeksforGeeks

30 Dec, 2020
Following is a typical recursive implementation of Merge Sort that uses last element as pivot.
# Recursive Python Program for merge sort  def merge(left, right):    if not len(left) or not len(right):        return left or right      result = []    i, j = 0, 0    while (len(result) < len(left) + len(right)):        if left[i] < right[j]:            result.append(left[i])            i+= 1        else:            result.append(right[j])            j+= 1        if i == len(left) or j == len(right):            result.extend(left[i:] or right[j:])            break       return result  def mergesort(list):    if len(list) < 2:        return list      middle = len(list)/2    left = mergesort(list[:middle])    right = mergesort(list[middle:])      return merge(left, right)      seq = [12, 11, 13, 5, 6, 7]print("Given array is")print(seq); print("\n")print("Sorted array is")print(mergesort(seq))  # Code Contributed by Mohit Gupta_OMG 
Please refer complete article on Iterative Merge Sort for more details!
Merge Sort
python sorting-exercises
Python Programs
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python Program for Merge Sort
What is the difference between MySQL BOOL and BOOLEAN column data types?

BOOL and BOOLEAN both acts like TINYINT(1). You can say that both are synonyms for TINYINT(1).
Here is an example of BOOLEAN. The query to create a table with column boolean type.
mysql> create table Demo
   -> (
   -> isVaidUser boolean
   -> );
Query OK, 0 rows affected (1.08 sec)
The query to insert records in the table using insert command is as follows −
mysql> insert into Demo values(true);
Query OK, 1 row affected (0.19 sec)

mysql> insert into Demo values(0);
Query OK, 1 row affected (0.17 sec)
Display all values from the table using select command. The query is as follows −
mysql> select *from Demo;
+------------+
| isVaidUser |
+------------+
|          1 |
|          0 |
+------------+
2 rows in set (0.00 sec)
Here is an example of BOOL. The following is the query to create a table −
mysql> create table Demo1
   -> (
   -> isVaidUser bool
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into Demo1 values(1);
Query OK, 1 row affected (0.14 sec)

mysql> insert into Demo1 values(false);
Query OK, 1 row affected (0.16 sec)
Display all values from the table using select command. The query is as follows −
mysql> select *from Demo1;
+------------+
| isVaidUser |
+------------+
|          1 |
|          0 |
+------------+
2 rows in set (0.00 sec)
Look at the sample output, false is converted to 0. That means BOOL and BOOLEAN implicitly convert into tinyint(1).
How to display output in javascript?

There are 4 ways to display the output in JavaScript.
 Live Demo
<html>
<body>
<p id="display"></p>
<script>
   document.getElementById("display").innerHTML = 10 + 10;
</script>
</body>
</html>
20.
 Live Demo
<html>
<body>
<script>
   document.write(2 + 3);
</script>
</body>
</html>
5
 Live Demo
<html>
<body>
<script>
   console.log(2 + 3);
</script>
</body>
</html>
5.
 Live Demo
<html>
<body>
<script>
   alert(2 + 3);
</script>
</body>
</html>
5
In case of handling json strings, or some other big data console.log is the best choice.
Python | Pandas Timedelta.microseconds - GeeksforGeeks

14 Jan, 2019
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.
Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.microseconds property in pandas.Timedelta is used to return Number of microseconds.
Syntax: Timedelta.microseconds
Parameters: None
Returns: return the Number of microseconds.
Code #1:
# importing pandas as pd import pandas as pd   # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000030')   # Print the Timedelta object print(td)   print(td.microseconds)
3 days 06:05:01.000030
30

Code #2:
# importing pandas as pd import pandas as pd   # Create the Timedelta object td = pd.Timedelta('1 days 7 hours 254.1245 seconds')   # Print the Timedelta object print(td)   print(td.microseconds)
1 days 07:04:14.124500
124500

Code #3:
# importing pandas as pd import pandas as pd import datetime  # Create the Timedelta object td = pd.Timedelta(datetime.timedelta(days = 3, hours = 7, seconds = 8, microseconds = 545))   # Print the Timedelta object print(td)   print(td.microseconds)
3 days 07:00:08.000545
545

Python pandas-timedelta
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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
C++ Program to Implement the RSA Algorithm

RSA is an asymmetric cryptography algorithm which works on two keys-public key and private key.
Begin
   1. Choose two prime numbers p and q.
   2. Compute n = p*q.
   3. Calculate phi = (p-1) * (q-1).
   4. Choose an integer e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
   5. Calculate d as d ≡ e−1 (mod phi(n)); here, d is the modular multiplicative inverse of e modulo phi(n).
   6. For encryption, c = me mod n, where m = original message.
   7. For decryption, m = c d mod n.
End
 Live Demo
#include<iostream>
#include<math.h>
using namespace std;
// find gcd
int gcd(int a, int b) {
   int t;
   while(1) {
      t= a%b;
      if(t==0)
      return b;
      a = b;
      b= t;
   }
}
int main() {
   //2 random prime numbers
   double p = 13;
   double q = 11;
   double n=p*q;//calculate n
   double track;
   double phi= (p-1)*(q-1);//calculate phi
   //public key
   //e stands for encrypt
   double e=7;
   //for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
   while(e<phi) {
      track = gcd(e,phi);
      if(track==1)
         break;
      else
         e++;
   }
   //private key
   //d stands for decrypt
   //choosing d such that it satisfies d*e = 1 mod phi
   double d1=1/e;
   double d=fmod(d1,phi);
   double message = 9;
   double c = pow(message,e); //encrypt the message
   double m = pow(c,d);
   c=fmod(c,n);
   m=fmod(m,n);
   cout<<"Original Message = "<<message;
   cout<<"\n"<<"p = "<<p;
   cout<<"\n"<<"q = "<<q;
   cout<<"\n"<<"n = pq = "<<n;
   cout<<"\n"<<"phi = "<<phi;
   cout<<"\n"<<"e = "<<e;
   cout<<"\n"<<"d = "<<d;
   cout<<"\n"<<"Encrypted message = "<<c;
   cout<<"\n"<<"Decrypted message = "<<m;
   return 0;
}
p = 13
q = 11
n = pq = 143
phi = 120
e = 7
d = 0.142857
Original Message = 9

Encrypted message = 48
Decrypted message = 9
How can I get the selected value of a drop-down list with jQuery?

With jQuery, it’s easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.
You can try to run the following code to learn how to change the selected value of a drop-down list. Here, we have a default select option first, but the alert shows the second option, which have been changed using the val method():
Live Demo
<html>

   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
           $("#button1").click(function(){
              $("#myselection").val('2');
                 alert( $("#myselection option:selected").text() );
            });
         });
   </script>
   </head>
   
   <body>

      <div>
        <p>The selected value:</p>
        <select id="myselection">
          <option value="1">First</option>
          <option value="2">Second</option>
          <option value="3">Third</option>
        </select>
      </div>
     <button id="button1">Click</button>

   </body>
</html>
Boolean Expressions in SQL - GeeksforGeeks

19 Nov, 2021
Boolean expressions are that expression that returns boolean datatype as result. In SQL there are three values for boolean datatype, those are:
TRUE
FALSE
UNKNOWN
The boolean data type can not be specified during table creation, unlike other data types. Boolean expressions are mainly used with WHERE clauses to filter the data from a table. It can include comparison operators and other operators like ‘AND’ operator, ‘OR’ operator, etc.
For a demonstration of boolean expressions, follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table(
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Step 4: Insert data into a table
Query:
INSERT INTO demo_table VALUES
('ROMY', 22, 'NEW DELHI'),
('PUSHKAR',23, 'NEW DELHI'),
('AKANKSHA',22, 'PUNJAB'),
('SUJATA', 30,'PATNA'),
('PREETI', 26,'BANGLORE'),
('PREM',31,'PUNE'),
('RAM', 34,'PUNE'),
('SHEETAL',32, 'RAJASTHAN'),
('SAMITA',25,'HIMACHAL');
Step 5: View data of the table
Query:
SELECT * FROM demo_table;
Output:
Step 6: Boolean expressions
Example 1: Boolean expression including equal to(=) comparison operator 
Query:
SELECT * FROM demo_table
WHERE AGE = 22;                                
{Boolean expression - > (AGE =22)}
This query will return the values from the table where the AGE column has data equal to 22.
Output:
Example 2:  Boolean expression including greater than(>) comparison operator 
Query :
SELECT * FROM demo_table
WHERE AGE > 22;                                      
{Boolean expression - > (AGE > 22)}
Output:
Example 3: Boolean expression including ‘OR’ operator
OR operator return value when any one of the specified conditions is True.
Query:
SELECT * FROM demo_table
WHERE AGE = 22 OR AGE = 23;         
{Boolean expression - > (AGE = 22 OR AGE = 23)}
Output:
mysql
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Case insensitive search in JavaScript - GeeksforGeeks

27 Sep, 2021
Case-insensitive: It means the text or typed input that is not sensitive to capitalization of letters, like “Geeks” and “GEEKS” must be treated as same in case-insensitive search. In Javascript, we use string.match() function to search a regexp in a string and match() function returns the matches, as an Array object. 
Syntax:  
string.match(regexp)
Parameters: This method accepts single parameter regexp which is required. It is used to pass the value to search for as a regular expression.
Regular expression (regexp): It is a particular syntax /pattern/modifiers; modifier sets the type. For example /GeeksforGeeks/i where “i” sets to case insensitive. 
Note: Here g and i used for global and case-insensitive search respectively.
Example 1: This example describes the search of a regular expression. 
HTML
<!DOCTYPE html><html> <head>    <title>        Case insensitive search        in JavaScript    </title></head> <body style = "text-align:center;">     <h1 style = "color:green;" >            GeeksforGeeks    </h1>          <p>        Click on button    </p>      <button onclick="myGeeks()">        Click Here!    </button>     <p id="GFG"></p>      <script>        function myGeeks() {            var str = "Welcome Geeks GEEKS geeks";            var res = str.match(/geeks/gi);                         document.getElementById("GFG").innerHTML                    = res;        }    </script></body> </html>                   
Output: 
Before clicking on the button: 
After clicking on the button: 
Example 2: This example describes the search of a regular expression. 
HTML
<!DOCTYPE html><html> <head>    <style>        h1 {            padding-top: 35px;            color: green;        }    </style></head> <body style="text-align:center;">     <h1>GeeksforGeeks</h1>      <p>Click the button to perform a global                     case-insensitive search.</p>      <button onclick="myFunction()">Try it</button>     <p id="demo"></p>      <script>        function myFunction() {            var str = "Brazil and Austraila won the WorldCup 5 times";            var res = str.match(/5/gi);            document.getElementById("demo").innerHTML = res;        }    </script> </body> </html>
Output :-
Before clicking on button 
After clicking on button:
 
adnanirshad158
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Iterate over a set in Python

In this article, we will learn about iterating/traversing over a set in Python 3.x. Or Earlier.
It is an unordered collection of objects without any duplicates. This can be done by enclosing all the elements within curly braces. We can also form sets by using type casting via a keyword “set”.
set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value in set_inp:
   print(value, end='')
set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(0,len(set_inp)):
   print(set_inp[value], end='')
set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value,char in enumerate(set_inp):
   print(char, end='')
set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(-len(set_inp),0):
   print(set_inp[value], end='')
The above 4 methods yeilds the following output.
plsrainuto
set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set

for value in range(1,len(set_inp)):
   print(set_inp[value-1:value], end='')
print(set_inp[-1:])
['p']['l']['s']['r']['a']['i']['n']['u']['t']['o']
In this article, we learned about iteration/traversal over a set data type. Also, we learned about various implementation techniques.
Difference between import tkinter as tk and from tkinter import

In order to work with tkinter applications and widgets, we have to import the tkinter library in the environment. There are multiple ways to import the tkinter library in the notebook.
Using from tkinter import *
Using import tkinter as tk
The first method to import the tkinter library is the most common, as it comes with all the inbuilt methods or functions. In the general sense, we don’t have to explicitly override the method for the widgets. In this way, we can create the object of widgets just by using the widget constructor. It comes with all the modules defined in tkinter.
However, to save the major typing efforts, we import the tkinter library with some acronym further that can be used to create an instance of widgets. Thus, the application structures become more aesthetical by using the import tkinter as tk.
The major difference between both the ways is, if we want to define the widget constructor explicitly by defining which module it is associated with, then we can use the acronym method. However, if we want to define every widget by importing all the functions and modules in it, then we can use "from tkinter import *" method.
import tkinter as tk
win= Tk()
win.geometry("750x250")
entry= Text(win, width= 24)
entry.insert(INSERT,"Hello World!")
entry.tag_add("start","1.0","end")
entry.tag_configure("start", background="blue", foreground= "white")
entry.pack()
win.mainloop()
The above code would flash an error. Now, replace the first line "import tkinter as tk" with "from tkinter import *" to import all the functions and modules in the environment. You will now get to see the following output window −
How can we add different font style items to JList in Java?


A JList is a subclass of JComponent class and it can be used to display a list of objects that allows the user to select
one or more items. A JList can generate a ListSelectiionListener interface and need to implement the abstract method valueChanged(). A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. We can add the items to a JList using the addElement() method of the DefaultListModel class, we can also add items with different fonts to JList using HTML tags like <b> for bold style text,  <i> for italic style text, <u> for underlined style text etc. 
import java.awt.*;
import javax.swing.*;
public class JLabelListTest {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new JLabelListTest().makeUI();
         }
      });
   }
   public void makeUI() {
      String[] data = {"<html>Raja</html>", "<html><b>Adithya</b></html>", "<html><i>Jaidev</i> </html>", "<html><u>Chaitanya</u></html>"};
      JList list = new JList(data);
      list.setBackground(Color.lightGray);
      JFrame frame = new JFrame();
      frame.getContentPane().add(new JScrollPane(list), BorderLayout.NORTH);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400, 300);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
Compare the content of two StringBuilders

Equals method is used in C# to compare the content of two StringBuilders.
The following are our two StringBuilders −
// first
StringBuilder str1 = new StringBuilder();
str1.Append("Tim");
str1.Append("Tom");
str1.Append("Henry");

// second
StringBuilder str2 = new StringBuilder();
str2.Append("John");
str2.Append("David");
str2.Append("Beth");
Now use the Equals() method to compare both the methods −
if (str1.Equals(str2)) {
   Console.WriteLine("Contents are equal!");
}
The following is the complete code −
 Live Demo
using System;
using System.Text;

class Demo {
   static void Main() {
      // first
      StringBuilder str1 = new StringBuilder();
      str1.Append("Tim");
      str1.Append("Tom");
      str1.Append("Henry");

      // second
      StringBuilder str2 = new StringBuilder();
      str2.Append("John");
      str2.Append("David");
      str2.Append("Beth");

      // check for equality
      if (str1.Equals(str2)) {
         Console.WriteLine("Contents are equal!");
      } else {
         Console.WriteLine("Contents are unequal!");
      }
   }
}
Contents are unequal!
PHP and MYSQL database connection and table creation only once if it does not already exist?

To create database only once, use the below syntax.
CREATE DATABASE IF NOT EXISTS yourDatabaseName;
To create table only once, use the below syntax −
CREATE TABLE IF NOT EXISTS yourTableName
(
   yourColumnName yourDatatype,
   .
   .
   .
   N
);
Let us implement both the above syntaxes to create database and table only once if does not already exist −
mysql> CREATE DATABASE IF NOT EXISTS login;
Query OK, 1 row affected (0.23 sec)
Above query creates a database successfully.
Following is the query to create a table −
mysql> CREATE TABLE IF NOT EXISTS DemoTable
(
   Id int
);
Query OK, 0 rows affected (0.56 sec)
Above query creates a table successfully.
Load a text file and find number of characters in the file - JavaScript

Suppose we have a data.txt file that lives in the same directory as our NodeJS file. Suppose the content of that file is −
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s.
We are required to write a JavaScript function that loads this external text file into our js file and returns the number of characters in this file.
Let’s write the code for this function −
const fs = require('fs');
const requireFile = async () => {
   const data = fs.readFileSync('./data.txt', 'utf-8');
   const len = data.length;
   return len;
};
requireFile().then(res => console.log(res)).catch(err => {
   console.log('some error occured');
})
The output in the console: −
399
Python program to find uncommon words from two Strings

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given two strings, we need to get the uncommon words from the given strings.
Now let’s observe the solution in the implementation below −
 Live Demo
# uncommon words
def find(A, B):
   # count
   count = {}
   # insert in A
   for word in A.split():
      count[word] = count.get(word, 0) + 1
   # insert in B
   for word in B.split():
      count[word] = count.get(word, 0) + 1
   # return ans
   return [word for word in count if count[word] == 1]
# main
A = "Tutorials point "
B = "Python on Tutorials point"
print("The uncommon words in strings are:",find(A, B))
The uncommon words in strings are: ['Python', 'on']
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python program to find uncommon words from two Strings
0-1 Knapsack Problem in C?

A knapsack is a bag. And the knapsack problem deals with the putting items to the bag based on the value of the items. It aim is to maximise the value inside the bag. In 0-1 Knapsack you can either put the item or discard it, there is no concept of putting some part of item in the knapsack.
Value of items = {20, 25,40}
Weights of items = {25, 20, 30}
Capacity of the bag = 50
25,20{1,2}
20,30 {2,3}
If we use {1,3} the weight will be above the max allowed value.
For {1,2} : weight= 20+25=45 Value = 20+25 = 45
For {2,3}: weight=20+30=50 Value = 25+40=65
The maximum value is 65 so we will put the item 2 and 3 in the knapsack.
#include<stdio.h>
int max(int a, int b) {
   if(a>b){
      return a;
   } else {
      return b;
   }
}
int knapsack(int W, int wt[], int val[], int n) {
   int i, w;
   int knap[n+1][W+1];
   for (i = 0; i <= n; i++) {
      for (w = 0; w <= W; w++) {
         if (i==0 || w==0)
            knap[i][w] = 0;
         else if (wt[i-1] <= w)
            knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);
         else
            knap[i][w] = knap[i-1][w];
      }
   }
   return knap[n][W];
}
int main() {
   int val[] = {20, 25, 40};
   int wt[] = {25, 20, 30};
   int W = 50;
   int n = sizeof(val)/sizeof(val[0]);
   printf("The solution is : %d", knapsack(W, wt, val, n));
   return 0;
}
The solution is : 65
How to convert string to 24-hour datetime format in MySQL?

To convert string to 24 hour datetime format in MySQL, you can use STR_TO_DATE() method. With that use the following format for datetime as the parameter:
'%Y-%m-%d %H:%i:%s'
Following is the syntax
SELECT STR_TO_DATE(yourColumnName, '%Y-%m-%d %H:%i:%s') FROM yourTableName;
Let us first create a table:
mysql> create table DemoTable (ArrivalDate varchar(200));
Query OK, 0 rows affected (0.57 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable values('2019-01-31 15:45:23');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('2012-12-12 20:30:26');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('2016-06-07 21:04:05');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2017-02-03 19:24:32');
Query OK, 1 row affected (0.27 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output
+---------------------+
| ArrivalDate         |
+---------------------+
| 2019-01-31 15:45:23 |
| 2012-12-12 20:30:26 |
| 2016-06-07 21:04:05 |
| 2017-02-03 19:24:32 |
+---------------------+
4 rows in set (0.00 sec)
Following is the query to convert string to 24-hour datetime format in MySQL:
mysql> select str_to_date(ArrivalDate,'%Y-%m-%d %H:%i:%s') AS `24HourFormat` from DemoTable;
This will produce the following output:
+---------------------+
| 24HourFormat        |
+---------------------+
| 2019-01-31 15:45:23 |
| 2012-12-12 20:30:26 |
| 2016-06-07 21:04:05 |
| 2017-02-03 19:24:32 |
+---------------------+
4 rows in set (0.00 sec)
How to find mode for an R data frame column?

To find the model for an R data frame column, we can create a function and use it for the calculation. The function for mode is created as written below −
mode<-function(x){which.max(tabulate(x))}
For a data frame called df having numerical column x, this function will be used as mode(df$x).
Consider the below data frame −
 Live Demo
ID<-1:20
x<-rpois(20,2)
df1<-data.frame(ID,x)
df1
  ID x
1  1  1
2  2  2
3  3  3
4  4  1
5  5  1
6  6  0
7  7  2
8  8  0
9  9  1
10 10 2
11 11 5
12 12 1
13 13 2
14 14 2
15 15 2
16 16 3
17 17 2
18 18 1
19 19 6
20 20 1
Finding the mode of x −
mode(df1$x)
[1] 1
 Live Demo
S.no<-1:20
y<-rpois(20,10)
df2<-data.frame(S.no,y)
df2
  S.no y
1  1   12
2  2   13
3  3   11
4  4   7
5  5   6
6  6   5
7  7   8
8  8   13
9  9   6
10 10  8
11 11  12
12 12  7
13 13  15
14 14  6
15 15  13
16 16  14
17 17  10
18 18  11
19 19  7
20 20  14
Finding the mode of y −
mode(df2$y)
[1] 6
How to use small font in HTML?

To set the small font in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-size. HTML5 do not support the <font> tag, so the CSS style is used to add font size.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try the following code to add font smaller than the default font in an HTML page
<!DOCTYPE html>
<html>
   <head>
      <title>HTML smaller font</title>
   </head>

   <body>
      <h1>Heading</h1>
      <p>This is demo content.</p>
      <p style="color:blue;font-size:11px;">This text will be smaller.</p>
   </body>
</html>
How to filter a specific month in MySQL when date is in varchar?

To filter, you can use STR_TO_DATE() function from MySQL. With that, use MONTH() to get the date from the specific month. Let us first create a table −
mysql> create table DemoTable
   -> (
  -> DueDate varchar(100)
   -> );
Query OK, 0 rows affected (1.18 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('06-19-2019');
Query OK, 1 row affected (0.36 sec)

mysql> insert into DemoTable values('01-31-2018');
Query OK, 1 row affected (0.38 sec)

mysql> insert into DemoTable values('12-01-2016');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 06-19-2019 |
| 01-31-2018 |
| 12-01-2016 |
+------------+
3 rows in set (0.00 sec)
Here is the query to filter month in MySQL when date is in varchar −
mysql> select *from DemoTable
-> where month(str_to_date(DueDate, '%m-%d-%Y')) = 06;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 06-19-2019 |
+------------+
1 row in set (0.00 sec)
Pairs with Difference less than K | Practice | GeeksforGeeks

Given an array of N integers, the task is to find all pairs with a difference less than K.
Example 1:
Input : Arr[] = {1, 10, 4, 2}, K = 3
Output : 2
Explanation:
we have an array a[] = {1, 10, 4, 2} and 
K = 3 We can make only two pairs with a 
difference of less than 3.
(1, 2) and (4, 2). So, the answer is 2.


Example 2:
Input : Arr[] = {2, 3, 4}, K = 5
Output : 3


Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function countPairs() that takes an array (arr), sizeOfArray (n), the integer K, and return the number of pairs whose difference is less than K. The driver code takes care of the printing.
Expected Time Complexity: O(NLog(n)).
Expected Auxiliary Space: O(1).
 
Constraints:
2 ≤ N ≤ 105
0 ≤ K ≤ 104
1 ≤ A[i] ≤ 105
0
Kuldeep Dahiya1 year ago
Kuldeep Dahiya
At last.Got it.
int countPairs(int arr[], int n, int k){    sort(arr,arr+n);    int cnt=0;    for(int i=0;i<n;i++){ int="" j="lower_bound(arr,arr+n,arr[i]+k)-arr;" j--;="" cnt+="j-i;" }="" return="" cnt;="" }="">
0
Kuldeep Dahiya1 year ago
Kuldeep Dahiya
I am getting time limit exceeded.Can anyone have better algorithm.
int countPairs(int arr[], int n, int k){    sort(arr,arr+n);    int cnt=0;    for(int i=0;i<n-1;i++){ int="" j="i+1;" while(j<n&&arr[j]-arr[i]<k)="" {cnt++;="" j++;}="" }="" return="" cnt;="" }="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
MapStruct - Mapping Map

Using Mapstruct we can create mapping of map objects using @MapMapping annotation. Other rules of mapping are same as we've seen so far.
@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
Following example demonstrates the same.
Open project mapping as updated in Mapping List chapter in Eclipse.
Create UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;

import java.util.GregorianCalendar;
import java.util.Map;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;

@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
Create UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtilityMapper;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper = Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("05.04.2015", target.get("1"));		
   }
}
Run the following command to test the mappings.
mvn clean test

Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...

 Print
 Add Notes
 Bookmark this page
How to create space between list bullets and text in HTML?

To create space between list bullets and text in HTML, use CSS padding property. Left padding padding-left is to be added to <ul> tag list item i.e. <li> tag. Through this, padding gets added, which will create space between list bullets and text in HTML.
We have the following unordered list with disc bullets
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML List</title>
   </head>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries:</p>
      <ul style="list-style-type:disc">
         <li>US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ul>
   </body>
</html>
You can try to run the following code to add space between list bullets and text in HTML. We are using the same code above and will add left padding to it for spacing
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Lists</title>
   </head>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries:</p>
      <ul style="list-style-type:disc">
         <li style="padding-left:1em">US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ul>
   </body>
</html>
How to fill color below a curve in Matplotlib?

To fill color below a curve, we can take the following steps −
Initialize variable n. Initialize x and y data points using numpy.
Initialize variable n. Initialize x and y data points using numpy.
Create a figure and a set of subplots, fig and ax.
Create a figure and a set of subplots, fig and ax.
Plot the curve using plot() method.
Plot the curve using plot() method.
Use fill_between() method to fill the area between the two curves, with -1 value.
Use fill_between() method to fill the area between the two curves, with -1 value.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig, ax = plt.subplots()
ax.plot(X, Y, color='blue', alpha=1.00)
ax.fill_between(X, Y, 0, color='blue', alpha=.1)
plt.show()
C++ Program to Generate Random Numbers Using Middle Square Method

The middle-square method is one of the simplest method of generating random numbers. this method will either begin repeatedly generating the same number or cycle to a previous number in the sequence and loop indefinitely. For a generator of ndigit random numbers, the period can be no longer than n. If the middle n digits are all zeroes, the Generator then outputs zeroes forever, while these runs of zero are easy to detect, they occur too frequently for this method to be of practical use.
Input − Enter the digit for random number:4
Output − The random numbers are: 6383, 14846, 8067, 51524, .........
Begin
   middleSquareNumber(number, digit)
   Declare an array and assign next_number=0.
   Square the number and assign it to a variable sqn.
   Divide the digit by 2 and assign it to a variable t.
   Divide sqn by a[t] and store it to sqn.
   For i=0 to digit, do
      next_number =next _number (sqn mod (a[t])) * (a[i]);
      sqn = sqn / 10;
   Done
   Return the next number
End.
#include <iostream>
using namespace std;
int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
int middleSquareNumber(int number, int digit) {
   int sqn = number * number, next_number = 0;
   int t = (digit / 2);
   sqn = sqn / a[t];
   for (int i = 0; i < digit; i++) {
      next_number += (sqn % (a[t])) * (a[i]);
      sqn = sqn / 10;
   }
   return next_number;
}
int main(int argc, char **argv) {
   cout << "Enter the digit random numbers you want: ";
   int n;
   cin >> n;
   int start = 1;
   int end = 1;
   start = a[n - 1];
   end = a[n];
   int number = ((rand()) % (end - start)) + start;
   cout << "The random numbers are:\n" << number << ", ";
   for (int i = 1; i < n; i++) {
      number = middleSquareNumber(number, n);
      cout << number << ", ";
   }
   cout << ".........";
}
Enter the digit random numbers you want: 4
The random numbers are: 6383, 14846, 8067, 51524, .........
Python import modules from Zip archives (zipimport)

Use of 'zipimport' module makes it possible to import Python modules and packages from ZIP-format archives. This module also allows an item of sys.path to be a string naming a ZIP file archive. Any files may be present in the ZIP archive, but only files .py and .pyc are available for import. ZIP import of dynamic modules is disallowed.
Functionality of this module is explained by first building a zip archive of files in 'newdir' directory. Following files are assumed to be present in newdir directory
['guess.py', 'hello.py', 'impzip.py', 'mytest.py', 'prime.py', 'prog.py', 'tmp.py']
import sys, glob
import zipfile
files = glob.glob("*.py")
print (files)
zf = zipfile.PyZipFile('zipimp.zip', mode='w')
for file in files:
   zf.write(file)
zf.close()
We now use 'zipimp.zip' in rest of the article.
The 'zipimport' module defines zipimporter class in which following methods are defined
zipimporter()
This method is the constructor which creates a new zipimporter instance. It requires path to a ZIP filea s argument. ZipImportError is raised if it is not a valid ZIP archive.
>>> import zipimport
>>> importer = zipimport.zipimporter('zipimp.zip')
find_module()
This method earchs for a module specified. It returns the zipimporter instance if the module was found, or None if it wasn’t.
>>> ret=importer.find_module('prime')
>>> ret
<zipimporter object "zipimp.zip">
>>> ret=importer.find_module('sample')
>>> ret
>>> print (ret)
None
get_code()
This method returns the code object for the specified module, raises ZipImportError if the module couldn’t be found.
>>> prog=importer.get_code('prime')
>>> print (prog)
<code object <module> at 0x022A4650, file "zipimp.zip\prime.py", line 1>
load_module()
This method loads the module specified. It returns the imported module, or raises ZipImportError if it wasn’t found.
>>> importer = zipimport.zipimporter('zipimp.zip')
>>> mod=importer.load_module('prog')
30
>>> mod.__name__
'prog'
>>> mod.__file__
'zipimp.zip\\prog.py'
>>> mod.__loader__
<zipimporter object "zipimp.zip">
get_source()
This method returns the source code for the specified module.
>>> prog=importer.get_source('prime')
>>> print (prog)
def isprime(x):
   for i in range(2,x-1):
      if x%i==0:
      return False
   else:
return True
f = int(input())
l = int(input())
primelist = list(filter(isprime, range(f,l)))
print ("prime1", "prime2", "composites")
composites=[(primelist[i-1], primelist[i],(primelist[i]-1)-primelist[i-1]) for i in range(1,len(primelist))]
print (composites)
How to perform square root without using math module in Python?

Python has exponentiation operator (**) which can be used to calculate power of a number. x**y returns x raised to y i.e. y times multiplication of x. Since we need to calculate square root, y should be (1/2)
>>> 10**(1/2)
3.1622776601683795
>>> 25**(1/2)
5.0
How to Count the Number of Rows of a Given SQLite Table using Python?

28 Apr, 2021
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch.
To create the database, we will execute the following code:
Python3
import sqlite3  # Connecting to sqlite# connection objectconnection_obj = sqlite3.connect('geek.db')  # cursor objectcursor_obj = connection_obj.cursor()  # Drop the GEEK table if already exists.cursor_obj.execute("DROP TABLE IF EXISTS GEEK")  # Creating tabletable = """ CREATE TABLE GEEK (            Email VARCHAR(255) NOT NULL,            Name CHAR(25) NOT NULL,            Score INT        ); """  cursor_obj.execute(table)  # inserting data into geek tableconnection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk1@gmail.com","Geek1",25)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk2@gmail.com","Geek2",15)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk3@gmail.com","Geek3",36)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk4@gmail.com","Geek4",27)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk5@gmail.com","Geek5",40)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk6@gmail.com","Geek6",14)""")connection_obj.execute(    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk7@gmail.com","Geek7",10)""")  connection_obj.commit()  # Close the connectionconnection_obj.close()
Output:
So by finding the length of this list which is return by fetchall(), we get the count of the total number of rows.
Python3
import sqlite3  # Connecting to sqlite# connection objectconnection_obj = sqlite3.connect('geek.db')  # cursor objectcursor_obj = connection_obj.cursor()  print("Count of Rows")cursor_obj.execute("SELECT * FROM GEEK")print(len(cursor_obj.fetchall()))  connection_obj.commit()  # Close the connectionconnection_obj.close()
Output:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Python PIL | Image.merge() method

19 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.merge() Merge a set of single band images into a new multiband image.
Syntax: PIL.Image.merge(mode, bands)
Parameters:
mode – The mode to use for the output image. See: Modes.bands – A sequence containing one single-band image for each band in the output image. All bands must have the same size.
Returns: An Image object.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object image = Image.open(r"C:\Users\System-Pc\Desktop\home.png")image.load()r, g, b, a = image.split()  # merge funstion usedim1 = Image.merge( 'RGB', (r, g, b))im1.show()
Output:
Another Example:Here used another image.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object image = Image.open(r"C:\Users\System-Pc\Desktop\python.png")image.load()r, g, b, a = image.split()[1]  # merge funstion usedim1 = Image.merge('RGB', (r, g, b))im1.show()
Output:
Python-pil
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
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method

18 Apr, 2022
The objective of the program given is to perform edge detection of images in real-time. In this article, the popular canny edge detection algorithm is used to detect a wide range of edges in images. OpenCV has in-built function cv2.Canny() which takes our input image as first argument and its aperture size(min value and max value) as last two arguments. This is a simple example of how to detect edges in Python. Steps to download the requirements below:
Download Python 2.7.x version, numpy and OpenCV 2.7.x or 3.1.0 version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.Make sure that numpy is running in your python then try to install opencv.
Download Python 2.7.x version, numpy and OpenCV 2.7.x or 3.1.0 version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.
Make sure that numpy is running in your python then try to install opencv.
Implementation 
Python
# OpenCV program to perform Edge detection in real time# import libraries of python OpenCV# where its functionality residesimport cv2 # np is an alias pointing to numpy libraryimport numpy as np  # capture frames from a cameracap = cv2.VideoCapture(0)  # loop runs if capturing has been initializedwhile(1):     # reads frames from a camera    ret, frame = cap.read()     # converting BGR to HSV    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)         # define range of red color in HSV    lower_red = np.array([30,150,50])    upper_red = np.array([255,255,180])         # create a red HSV colour boundary and    # threshold HSV image    mask = cv2.inRange(hsv, lower_red, upper_red)     # Bitwise-AND mask and original image    res = cv2.bitwise_and(frame,frame, mask= mask)     # Display an original image    cv2.imshow('Original',frame)     # finds edges in the input image and    # marks them in the output map edges    edges = cv2.Canny(frame,100,200)     # Display edges in a frame    cv2.imshow('Edges',edges)     # Wait for Esc key to stop    k = cv2.waitKey(5) & 0xFF    if k == 27:        break  # Close the windowcap.release() # De-allocate any associated memory usagecv2.destroyAllWindows()
Output:  References:
http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/canny_detector/canny_detector.html
http://docs.opencv.org/trunk/da/d22/tutorial_py_canny.html
https://en.wikipedia.org/wiki/Canny_edge_detector
http://www.ijcsmc.com/docs/papers/July2013/V2I7201329.pdf
This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
simmytarika5
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.