code-rag-bench/online-tutorials huggingface dataset:
MySQL query to subtract date records with week day and display the weekday with records

For this, you can use DATE_FORMAT(). Let us first create a table −
mysql> create table DemoTable1820
     (
     AdmissionDate varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1820 values('20/10/2019');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1820 values('19/12/2018');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1820 values('16/04/2017');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1820;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 20/10/2019    |
| 19/12/2018    |
| 16/04/2017    |
+---------------+
3 rows in set (0.00 sec)
Here is the query to subtract date records with week day and display week day name along with records −
mysql> select DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') from DemoTable1820;
This will produce the following output −
+-------------------------------------------------------------------------------------------------------------------------+
| DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') |
+-------------------------------------------------------------------------------------------------------------------------+
| Mon 19 Oct                                                                                                              |
| Mon 14 Dec                                                                                                              |
| Mon 13 Apr                                                                                                              |
+-------------------------------------------------------------------------------------------------------------------------+
3 rows in set, 6 warnings (0.00 sec)
Perl readline Function

This function reads a line from the filehandle referred to by EXPR, returning the result. If you want to use a FILEHANDLE directly, it must be passed as a typeglob.
Simply readline function is equvivalent to <>.
Following is the simple syntax for this function −
readline EXPR

This function returns only one line in a scalar context and in a list context, a list of line up to end-of-file is returned
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

my($buffer) = "";
open(FILE, "/etc/services") or
   die("Error reading file, stopped");

$buffer = <FILE>;
print("$buffer");

$buffer = readline( *FILE );
print("$buffer");

close(FILE);
When above code is executed, it produces the following result −
# /etc/services:
# $Id: services,v 1.33 2003/03/14 16:41:47 notting Exp $


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to convert dictionary into list of JavaScript objects?

Following is the code to convert dictionary into list of JavaScript objects −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample{
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Convert dictionary into list of JavaScript objects</h1>
<div class="sample">
{ A: { 1: "Apple", 2: "Apricot" }, B: { 1: "Ball", 2: "Bull" }, C: { 1:
"Cat", 2: "Cow" }, D: { 1: "Dog", 2: "Drill" }, }
</div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to convert the above dictionary into list of object</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let arr;
   const obj = {
      A: { 1: "Apple", 2: "Apricot" },
      B: { 1: "Ball", 2: "Bull" },
      C: { 1: "Cat", 2: "Cow" },
      D: { 1: "Dog", 2: "Drill" },
   };
   BtnEle.addEventListener("click", () => {
      arr = Object.values(obj);
      console.log(arr);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button and looking at the output in console −
Tryit Editor v3.7

Tryit: Ordered HTML list
How to get the maximum file name length limit using Python?

On some platforms, the maximum filename length varies according to the location on the disk. If you run UNIX with different filesystems mounted in various locations on your directory tree, you might see the following values for the maximum filename length in those locations:
>>> import statvfs, os
>>> os.statvfs('/')[statvfs.F_NAMEMAX]
4032
>>> os.statvfs('/boot')[statvfs.F_NAMEMAX]
255
C++ program to find minimum vertex cover size of a graph using binary search

In this article, we will be discussing a program to find the minimum vertex cover size of a given graph using binary search.
Minimum vertex cover is a set of vertices of the given graph such that every edge in the graph is incident of either of the vertices in that set.
For example, take the graph
2 ---- 4 ---- 6
|     |
|     |
|     |
3 ---- 5
Here, the minimum vertex cover involves vertices 3 and 4. All the edges of the graphs are incident on either 3 or 4 vertice of the graph.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
#define max 15
//array to store graph
bool arr[max][max];
//check if minimum vertex cover exists
bool check_cover(int V, int k, int E) {
   int set = (1 << k) - 1;
   int limit = (1 << V);
   //to mark the edges of size 'k'
   bool vis[max][max];
   while (set < limit) {
      //resetting the vertex cover for each iteration
      memset(vis, 0, sizeof vis);
      int count = 0;
      //checking the values which has a high value
      for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) {
         if (set & j) {
            //marking the edges visited
            for (int k = 1 ; k <= V ; k++) {
               if (arr[v][k] && !vis[v][k]) {
                  vis[v][k] = 1;
                  vis[k][v] = 1;
                  count++;
               }
            }
         }
      }
      //if all the edges are covered
      if (count == E)
         return true;
      int c = set & -set;
      int r = set + c;
      set = (((r^set) >> 2) / c) | r;
   }
   return false;
}
//to find minimum vertex cover
int find_cover(int n, int m) {
   //performing binary search
   int left = 1, right = n;
   while (right > left){
      int mid = (left + right) >> 1;
      if (check_cover(n, mid, m) == false)
         left = mid + 1;
      else
         right = mid;
   }
   return left;
}
//inserting edge in the graph
void add_edge(int u, int v) {
   arr[u][v] = 1;
   arr[v][u] = 1;
}
int main() {
   memset(arr, 0, sizeof arr);
   int V = 6, E = 5;
   add_edge(2, 3);
   add_edge(2, 4);
   add_edge(3, 5);
   add_edge(4, 5);
   add_edge(4, 6);
   cout << "Size of Minimum Vertex Cover : " << find_cover(V, E) << endl;
   return 0;
}
Size of Minimum Vertex Cover : 2
Flashback Queries - GeeksforGeeks

24 May, 2020
Flashback Query allows users to see the view of past data, If in case some data or table is being deleted by the user, then the flashback query provides us an opportunity to view that data again and perform manipulations over it.
In flashback queries we have an concept of flash area, in flash area we store the deleted data which can be viewed if needed in future.
To use the feature of flashback query, our server must be configured according to automatic undo management.If our system supports the traditional approach of rollback then we can not perform flashback query on such systems.
We can enable the flashback query using the package DBMS_FLASHBACK. This package enables us to view the data in past by specifying the System change number or the exact time in the past.
How to use DBMS_FLASHBACK :
EXECUTE Dbms_Flashback.Enable_At_System_Change_Number(647392649);
EXECUTE Dbms_Flashback.Enable_At_Time('19-APR-2020 11:00:00); 
Example of Flashback Query :If we want to view a past data which is being deleted by mistake.The data consists of students table and it is being deleted at 11:05 AM on 19-APR-2020.To access the data we can use flashback query either by giving exact time or by mentioning the system change number.
Limitations Flashback Query :
Flashback query only works on those systems which supports automatic undo management.Systems having traditional approach of rollback does not supports flashback query.We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query.Flashback query does not reverse the DDL(Data Definition Language) commands.Flashback query can perform manipulations in DDL(Data Definition Language) commands.We can not apply flashback queries on functions, Packages, Procedures and triggers.
Flashback query only works on those systems which supports automatic undo management.
Systems having traditional approach of rollback does not supports flashback query.
We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query.
Flashback query does not reverse the DDL(Data Definition Language) commands.
Flashback query can perform manipulations in DDL(Data Definition Language) commands.
We can not apply flashback queries on functions, Packages, Procedures and triggers.
DBMS-SQL
DBMS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
What is Temporary Table in SQL?
Conflict Serializability in DBMS
KDD Process in Data Mining
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
Tryit Editor v3.6 - Show Node.js Command Prompt

var events = require('events');
var eventEmitter = new events.EventEmitter();
​
//Create an event handler:
var myEventHandler = function () {
  console.log('I hear a scream!');
}
​
//Assign the eventhandler to an event:
Why Final Class used in Java?

The final keyword is used with a class to create a final class. The final class cannot be inherited and so the final keyword is commonly used with a class to prevent inheritance.
A program that demonstrates a final class in Java is given as follows:
 Live Demo
final class A {
   private int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}
public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}
Value of a = 9
Now let us understand the above program.
The class A is a final class. This means that it cannot be inherited. It has a private data member a and a method printA() that displays the value of a. A code snippet which demonstrates this is as follows:
final class A {
   private int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}
In the main() method in class Demo, an object obj of final class A is created. Then printA() method is called. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}
How to use HTML5 localStorage and sessionStorage?

HTML5 introduced two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome the following drawbacks.
Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data.
Cookies are limited to about 4 KB of data. Not enough to store required data.
The two mechanisms for storage are session storage and local storage and they would be used to handle different situations.
The Session Storage is designed for scenarios where the user is carrying out a single transaction but could be carrying out multiple transactions in different windows at the same time.
You can try to run the following to set a session variable and access that variable
Live Demo
<!DOCTYPE HTML>
<html>
   <body>
      <script type="text/javascript">
         if( sessionStorage.hits ){
            sessionStorage.hits = Number(sessionStorage.hits) +1;
         } else{
            sessionStorage.hits = 1;
         }
         document.write("Total Hits :" + sessionStorage.hits );
      </script>
      <p>Refresh the page to increase number of hits.</p>
      <p>Close the window and open it again and check the result.</p>
   </body>
</html>
The Local Storage is designed for storage that spans multiple windows and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.
You can try to run the following code to set a local storage variable and access that variable every time this page is accessed, even next time when you open the window.
Live Demo
<!DOCTYPE HTML>
<html>
   <body>
      <script type="text/javascript">
         if( localStorage.hits ){
            localStorage.hits = Number(localStorage.hits) +1;
         } else{
            localStorage.hits = 1;
         }
         document.write("Total Hits :" + localStorage.hits );
      </script>
      <p>Refresh the page to increase number of hits.</p>
      <p>Close the window and open it again and check the result.</p>
   </body>
</html>
Get the location of an element in Java ArrayList

The location of an element in an ArrayList can be obtained using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      System.out.println("The index of element C in ArrayList is: " + aList.indexOf("C"));
      System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F"));
   }
}
The index of element C in ArrayList is: 2
The index of element F in ArrayList is: -1
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.indexOf() returns the index of the first occurrence of “C” and “F” that is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
System.out.println("The index of element C in ArrayList is: " + aList.indexOf("C"));
System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F"));
Program to check points are forming concave polygon or not in Python

