code-rag-bench/online-tutorials huggingface dataset:
Using EXPLAIN keyword in MySQL

MySQL EXPLAIN gives a query execution plan. EXPLAIN can be used in the beginning with SELECT, INSERT, DELETE, REPLACE, and UPDATE.
To avoid the complete table scan in database, you need to use index. Let us first create a table −
mysql> create table DemoTable1488
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (2.18 sec)
Here is the query to create index −
mysql> create index student_id_index on DemoTable1488(StudentId);
Query OK, 0 rows affected (0.90 sec)
Records: 0  Duplicates: 0  Warnings: 0
insert into DemoTable1488 valueInsert some records in the table using insert command −
mysql> insert into DemoTable1488 values(101,'Sam',21);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable1488 values(102,'Bob',23);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1488 values(103,'David',20);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1488;
This will produce the following output −
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|       101 | Sam         |         21 |
|       102 | Bob         |         23 |
|       103 | David       |         20 |
+-----------+-------------+------------+
3 rows in set (0.00 sec)
Now, use EXPLAIN −
mysql> explain select * from DemoTable1488 where StudentId=1;
This will produce the following output −
+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
| id | select_type | table         | partitions | type | possible_keys    | key              | key_len  | ref | rows  | filtered | Extra |
+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | DemoTable1488 | NULL       | ref  | student_id_index | student_id_index | 5       | const |    1 | 100.00   | NULL |
+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)
How to deal with error “var(x) : Calling var(x) on a factor x is defunct.” in R?

The error “Calling var(x) on a factor x is defunct” occurs when we try to apply a numerical function on factor data.
For example, if we have a factor column in a data frame then applying numerical functions on that column would result in the above error. To deal with this problem, we can use as.numeric function along with the numerical function as shown in the below examples.
Following snippet creates a sample data frame −
x<-factor(rpois(20,5))
df<-data.frame(x)
df
The following dataframe is created −
    x
1   7
2   3
3   7
4   4
5   7
6   6
7   4
8   6
9   8
10  2
11  6
12  6
13  9
14  5
15  3
16  4
17 10
18  2
19  4
20  2
Now, in order to apply t test on data in x, add the following code to the above snippet −
t.test(df$x,mu=2)
If you execute all the above given snippets as a single program, it generates the following Output −
Error in var(x) : Calling var(x) on a factor x is defunct.
Hence, use something like the following ' to test for a constant vector.
'all(duplicated(x)[-1L])
If you execute all the above given snippets as a single program, it generates the following Output −
In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA
Now, use as.numeric function on x while applying t.test function and add the following code to the above snippet −
t.test(as.numeric(df$x),mu=2)
If you execute all the above given snippets as a single program, it generates the following Outpu for the one sample t-test −
data: as.numeric(df$x)
t = 4.3061, df = 19, p-value = 0.0003811
alternative hypothesis: true mean is not equal to 2
95 percent confidence interval:
   3.156355 5.343645
sample estimates:
mean of x
   4.25
Following snippet creates a sample data frame −
y<-factor(rpois(20,2))
dat<-data.frame(y)
dat
The following dataframe is created −
    y
1   1
2   2
3   4
4   4
5   2
6   0
7   0
8   1
9   3
10  0
11  2
12  0
13  0
14  2
15  2
16  2
17  2
18  0
19  4
20  2
Now, in order to apply t test on data, add the following code to the above snippet −
t.test(dat$y,mu=0)
If you execute all the above given snippets as a single program, it generates the following output −
Error in var(x) : Calling var(x) on a factor x is defunct.
Use something like the following to test for a constant vector −
'all(duplicated(x)[-1L])'
If you execute all the above given snippets as a single program, it generates the following Output −
In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA
Now, use as.numeric function on y while applying t.test function, add the following code to the above snippet −
t.test(as.numeric(dat$y),mu=0)
If you execute all the above given snippets as a single program, it generates the following Output for the one sample t-test −
data: as.numeric(dat$y)
t = 8.5446, df = 19, p-value = 6.216e-08
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
   2.000878 3.299122