Suppose we have outer points of a polygon in clockwise order. We have to check these points are forming a convex polygon or not. A polygon is said to be concave if any one of its interior angle is greater than 180°.
From this diagram it is clear that for each three consecutive points the interior angle is not more than 180° except CDE.
So, if the input is like points = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)], then the output will be True.
To solve this, we will follow these steps −
n := size of points
for i in range 0 to size of points, dop1 := points[i-2] when i > 1, otherwise points[n-2]p2 := points[i-2] when i > 0, otherwise points[n-1]p3 := points[i]if angle between points (p1, p2, p3) > 180, thenreturn True
p1 := points[i-2] when i > 1, otherwise points[n-2]
p2 := points[i-2] when i > 0, otherwise points[n-1]
p3 := points[i]
if angle between points (p1, p2, p3) > 180, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
import math
def get_angle(a, b, c):
   angle = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
   return angle + 360 if angle < 0 else angle

def solve(points):
   n = len(points)
   for i in range(len(points)):
      p1 = points[i-2]
      p2 = points[i-1]
      p3 = points[i]
      if get_angle(p1, p2, p3) > 180:
         return True
   return False

points = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)]
print(solve(points))
[(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)]

True
DateTime.Subtract() Method in C#

The DateTime.Subtract() method in C# is used to subtract the specified DateTime or span.
Following is the syntax −
public TimeSpan Subtract (DateTime value);
public DateTime Subtract (TimeSpan value);
Let us now see an example to implement the DateTime.Subtract() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d1 = new DateTime(2019, 10, 10, 8, 10, 40);
      DateTime d2 = new DateTime(2017, 11, 06, 8, 10, 40);
      Console.WriteLine("Date 1 = "+d1);
      Console.WriteLine("Date 2 = "+d2);
      TimeSpan res = d1.Subtract(d2);
      Console.WriteLine("TimeSpan between two dates = {0} ",res);
   }
}
This will produce the following output −
Date 1 = 10/10/2019 8:10:40 AM
Date 2 = 11/6/2017 8:10:40 AM
TimeSpan between two dates = 703.00:00:00
Let us now see another example to implement the DateTime.Subtract() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 10, 10, 8, 10, 40);
      TimeSpan t = new TimeSpan(1, 10, 10, 12);
      Console.WriteLine("Date = "+d);
      DateTime res = d.Subtract(t);
      Console.WriteLine("DateTime between date d and timespan t = {0} ",res);
   }
}
This will produce the following output −
Date = 10/10/2019 8:10:40 AM
DateTime between date d and timespan t = 10/8/2019 10:00:28 PM
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

28 Jun, 2021
A pennant is a sequence of numbers, each number being 1 or 2. An n-pennant is a sequence of numbers with sum equal to n. For example, (1,1,2) is a 4-pennant. The set of all possible 1-pennants is {(1)}, the set of all possible 2-pennants is {(2), (1,1)} and the set of all 3-pennants is {(2,1), (1,1,1), (1,2)}. Note that the pennant (1,2) is not the same as the pennant (2,1). The number of 10-pennants is ______________.(A) 88.9 to 89.1Answer: (A)Explanation:
1-pennant {(1)} - #1

2-pennant {(1,1),(2)} - #2

3-pennant {(1,1,1),(1,2),(2,1)} - #3

4-pennant {(1,1,1,1),(2,2),(1,1,2),(1,2,1),(2,1,1)} - #5

5-pennant {(1,1,1,1,1),(2,1,1,1),(1,2,1,1),(1,1,2,1),
            (1,1,1,2),(2,2,1),(2,1,2),(1,2,2)} - #8

If one observe carefully they are the terms(part of) a Fibonacci series. (0,1,1,2,3,5,8,13 ....). Hence the # of 10-pennant is the 12th term of the series ie. 89Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
MySQL date column auto fill with current date?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function.
Case 1:
The syntax is as follows:
yourDateColumnName date default ‘yourDateValue’;
Case 2:
The syntax is as follows:
yourDateColumnName datetime default now();
To understand the above, let us create a table. The query to create a table is as follows:
mysql> create table DefaultCurrentdateDemo
   -> (
   -> LoginDate datetime default now()
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into DefaultCurrentdateDemo values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into DefaultCurrentdateDemo values('2017-11-19');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DefaultCurrentdateDemo values('2018-10-21');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DefaultCurrentdateDemo values();
Query OK, 1 row affected (0.23 sec)

mysql> insert into DefaultCurrentdateDemo values('2020-12-24');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from DefaultCurrentdateDemo;
The following is the output:
+---------------------+
| LoginDate |
+---------------------+
| 2019-01-12 20:33:51 |
| 2017-11-19 00:00:00 |
| 2018-10-21 00:00:00 |
| 2019-01-12 20:34:37 |
| 2020-12-24 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)
If you want to extract only date, then use the date() method. The query is as follows:
mysql> select date(LoginDate) as OnlyDate from DefaultCurrentdateDemo;
The following is the output:
+------------+
| OnlyDate |
+------------+
| 2019-01-12 |
| 2017-11-19 |
| 2018-10-21 |
| 2019-01-12 |
| 2020-12-24 |
+------------+
5 rows in set (0.00 sec)
Let us set the default value with some date.
The query to create a default value to date column is as follows:
mysql> create table DefaultDate
   -> (
   -> LoginDate date default '2019-01-12'
   -> );