sample estimates:
mean of x
   2.65
Program to find number of combinations of coins to reach target in Python

Suppose we have a list of coins and another value amount, we have to find the number of combinations there are that sum to amount. If the answer is very large, then mod the result by 10^9 + 7.
So, if the input is like coins = [2, 5] amount = 10, then the output will be 2, as we can make these combinations − [2, 2, 2, 2, 2], [5, 5]
To solve this, we will follow these steps −
m := 10^9 + 7
dp := a list of size same as amount + 1, and fill it with 0
dp[0] := 1
for each d in coins, dofor i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d]
for i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d]
if i - d >= 0, thendp[i] := dp[i] + dp[i - d]
dp[i] := dp[i] + dp[i - d]
return (last element of dp) mod m
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, coins, amount):
      dp = [0] * (amount + 1)
      dp[0] = 1
      for d in coins:
         for i in range(1, len(dp)):
            if i - d >= 0:
               dp[i] += dp[i - d]
      return dp[-1] % (10 ** 9 + 7)
ob = Solution()
coins = [2, 5]
amount = 10
print(ob.solve(coins, amount))
[2, 5], 10
2
Python - Sum negative and positive values using GroupBy in Pandas

Let us see how to find the sum of negative and positive values. At first, create a dataframe with positive and negative values −
dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})
Next, use groupby to group on the basis of Place column −
groupRes = dataFrame.groupby(dataFrame['Place'])
Use lambda function to return the positive and negative values. We have also added the positive and negative values individually −
# lambda function
def plus(val):
   return val[val > 0].sum()
def minus(val):
   return val[val < 0].sum()
Following is the complete code −
import pandas as pd

# create a DataFrame with temperature in celsius
dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})
print(dataFrame)

# using groupby to group on the basis of place
groupRes = dataFrame.groupby(dataFrame['Place'])

# lambda function
def plus(val):
   return val[val > 0].sum()
def minus(val):
   return val[val < 0].sum()

print(groupRes['Temperature'].agg([('negTemp', minus), ('posTemp', plus)]))
This will produce the following code −
      Place      Temperature
0   Chicago               -2
1    Denver               30
2   Atlanta               -5
3   Chicago               10
4    Dallas               30
5    Denver               -5
6    Dallas               20
7   Atlanta              -10
           negTemp  posTemp
Place
Atlanta        -15       0
Chicago         -2      10
Dallas           0      50
Denver          -5      30
Python | sympy.sin() method - GeeksforGeeks

19 Jul, 2019
In simpy, sin() method is sine function. Using the sin(x) method in simpy module, we can compute the sine of x.
Syntax : sympy.sin(x)
Return : Returns the sine of x 
Code #1:Below is the example using sin() method to find sine function.
# importing sympy libraryfrom sympy import *  # calling sin() method on expressiongeek1 = sin(-1)geek2 = sin(pi / 3)  print(geek1)print(geek2)
Output:
-sin(1)
sqrt(3)/2

 Code #2:
# importing sympy libraryfrom sympy import *    # calling sin() method on expressiongeek = sin(2 + 5j)print(geek)
Output:
67.4789152384559 - 30.8794313435882*I

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Date and Time - EOMONTH Function

The EOMONTH function returns the serial number for the last day of the month that is the indicated number of months before or after start_date.
EOMONTH (start_date, months)

A date that represents the starting date.
Dates should be entered by using the DATE function, or as results of other formulas or functions.
Problems can occur if dates are entered as text.
The number of months before or after start_date.
A positive value for months yields a future date.
A negative value yields a past date.
Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900
Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900
If months is not an integer, it is truncated.
If months is not an integer, it is truncated.
The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells.
The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells.
If start_date is not a valid date, EOMONTH returns the #NUM! error value.
If start_date is not a valid date, EOMONTH returns the #NUM! error value.
If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value.
If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value.
If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value.
If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value.
Excel 2007, Excel 2010, Excel 2013, Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Priority queue of pairs in C++ (Ordered by first)

Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time. The priority queue doesn’t stores elements in linear fashion with respect to their locations like in Stacks, Queues, List, etc. The priority queue ADT(abstract data type) stores elements based upon their priorities.
Priority Queue supports the following functions −
Size() − it is used to calculate the size of the priority queue as it returns the number of elements in it.
Empty() − it return true if the Priority Queue is empty and false otherwise
Insert(element) − used to insert the new element into a Priority Queue
Min() − it returns the element with the smallest associated key value and display error message if Priority Queue is empty.
removeMin() − it removes the element referenced by the min() function.
The task is to implement the concept of priority queue of pairs in C++ ordered by the first.
We can solve the problem in a similar fashion of heaps, have two ways to solve the problem
Max priority or Max heap
Min priority or Min heap
Heap is a tree structure in which the nodes are arranged in a specific order. There are two types of heaps Min heap and Max heap. In Min heap the root node or the parent node is smaller than its child node, whereas in Max heap the root node or the parent node is larger than its child node.
Input: priorityq.push(make_pair(18, 200))
Input: priorityq.push(make_pair(18, 200))
priorityq.push(make_pair(29, 100))
priorityq.push(make_pair(11, 400))
Output: 29 100

Input: priorityq.push(make_pair(10, 200))
priorityq.push(make_pair(20, 100))
priorityq.push(make_pair(19, 400))
Output: 20 100
Through Max priority (Max heap)
Start
Step 1-> In main function()
   Define priority_queue<pair<int, int> > priorityq
   Call priorityq.push(make_pair(18, 200))
   Call priorityq.push(make_pair(29, 100))
   Call priorityq.push(make_pair(11, 400))
   Set pair<int, int> top = priorityq.top()
   Print top.first and top.second
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
// main program
int main() {
   priority_queue<pair<int, int> > priorityq;
   priorityq.push(make_pair(18, 200));
   priorityq.push(make_pair(29, 100));
   priorityq.push(make_pair(11, 400));
   pair<int, int> top = priorityq.top();
   cout << top.first << " " << top.second;
   return 0;
}
29 100
Start
Step 1-> In main function()
   Define priority_queue<pair<int, int> > priorityq
   Call pq.push(make_pair(10, 200))
   Call pq.push(make_pair(20, 100))
   Call pq.push(make_pair(15, 400))
   Set pair<int, int> top = pq.top()
   Print top.first and top.second
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
// main program
int main() {
   priority_queue<pi, vector<pi>, greater<pi> > pq;
   pq.push(make_pair(10, 200));
   pq.push(make_pair(20, 100));
   pq.push(make_pair(15, 400));
   pair<int, int> top = pq.top();
   cout << top.first << " " << top.second;
   return 0;
}
10 200
How to draw a polygon in HTML5 SVG?

SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. The points attribute is the x and y coordinates for each corner of the polygon.
You can try to run the following code to learn how to draw a polygon in HTML5 SVG.
<!DOCTYPE html>
<html>
   <head>
      <style>
         #svgelem {
            position: relative;
            left: 10%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
      <title>HTML5 SVG Polygon</title>
   </head>

   <body>
      <h2>HTML5 SVG Polygon</h2>
      <svg id="svgelem" width="300" height="300" xmlns="http://www.w3.org/2000/svg">
         <polygon points="100, 20 200,180 100,200" style="fill:green;" />
      </svg>
   </body>
</html>
How to use inline CSS (Style Sheet) in HTML?

To add inline CSS in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with CSS properties such as font-family, font-style, text-decoration, direction, etc.
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 use inline CSS in HTML. Here, we are adding font size to heading using inline CSS
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Inline CSS</title>
   </head>

   <body>
      <h1 style=”font-size: 20px;”>
         Tutorials
      </h1>
      <p>We have tutorials on Programming, CMS, Scripting Languages, etc.</p>
   </body>
</html>
hidden.bs.modal Bootstrap Event