Query OK, 0 rows affected (0.53 sec)
If you do not pass any value to the column then default value will be provided to the column. The query to insert record is as follows:
mysql> insert into DefaultDate values();
Query OK, 1 row affected (0.13 sec)
Display all records from the table using
select statement. The query is as follows:
mysql> select *from DefaultDate;
The following is the output:
+------------+
| LoginDate  |
+------------+
| 2019-01-12 |
+------------+
1 row in set (0.00 sec)
How can we implement a timer thread in Java?

The Timer class schedules a task to run at a given time once or repeatedly. It can also run in the background as a daemon thread. To associate Timer with a daemon thread, there is a constructor with a boolean value. The Timer schedules a task with fixed delay as well as a fixed rate. In a fixed delay, if any execution is delayed by System GC, the other execution will also be delayed and every execution is delayed corresponding to previous execution. In a fixed rate, if any execution is delayed by System GC then 2-3 execution happens consecutively to cover the fixed rate corresponding to the first execution start time. The Timer class provides a cancel() method to cancel a timer. When this method is called, the Timer is terminated. The Timer class executes only the task that implements the TimerTask.
import java.util.*;
public class TimerThreadTest {
   public static void main(String []args) {
      Task t1 = new Task("Task 1");
      Task t2 = new Task("Task 2");
      Timer t = new Timer();
      t.schedule(t1, 10000); //  executes for every 10 seconds
      t.schedule(t2, 1000, 2000); // executes for every 2 seconds
   }
}
class Task extends TimerTask {
   private String name;
   public Task(String name) {
       this.name = name;
   }
   public void run() {
      System.out.println("[" + new Date() + "] " + name + ": task executed!");
   }
}
[Thu Aug 01 21:32:44 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:46 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:48 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:50 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:52 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:53 IST 2019] Task 1: task executed!
[Thu Aug 01 21:32:54 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:56 IST 2019] Task 2: task executed!
[Thu Aug 01 21:32:58 IST 2019] Task 2: task executed!
[Thu Aug 01 21:33:00 IST 2019] Task 2: task executed!
Add a horizontal rule in HTML