The hidden.bs.modal event in Bootstrap fires when the modal is completely hidden.
Hide the modal on button click −
$("#button1").click(function(){
  $("#newModal").modal("hide");
});
After you will hide it, use the hidden.bs.modal Bootstrap event to generate an alert before the modal completely hides −
$("#newModal").on('hidden.bs.modal', function () {
  alert('The modal is completely hidden now!');
});
You can try to run the following code to implement the hidden.bs.modal event −
Live Demo
<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
     #button1 {
      width: 140px;
      padding: 20px;
      bottom: 150px;
      z-index: 9999;
      font-size:15px;
      position: absolute;
      margin: 0 auto;
     }
    </style>
  </head>

<body>
  <div class="container">
    <h2>Sample</h2>
    <p>This is demo text.</p>
    <p>This is demo text.</p>  
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>
    <p>This is demo text.</p>

    <button type="button" class="btn btn-default btn-lg" id="button1">Click to hide</button>
    <div class="modal fade" id="newModal" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Information</h4>
           </div>
        <div class="modal-body">
          <p>Crucial Information about the Examination.</p>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
  $("#newModal").modal("show");

  $("#button1").click(function(){
    $("#newModal").modal("hide");
  });
  $("#newModal").on('hide.bs.modal', function () {
    alert('The modal is about to be hidden!');
  });
  $("#newModal").on('hidden.bs.modal', function () {
    alert('The modal is completely hidden now!');
  });
});
</script>

</body>
</html>
Ruby | Math log() function - GeeksforGeeks

07 Jan, 2020
The log() function in Ruby returns the logarithm value of X. The second parameter is the base given by the user to which the logarithm value is returned. In case its not given, then the default base is e.
Syntax: Math.log(X, base)
Parameter: The function takes one mandatory parameter X whose logarithm value is to be returned and a non-mandatory parameter base, to whose base is the logarithm.
Return Value: The function returns the logarithm value of X.
Example 1:
# Ruby program for log() function   # Assigning valuesval1 = 213val2 = 256base2 = 2  val3 = 27 base3 = 3  val4 = 100 base4 = 10  # Prints the value returned by log() puts Math.log(val1)  puts Math.log(val2, base2)  puts Math.log(val3, base3)  puts Math.log(val4, base4)
Output:
5.3612921657094255
8.0
3.0
2.0
Example 2:
# Ruby program for log() function   # Assigning valuesval1 = 10  val2 = 256base2 = 4  val3 = 27 base3 = 10  val4 = 105 base4 = 7  # Prints the value returned by log() puts Math.log(val1)  puts Math.log(val2, base2)  puts Math.log(val3, base3)  puts Math.log(val4, base4)
Output:
2.302585092994046
4.0
1.4313637641589871
2.3916625094004957

Reference: https://devdocs.io/ruby~2.5/math#method-c-log
Ruby Math-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array slice() function
Ruby | Array count() operation
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Case Statement
Include v/s Extend in Ruby
MySQL query to select multiple rows effectively?

You need to use index to select multiple rows effectively. Let us first create a table −
mysql> create table DemoTable1501
   -> (
   -> Id int NOT NULL PRIMARY KEY,
   -> URL text
   -> );
Query OK, 0 rows affected (0.62 sec)
Here is the query to create index −
mysql> create index id_index on DemoTable1501(Id);
Query OK, 0 rows affected (0.23 sec)
Records: 0  Duplicates: 0  Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable1501 values(101,'www.facebook.com');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1501 values(110,'www.google.com');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1501 values(220,'www.gmail.com');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable1501 values(350,'www.youtube.com');
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1501;
This will produce the following output −
+-----+------------------+
| Id  | URL              |
+-----+------------------+
| 101 | www.facebook.com |
| 110 | www.google.com   |
| 220 | www.gmail.com    |
| 350 | www.youtube.com  |
+-----+------------------+
4 rows in set (0.00 sec)
Following is the query to select multiple rows efficiently −
mysql> select * from DemoTable1501
   -> where Id in(101,220,350);