The HTML <hr> tag is the horizontal rule tag, used for creating a horizontal line. The HTML <hr> tag supports following additional attributes −
You can try to run the following code to add a horizontal rule in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML hr Tag</title>
   </head>
   <body>
      <p>This text will be followed by a horizontal line</p>
      <hr />
      <p>Another horizontal line</p>
      <hr />
   </body>
</html>
C# Program to Create a Thread Pool

For a thread pool, create more than two functions and queue methods for execution.
Firstly, create a method like −
public void one(object o) {
   for (int i = 0; i <= 3; i++) {
      Console.WriteLine("One executed");
   }
}
In the same way, create more methods and then use ThreadPool.QueueUserWorkItem to queue the methods for execution −
Demo d = new Demo();
for (int i = 0; i < 3; i++) {
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));
}
You can try to run the following C# code to create a Thread Pool.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Demo {
   public void one(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("One executed");
      }
   }
   public void two(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("Two executed");
      }
   }
   public void three(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("Three executed");
      }
   }
   static void Main() {
      Demo d = new Demo();
      for (int i = 0; i < 3; i++) {
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));
      }
      Console.Read();
   }
}
Two executed
Two executed
Two executed
Two executed
Two executed
Two executed
Two executed
One executed
One executed
One executed
One executed
One executed
Two executed
Two executed
Three executed
Three executed
Two executed
One executed
Three executed
Two executed
Three executed
One executed
One executed
One executed
Java Cryptography - KeyPairGenerator

Java provides the KeyPairGenerator class. This class is used to generate pairs of public and private keys. To generate keys using the KeyPairGenerator class, follow the steps given below.
The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys.
Create KeyPairGenerator object using the getInstance() method as shown below.
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size.
Initialize the KeyPairGenerator object created in the previous step using this method as shown below.
//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below.
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

You can get the private key from the generated KeyPair object using the getPrivate() method as shown below.
//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();

You can get the public key from the generated KeyPair object using the getPublic() method as shown below.
//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();

Following example demonstrates the key generation of the secret key using the KeyPairGenerator class of the javax.crypto package.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