This will produce the following output −
+-----+------------------+
| Id  | URL             |
+-----+------------------+
| 101 | www.facebook.com |
| 220 | www.gmail.com    |
| 350 | www.youtube.com  |
+-----+------------------+
3 rows in set (0.00 sec)
To prove this, use the SHOW command in which the Handler_read_key uses 3 out of 4 Ids −
mysql> SHOW STATUS LIKE 'Handler_%';
This will produce the following output −
+----------------------------+-------+
| Variable_name              | Value |
+----------------------------+-------+
| Handler_commit             |     1 |
| Handler_delete             |     0 |
| Handler_discover           |     0 |
| Handler_external_lock      |     2 |
| Handler_mrr_init           |     0 |
| Handler_prepare            |     0 |
| Handler_read_first         |     0 |
| Handler_read_key           |     3 |
| Handler_read_last          |     0 |
| Handler_read_next          |     0 |
| Handler_read_prev          |     0 |
| Handler_read_rnd           |     0 |
| Handler_read_rnd_next      |     0 |
| Handler_rollback           |     0 |
| Handler_savepoint          |     0 |
| Handler_savepoint_rollback |     0 |
| Handler_update             |     0 |
| Handler_write              |     0 |
+----------------------------+-------+
18 rows in set (0.00 sec)
How to use null value as key in Java HashMap

Yes, you can set null as key in Java HashMap. For this, let’s first create a HashMap with key and value pair −
Map<String,String>map = new HashMap<>();
map.put("Football", "A");
map.put("Squash", "B");
map.put("Cricket", "C");
map.put("Hockey", "D");
map.put("Rugby", "E");
Now, let’s add null value as key −
map.put(null, "H");
You can try to get the value for key as “null” −
map.get(null);
 Live Demo
import java.util.HashMap;
import java.util.Map;
public class Demo {
   public static final void main(String[] args) {
      Map<String,String>map = new HashMap<>();
      map.put("Football", "A");
      map.put("Squash", "B");
      map.put("Cricket", "C");
      map.put("Hockey", "D");
      map.put("Rugby", "E");
      map.put("Golf", "F");
      map.put("Archery", "G");
      System.out.println("Size of HashMap = " + map.size());
      map.put(null, "H");
      System.out.println("Updated Size of HashMap = " + map.size());
      System.out.println("For null = " + map.get(null));
   }
}
Size of HashMap = 7
Updated Size of HashMap = 8
For null = H
Jackson Annotations - @JsonSubTypes

@JsonSubTypes is used to indicate subtypes of types annotated.
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException{
      Shape shape = new JacksonTester.Circle("CustomCircle", 1);
      String result = new ObjectMapper()
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(shape);
      System.out.println(result);   
      String json = "{\"name\":\"CustomCircle\",\"radius\":1.0, \"type\":\"circle\"}";
      Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);
      System.out.println(circle.name);
   }
   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({
         
      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      public String name;    
      Shape(String name) {
         this.name = name;
      }
   }
   @JsonTypeName("square")
   static class Square extends Shape {
      public double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }
   @JsonTypeName("circle")
   static class Circle extends Shape {
      public double radius;  
      Circle(){
         this(null,0.0);
      }
      Circle(String name, double radius){
         super(name);
         this.radius = radius;
      }
   }   
}
{
   "type" : "circle",
   "name" : "CustomCircle",
   "radius" : 1.0
}
CustomCircle

 Print
 Add Notes
 Bookmark this page
How to Set the Default Text of Tkinter Entry Widget? - GeeksforGeeks

11 Dec, 2020
The Tkinter Entry widget does not have any text attribute that can be used to set the default text.  Therefore, default text must be added to any text field in Tkinter using the following methods:
Insert method
stringvar method
Method 1: Using the insert method
The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . Next a Entry widget ‘textBox ‘ is created on the root widget. The insert() method is called on the Entry widget. The insert() method takes two arguments. The first argument is the position of the string and the second argument is the text itself. Since the text must be there by default in the Entry widget, the position of the text is set to 0. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application.
Below is the implementation:
Python3
import tkinter as tk    root = tk.Tk()root.geometry("200x100")  textBox = tk.Entry(root)textBox.insert(0, "This is the default text")textBox.pack()root.mainloop()
Output
Method 2: Using the stringvar method
The second method to add a default text to the Entry widget in Tkinter is the StringVar() method. The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . A text variable is a string variable and is its value is set to the default text. Next, an Entry widget ‘textBox ‘ is created on the root widget. The textvariable attribute of the Entry widget is assigned the value of the text variable. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application.
Below is the implementation:
Python3
import tkinter as tk    root = tk.Tk()root.geometry("200x100")  text = tk.StringVar()text.set("This is the default text")textBox = tk.Entry(root,textvariable = text)  textBox.pack()  root.mainloop()
Output
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
flag.Bool() Function in Golang With Examples - GeeksforGeeks

19 May, 2020
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string.
Syntax:
func Bool(name string, value bool, usage string) *bool
Parameters: This function accepts three parameters as mentioned above and described below:
name: It is a string that specifies the name to be used for the flag.
value: It is a boolean value that specifies the default value to be used by the flag.
usage: It is a string that specifies the usage or help message to be shown for the flag.
Return Value: It returns an address of the boolean variable that stores the value of the flag defined.
Below programs illustrate the flag.Bool() function:
Example 1:
// Golang program to illustrate// the flag.Bool() Functionpackage main  import (    "flag"    "fmt")  func main() {    // Define a bool flag    boolArgPtr := flag.Bool("arg1", false, "This is a bool argument")      // Parse command line     // into the defined flags    flag.Parse()      fmt.Println("Bool Arg:", *boolArgPtr)}
Output:
Specifying the flag value$ go run ex1.go -arg1=true
Bool Arg: true
$ go run ex1.go -arg1=true
Bool Arg: true
Not specifying the flag value (Default Value)$ go run ex1.go
Bool Arg: false

$ go run ex1.go
Bool Arg: false

Example 2:
// Golang program to illustrate// the flag.Bool() Functionpackage main  import (    "flag"    "fmt")  func main() {      // Define multiple bool arguments    plainArgPtr := flag.Bool("plaintext", false, "Enable plaintext")    jsonArgPtr := flag.Bool("json", false, "Enable JSON")    csvArgPtr := flag.Bool("csv", false, "Enable CSV")      // Parse command line into the defined flags    flag.Parse()      fmt.Println("Enable plaintext:", *plainArgPtr)    fmt.Println("Enable JSON:", *jsonArgPtr)    fmt.Println("Enable CSV:", *csvArgPtr)}
Output
Specifying some flag values$ go run ex2.go -plaintext=true -csv=true
Enable plaintext: true
Enable JSON: false
Enable CSV: true

$ go run ex2.go -plaintext=true -csv=true
Enable plaintext: true
Enable JSON: false
Enable CSV: true

Not specifying any flag value (Default Values)$ go run ex2.go
Enable plaintext: false
Enable JSON: false
Enable CSV: false

$ go run ex2.go
Enable plaintext: false
Enable JSON: false
Enable CSV: false

Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Loops in Go Language
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Strings in Golang
Class and Object in Golang
How to iterate over an Array using for loop in Golang?
Structures in Golang
How to compare DateTime Column with only Date not time in MySQL?