public class KeyPairGenertor {
   public static void main(String args[]) throws Exception{
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initializing the KeyPairGenerator
      keyPairGen.initialize(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();   
      
      //Getting the public key from the key pair
      PublicKey publicKey = pair.getPublic(); 
      System.out.println("Keys generated");
   }
}
The above program generates the following output −
Keys generated


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Apex - SOQL For Loop

This type of for loop is used when we do not want to create the List and directly iterate over the returned set of records of the SOQL query. We will study more about the SOQL query in subsequent chapters. For now, just remember that it returns the list of records and field as given in the query.
for (variable : [soql_query]) { code_block }

or
for (variable_list : [soql_query]) { code_block }

One thing to note here is that the variable_list or variable should always be of the same type as the records returned by the Query. In our example, it is of the same type as APEX_Invoice_c.
Consider the following for loop example using SOQL for loop.
// The same previous example using For SOQL Loop
List<apex_invoice__c> PaidInvoiceNumberList = new
List<apex_invoice__c>();   // initializing the custom object records list to store
                           // the Invoice Records
List<string> InvoiceNumberList = new List<string>();

// List to store the Invoice Number of Paid invoices
for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM
   APEX_Invoice__c WHERE CreatedDate = today]) {
   
   // this loop will iterate and will process the each record returned by the Query
   if (objInvoice.APEX_Status__c == 'Paid') {
      
      // Condition to check the current record in context values
      System.debug('Value of Current Record on which Loop is iterating is '+objInvoice);
      
      //current record on which loop is iterating
      InvoiceNumberList.add(objInvoice.Name);
      // if Status value is paid then it will the invoice number into List of String
   }
}

System.debug('Value of InvoiceNumberList with Invoice Name:'+InvoiceNumberList);

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page
Read all Files in Directory using R

06 Jun, 2021
To list all files in a directory in R programming language we use list.files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories. If no files are present in the directory, it returns “”. If a path does not exist it is skipped and a warning is shown. 
Note: File naming conventions depend on the platform.
Syntax:
list.files(path, pattern, all.files, full.names)
Parameter:
Path:  It is a character vector that contains pathname to directories.
Pattern:  It is an optional regular expression. If this argument is provided then the function only returns the files that have given pattern in their name.
all.files: It is a logical value. 
FALSE: Only the names of visible files are returned.
TRUE:  All file names will be returned irrespective of whether they are visible or hidden.
full.names:  It is a logical value.
TRUE: The filename also contains the full path to the directory.
FALSE: The filename doesn’t contain the path to the directory.
Directory in use:
Directory used
Example 1:
R
list.files(path=".", pattern=NULL, all.files=FALSE,    full.names=FALSE)
Output:
Output
It is also possible to produce only some specific files for that the extension of those files is passed as the value to parameter pattern.
Example 2:
R
list.files(path=".", pattern=".pdf", all.files=TRUE,    full.names=TRUE)
Output:
Output
Picked
R-FileHandling
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
How to rename multiple columns in PySpark dataframe ?

04 Jul, 2021
In this article, we are going to see how to rename multiple columns in PySpark Dataframe.
Before starting let’s create a dataframe using pyspark:
Python3
# importing moduleimport pysparkfrom pyspark.sql.functions import col  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  datadata = [["1", "sravan", "vignan"],        ["2", "ojaswi", "vvit"],        ["3", "rohith", "vvit"],        ["4", "sridevi", "vignan"],        ["1", "sravan", "vignan"],        ["5", "gnanesh", "iit"]]  # specify column namescolumns = ['student ID', 'student NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  print("Actual data in dataframe")  # show dataframedataframe.show()
Output:
Method 1: Using withColumnRenamed.
Here we will use withColumnRenamed() to rename the existing columns name.
Syntax: withColumnRenamed( Existing_col, New_col)
Parameters:
Existing_col: Old column name.
New_col: New column name.
Example 1: Renaming single columns.
Python3
dataframe.withColumnRenamed("college",                             "College Name").show()
Output:
Example 2: Renaming multiple columns.
Python3
df2 = dataframe.withColumnRenamed("student ID",                                  "Id").withColumnRenamed("college",                                                          "College_Name")df2.show()
Output:
Method 2: Using toDF()
This function returns a new DataFrame that with new specified column names.
Syntax: toDF(*col)
Where, col is a new column name
In this example, we will create an order list of new column names and pass it into toDF function.
Python3
Data_list = ["College Id"," Name"," College"]new_df = dataframe.toDF(*Data_list)new_df.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Java - exp() Method

The method returns the base of the natural logarithms, e, to the power of the argument.
double exp(double d)

Here is the detail of parameters −
d − Any primitive data type.
d − Any primitive data type.
This method returns the base of the natural logarithms, e, to the power of the argument.
This method returns the base of the natural logarithms, e, to the power of the argument.
public class Test { 

   public static void main(String args[]) {
      double x = 11.635;
      double y = 2.76;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("exp(%.3f) is %.3f%n", x, Math.exp(x));  
   }
}
This will produce the following result −
The value of e is 2.7183
exp(11.635) is 112983.831
Database - First Normal Form (1NF)

The First normal form (1NF) sets basic rules for an organized database −
Define the data items required, because they become the columns in a table.
Define the data items required, because they become the columns in a table.
Place the related data items in a table.
Place the related data items in a table.
Ensure that there are no repeating groups of data.
Ensure that there are no repeating groups of data.
Ensure that there is a primary key.
Ensure that there is a primary key.
You must define the data items. This means looking at the data to be stored, organizing the data into columns, defining what type of data each column contains and then finally putting the related columns into their own table.
For example, you put all the columns relating to locations of meetings in the Location table, those relating to members in the MemberDetails table and so on.
The next step is ensuring that there are no repeating groups of data. Consider we have the following table −
CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25),
   ORDERS   VARCHAR(155)
);
So, if we populate this table for a single customer having multiple orders, then it would be something as shown below −
But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let us break the above table into two parts and then join them using a key as shown in the following program −
CUSTOMERS table −
CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25),
   PRIMARY KEY (ID)
);
This table would have the following record −
ORDERS table −
CREATE TABLE ORDERS(
   ID   INT              NOT NULL,
   CUSTOMER_ID INT       NOT NULL,
   ORDERS   VARCHAR(155),
   PRIMARY KEY (ID)
);
This table would have the following records −
The final rule of the first normal form, create a primary key for each table which we have already created.
Python | Pandas Series.str.count()

24 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.count() method is used to count occurrence of a string or regex pattern in each string of a series. Additional flags arguments can also be passed to handle to modify some aspects of regex like case sensitivity, multi line matching etc.
Since this is a pandas string method, it’s only applicable on Series of strings and .str has to be prefixed every time before calling this method. Otherwise, it will give an error.
Syntax: Series.str.count(pat, flags=0)
Parameters:pat: String or regex to be searched in the strings present in seriesflags: Regex flags that can be passed (A, S, L, M, I, X), default is 0 which means None. For this regex module (re) has to be imported too.
Return type: Series with count of occurrence of passed characters in each string.
To download the CSV used in code, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Counting word occurrenceIn this example, a Pandas series is made from a list and occurrence of gfg is counted using str.count() method.
# importing pandas packageimport pandas as pd  # making listlist =["GeeksforGeeks", "Geeksforgeeks", "geeksforgeeks",       "geeksforgeeks is a great platform", "for tech geeks"]  # making seriesseries = pd.Series(list)  # counting occurrence of geekscount = series.str.count("geeks")  # displaycount
Output:As shown in the output image, the occurrence of geeks in each string was displayed and Geeks wasn’t counted due to first upper case letter. Example #2: Using Flags
In this example, occurrence of “a” is counted in the Name column. The flag parameter is also used and re.I is passed to it, which means IGNORECASE. Hence, a and A both will be considered during count.
# importing pandas module import pandas as pd  # importing module for regeximport re  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # String to be searched in start of string search ="a"  # count of occurrence of a and creating new columndata["count"]= data["Name"].str.count(search, re.I)  # displaydata
Output:As shown in the output image, it can be clearly compared by looking at the first index itself, the count for a in Avery Bradely is 2, which means both upper case and lower case was considered.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to capture out of memory exception in C#?

The System.OutOfMemoryException occurs when the CLR fail in allocating enough memory that is needed.
System.OutOfMemoryException is inherited from the System.SystemException class.
Set the strings −
string StudentName = "Tom";
string StudentSubject = "Maths";
Now you need to initialize with allocated Capacity that is the length of initial value −
StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
Now, if you will try to insert additional value, the exception occurs.
sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
The following exception occurs −
System.OutOfMemoryException: Out of memory
To capture the error, try the following code −
 Live Demo
using System;
using System.Text;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         try {
            string StudentName = "Tom";
            string StudentSubject = "Maths";
            StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
            // Append initial value
            sBuilder.Append(StudentName);
            sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
         } catch (System.OutOfMemoryException e) {
               Console.WriteLine("Error:");
               Console.WriteLine(e);
         }
      }
   }
}
The above handles OutOfMemoryException and generates the following error −
Error:
System.OutOfMemoryException: Out of memory
Create a transparent box with CSS

To create a transparent box with CSS, you can try to run the following code
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            background-color: #808000;
            padding: 20px;
         }
         div.myopacity {
            opacity: 0.4;
            filter: alpha(opacity=80);
         }
      </style>
   </head>
   <body>
      <h1>Heading</h1>
      <p>Check trensparency in the below box:</p>
      <div class = "myopacity">
         <p>opacity 0.4</p>
      </div>
      <div>
         <p>opacity 1</p>
      </div>
   </body>
</html>
F# - Nested Loops

F# programming language allows to use one loop inside another loop.
The syntax for a nested for loop statement could be as follows −
for var1 = start-expr1 to end-expr1 do
   for var2 = start-expr2 to end-expr2 do
      ... // loop body

The syntax for a nested while loop statement could be as follows −
while test-expression1 do
   while test-expression2 do
      body-expression

let main() =
   for i = 1 to 5 do
      printf "\n"
      for j = 1 to 3 do
         printf "*"
main()
When you compile and execute the program, it yields the following output −
***
***
***
***
***

 Print
 Add Notes
 Bookmark this page
How to check for duplicates in MySQL table over multiple columns?

To check for duplicates in MySQL, you can use group by having clause. The syntax is as follows.
select yourColumnName1,yourColumnName2,......N,count(*) as anyVariableName from
yourTableName
group by yourColumnName1,yourColumnName2
having count(*) > 1;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table DuplicateDemo
-> (
-> StudentId int not null,
-> StudentFirstName varchar(100),
-> StudentLastName varchar(100),
-> Primary Key(StudentId)
-> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into DuplicateDemo values(1,'John','Smith');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DuplicateDemo values(2,'Mike','Jones');
Query OK, 1 row affected (0.28 sec)

mysql> insert into DuplicateDemo values(3,'David','Smith');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DuplicateDemo values(4,'Carol','Taylor');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DuplicateDemo values(5,'David','Smith');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DuplicateDemo values(6,'John','Smith');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DuplicateDemo values(7,'John','Taylor');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows -
mysql> select *from DuplicateDemo;
The following is the output.
+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1         | John             | Smith           |
| 2         | Mike             | Jones           |
| 3         | David            | Smith           |
| 4         | Carol            | Taylor          |
| 5         | David            | Smith           |
| 6         | John             | Smith           |
| 7         | John             | Taylor          |
+-----------+------------------+-----------------+
7 rows in set (0.00 sec)
Here is the query to check the duplicates from the table.
mysql> select StudentFirstName,StudentLastName,count(*) as Total from DuplicateDemo
-> group by StudentFirstName,StudentLastName
-> having count(*) > 1;
The following is the output.
+------------------+-----------------+-------+
| StudentFirstName | StudentLastName | Total |
+------------------+-----------------+-------+
| John             | Smith           | 2     |
| David            | Smith           | 2     |
+------------------+-----------------+-------+
2 rows in set (0.00 sec)