To compare DateTime column with only Date, you need to use the Date() method. Following is the syntax. Below, you need to date in the 'yourDateValue':
select *from yourTableName where Date(yourColumnName)='yourDateValue';
Let us first create a table:
mysql> create table DemoTable
(
   ArrivalTime datetime
);
Query OK, 0 rows affected (0.74 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable values('2019-01-31 02:34:56');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('2019-04-09 18:20:58');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-05-11 19:45:23');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-02-03 21:10:02');
Query OK, 1 row affected (0.16 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output with date and time record:
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-01-31 02:34:56 |
| 2019-04-09 18:20:58 |
2019-05-11 19:45:23   |
| 2019-02-03 21:10:02 |
+---------------------+
4 rows in set (0.00 sec)
Following is the query to compare only date not time. Here, we are comparing the date:
mysql> select *from DemoTable where Date(ArrivalTime)='2019-04-09';
This will produce the following output:
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-04-09 18:20:58 |
+---------------------+
1 row in set (0.00 sec)
Replicate elements of vector in R programming - rep() Method - GeeksforGeeks

21 Dec, 2021
In the R programming language, A very useful function for creating a vector by repeating a given numbervector with the specified number of times is the rep().
The general structure of rep() : rep(v1,n1).
Here, v1 is repeated n1 times.
The forms of rep() functions :
rep(v1, times=)
rep(v1, each=)
rep(v1, length=)
Example 1:
R
# Replicate '0' 5 timerep(0, 5)
Output:
[1] 0 0 0 0 0
Example 2:
rep(v1,  times=)
R
# 1,2,3 repeated 3 times in sequenciallyrep(1:3,times=3)
Output:
[1] 1 2 3 1 2 3 1 2 3
Example 3:
rep(v1,  each=)
R
# 1,2,3 repeated 3 timesrep(1:3,each=3)
Output:
[1] 1 2 3 1 2 3 1 2 3
Example 4:
rep(v1,  length=)
R
# generate a vector 1,2,3x<-1:3 # vector x is replicated such that the# length is five.rep(x, length=5)
Output:
1 2 3 1 2
Example 5:
R
# 1 is replicated 2 times, and so onrep(x,c(2,1,3))
Output:
1 1 2 3 3 3
immortalishika2001
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
GATE | GATE CS 2019 | Question 35 - GeeksforGeeks

05 Aug, 2021
Consider the following C program:
void convert(int n) {  if (n < 0)    printf(“ % d”, n);  else {    convert(n / 2);    printf(“ % d”, n % 2);  }}
Which one of the following will happen when the function convert is called with any positive integer n as argument?(A) It will print the binary representation of n in the reverse order and terminate.(B) It will print the binary representation of n but will not terminate(C) It will not print anything and will not terminate.(D) It will print the binary representation of n and terminate.Answer: (C)Explanation: Since n is the integer, so it 1/2 = 0.5 = 0 will return because of integer.
0/2 = 0 will cause infinite loop because there is no terminating condition for 0.
So, option (C) is correct.
Note:It will print the binary representation of n and terminate, only if condition “if (n <= 0)".
#include <stdio.h>  void convert(int n) {    if(n <= 0)  printf("%d", n);      else {  convert(n / 2);  printf("%d", n%2);  };}  int main() { convert (16);}
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:12 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to change screen background color in Pygame? - GeeksforGeeks

01 Oct, 2020
Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language.
Functions Used:
pygame.init(): This function is used to initialize all the pygame modules.
pygame.display.set_mode(): This function is used to initialize a screen for display.
fill(): This method is used to fill the display with the color specified.
Example 1: This example sets the screen background color to red.
Python3
# Importing the libraryimport pygame  # Initializing Pygamepygame.init()  # Initializing surfacesurface = pygame.display.set_mode((400,300))  # Initialing RGB Color color = (255,0, 0)  # Changing surface colorsurface.fill(color)pygame.display.flip()
Output:
Example 2: This example uses RGB color to set the screen color to blue.
Python3
# Importing the libraryimport pygame  # Initializing Pygame modulespygame.init()  # Initializing surfacesurface = pygame.display.set_mode((400,300))  # Initialing RGB Color color = (0, 0, 255)  # Changing surface colorsurface.fill(color)pygame.display.flip()
Output:
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Filtering a PySpark DataFrame using isin by exclusion - GeeksforGeeks

29 Jun, 2021
In this article, we will discuss how to filter the pyspark dataframe using isin by exclusion.
isin(): This is used to find the elements contains in a given dataframe, it takes the elements and gets the elements to match the data.
Syntax: isin([element1,element2,.,element n)
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark  # 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  data  with null values# we can define null values with nonedata = [[1, "sravan", "vignan"],        [2, "ramya", "vvit"],        [3, "rohith", "klu"],        [4, "sridevi", "vignan"],        [5, "gnanesh", "iit"]]  # specify column namescolumns = ['ID', 'NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)dataframe.show()
Output:
Method 1: Using filter()
filter(): This clause is used to check the condition and give the results, Both are similar
Syntax: dataframe.filter(condition)
Example 1: Get the particular ID’s with filter() clause
Python3
# get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show()
Output:
Example 2: Get names from dataframe columns.
Python3
# get name as sravandataframe.filter((dataframe.NAME).isin(['sravan'])).show()
Output:
Method 2: Using Where()
where(): This clause is used to check the condition and give the results
Syntax: dataframe.where(condition)
Example 1: Get the particular colleges with where() clause.
Python3
# get college as vignandataframe.where((dataframe.college).isin(['vignan'])).show()
Output:
Example 2: Get ID except 5 from dataframe.
Python3
# get ID except 1dataframe.where(~(dataframe.ID).isin([1])).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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Java Program for Naive algorithm for Pattern Searching - GeeksforGeeks

11 Dec, 2018
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12


Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.
Java
// Java program for Naive Pattern Searchingpublic class NaiveSearch {      public static void search(String txt, String pat)    {        int M = pat.length();        int N = txt.length();          /* A loop to slide pat one by one */        for (int i = 0; i <= N - M; i++) {              int j;              /* For current index i, check for pattern               match */            for (j = 0; j < M; j++)                if (txt.charAt(i + j) != pat.charAt(j))                    break;              if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]                System.out.println("Pattern found at index " + i);        }    }      public static void main(String[] args)    {        String txt = "AABAACAADAABAAABAA";        String pat = "AABA";        search(txt, pat);    }}// This code is contributed by Harikishore
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13

Please refer complete article on Naive algorithm for Pattern Searching for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Replace a Element in Java ArrayList?
Java Program to Read a File to String
Java Program to Find Sum of Array Elements
How to Write Data into Excel Sheet using Java?
Removing last element from ArrayList in Java
Tic-Tac-Toe Game in Java
Java Program to Write an Array of Strings to the Output Console
Python | Type conversion in dictionary values - GeeksforGeeks

16 Aug, 2021
The problem of conventional type conversion is quite common and can be easily done using the built-in converters of python libraries. But sometimes, we may require the same functionality in a more complex scenario vis. for keys of list of dictionaries. Let’s discuss certain ways in which this can be achieved.Method #1 : Naive Method In the naive method, we employ 2 loops, nested. One for all the dictionaries in the list and the second one for the dictionary key-value pairs in a specific dictionary. 
Python3
# Python3 code to demonstrate# Type conversion in list of dicts.# using naive method # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint ("The original list is : " + str(test_list)) # using naive method# type conversation in list of dicts.for dicts in test_list:    for keys in dicts:        dicts[keys] = int(dicts[keys])     # printing resultprint ("The modified converted list is : " +  str(test_list))
Output :  
The original list is : [{'a': '1', 'b': '2'}, {'c': '3', 'd': '4'}]
The modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
 Method #2 : Using items() + list comprehension This can easily performed using just a one line with the help of list comprehension. The items function can be exploited to extract the list values as when required and list comprehension part handles the iteration part. 
Python3
# Python3 code to demonstrate# Type conversion in list of dicts.# using items() + list comprehension # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint ("The original list is : " + str(test_list)) # using items() + list comprehension# type conversation in list of dicts.res = [dict([key, int(value)]       for key, value in dicts.items())       for dicts in test_list]     # printing resultprint ("The modified converted list is : " +  str(res))
Output :  
The original list is : [{'b': '2', 'a': '1'}, {'c': '3', 'd': '4'}]
The modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
 
kalrap615
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary