code-rag-bench/online-tutorials huggingface dataset:
Palindrome Partitioning


In this algorithm, the input is a string, a partitioning of that string is palindrome partitioning when every substring of the partition is a palindrome.
In this algorithm, we have to find the minimum cuts are needed to palindrome partitioning the given string.
Input:
A string. Say “ababbbabbababa”
Output:
Minimum cut to partition as palindrome. Here 3 cuts are needed.
The palindromes are: a | babbbab | b | ababa
minPalPart(str)
Input: The given string.
Output: Minimum number of palindromic partitioning from the string.
Begin
   n := length of str
   define cut matrix and pal matrix each of order n x n

   for i := 0 to n, do
      pal[i, i] := true
      cut[i, i] := 0
   done

   for len in range 2 to n, do
      for i in range 0 to n – len, do
         j := i + len – 1
         if len = 2, then
            if str[i] = str[j]
               pal[i, j] := true
         else
            if str[i] = str[j] and pal[i+1, j-1] ≠ 0
               pal[i, j] := true

         if pal[i, j] is true, then
            cut[i, j] := 0
         else

            cut[i, j] := ∞
            for k in range i to j-1, do
               cut[i, j] := minimum of cut[i, j] and (cut[i, k]+ cut[k+1, j+1]+1)
            done
      done
   done
   return cut[0, n-1]
End
#include <iostream>
using namespace std;

int min (int a, int b) {
   return (a < b)? a : b;
}

int minPalPartion(string str) {
   int n = str.size();

   int cut[n][n];
   bool pal[n][n];              //true when palindrome present for i to jth  element

   for (int i=0; i<n; i++) {
      pal[i][i] = true;         //substring of length 1 is plaindrome
      cut[i][i] = 0;
   }

   for (int len=2; len<=n; len++) {
      for (int i=0; i<n-len+1; i++) {        //find all substrings of length len

         int j = i+len-1;              // Set ending index
         if (len == 2)                 //for two character string
            pal[i][j] = (str[i] == str[j]);
         else                  //for string of more than two characters
            pal[i][j] = (str[i] == str[j]) && pal[i+1][j-1];

         if (pal[i][j] == true)
            cut[i][j] = 0;
         else {
            cut[i][j] = INT_MAX;          //initially set as infinity
            for (int k=i; k<=j-1; k++)
               cut[i][j] = min(cut[i][j], cut[i][k] + cut[k+1][j]+1);
         }
      }
   }
   return cut[0][n-1];
}

int main() {
   string str= "ababbbabbababa";
   cout << "Min cuts for Palindrome Partitioning is:" << minPalPartion(str);
}
Min cuts for Palindrome Partitioning is: 3
Count the number of unique characters in a string in Python - GeeksforGeeks

06 Jul, 2021
Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string.
Examples:
Input: S = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 6 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}.
Input: S = “madam”Output: 3
Approach: The idea to solve the given problem is to initialize a Set() in python to store all distinct characters of the given string and then, print the size of the set as the required answer.
Below is the implementation of the above approach:
Python3
# Python program for the above approach # Function to count the number of distinct# characters present in the string strdef countDis(str):     # Stores all distinct characters    s = set(str)     # Return the size of the set    return len(s)  # Driver Codeif __name__ == "__main__":     # Given string S    S = "geeksforgeeks"     print(countDis(S))
7
 
Time Complexity: O(N)Auxiliary Space: O(1)
Count the frequencies of all elements using Counter function and number of keys of this frequency dictionary gives the result.
Below is the implementation:
Python3
# Python program for the above approachfrom collections import Counter # Function to count the number of distinct# characters present in the string strdef countDis(str):     # Stores all frequencies    freq = Counter(str)     # Return the size of the freq dictionary    return len(freq)  # Driver Codeif __name__ == "__main__":     # Given string S    S = "geeksforgeeks"     print(countDis(S))     # This code is contributed by vikkycirus
Output:
7
Time Complexity: O(N)
Auxiliary Space: O(N)
official_vivek
vikkycirus
arorakashish0911
HashSet
python-set
Hash
Python
Strings
Technical Scripter
python-set
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Hashing in Java
Load Factor and Rehashing
Hash Functions and list/types of Hash functions
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Export CSV File without Row Names in R - GeeksforGeeks

09 May, 2021
In this article, we will learn how to export CSV files without row names in R Programming Language. In R language we use write.csv() function to create a CSV file from the data. 
Syntax: write.csv(df, path) 
Parameters:
df: dataframe object
path: local path on your system where .csv file will be written/saved.
For this, we have to create a dataframe with the required values and then export values to a dataframe on the provided path. If the file doesn’t exist it firsts create it. If it does, it will be overwritten.
By default, the data is exported with row names. Let us see an example to understand better.
Example:
R
df <- data.frame(c1 = 20:24,                   c2 = c(2021,2020,2019,2018,2017),                   c3 = rep("GFG", 5))                     write.csv(df, "dataframe.csv")
Output:
Now to export data without row names we simply have to pass row.names=FALSE as an argument in the write.csv() function.
Example:
R
df <- data.frame(c1 = 20:24,                   c2 = c(2021,2020,2019,2018,2017),                   c3 = rep("GFG", 5))                     write.csv(df, "dataframe.csv", row.names=FALSE)
Output:
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
How to change Colors in ggplot2 Line Plot in R ?
How to filter R DataFrame by values in a column?
Linear Discriminant Analysis in R Programming
R - Operators
How to create a hyperlink to link another document in HTML?

Use the <a> tag to create a hyperlink. The HTML <a> tag is used for creating a hyperlink either to another document, or somewhere within the current document.
The following are the attributes −
You can try to run the following code to create a link −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML a Tag</title>
   </head>
   <body>
      <p>This is a link to <a href = "https://qries.com">Qries.com</a></p>
   </body>
</html>
C++ Numeric Library - partial_sum

It is used to compute partial sums of range and assigns to every element in the range starting at result the partial sum of the corresponding elements in the range [first,last).
Following is the declaration for std::partial_sum.
	
template <class InputIterator, class OutputIterator>
   OutputIterator partial_sum (InputIterator first, InputIterator last,
                               OutputIterator result);	
template <class InputIterator, class OutputIterator, class BinaryOperation>
   OutputIterator partial_sum (InputIterator first, InputIterator last,
                               OutputIterator result, BinaryOperation binary_op);
template <class InputIterator, class OutputIterator>
   OutputIterator partial_sum (InputIterator first, InputIterator last,
                               OutputIterator result);	
template <class InputIterator, class OutputIterator, class BinaryOperation>
   OutputIterator partial_sum (InputIterator first, InputIterator last,
                               OutputIterator result, BinaryOperation binary_op);
first, last − It iterators to the initial and final positions in a sequence.
first, last − It iterators to the initial and final positions in a sequence.
init − It is an initial value for the accumulator.
init − It is an initial value for the accumulator.
binary_op − It is binary operation.
binary_op − It is binary operation.
binary_op2 − It is binary operation and taking two elements.
binary_op2 − It is binary operation and taking two elements.
It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored, or result if [first,last) is an empty range.
It throws if any of the operations on the elements or iterators throws.
The elements in the range [first1,last1) are accessed.
In below example for std::partial_sum.
#include <iostream>
#include <functional>
#include <numeric>

int myop (int x, int y) {return x+y+1;}

int main () {
   int val[] = {10,20,30,40,50};
   int result[5];

   std::partial_sum (val, val+5, result);
   std::cout << "Default partial_sum: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';

   std::partial_sum (val, val+5, result, std::multiplies<int>());
   std::cout << "Functional operation multiplies: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';

   std::partial_sum (val, val+5, result, myop);
   std::cout << "Custom function: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';
   return 0;
}
The output should be like this −
Default partial_sum: 10 30 60 100 150 
Functional operation multiplies: 10 200 6000 240000 12000000 
Custom function: 10 31 62 103 154 

 Print
 Add Notes
 Bookmark this page
Python Pandas – Check if any specific column of two DataFrames are equal or not

To check if any specific column of two DataFrames are equal or not, use the equals() method. Let us first create DataFrame1 with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)
Create DataFrame2 with two columns −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)
Check for the equality of a specific column Units −
dataFrame2['Units'].equals(dataFrame1['Units'])

Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# check for equality
print"\nAre both the DataFrame objects equal? ",dataFrame1.equals(dataFrame2)

# check for specific column Units equality
print"\nAre both the DataFrames have similar Units column? ",dataFrame2['Units'].equals(dataFrame1['Units']
)
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90

DataFrame2 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90

Are both the DataFrame objects equal? True

Are both the DataFrames have similar Units column? True
ReactJS – componentWillMount() Method

In this article, we are going to see how to execute a function before the component is loaded in the DOM tree.
This method is used during the mounting phase of the React lifecycle. This function is generally called before the component gets loaded in the DOM tree. This method is called before the render() method is called, so it can be used to initialize the state but the constructor is preferred.
This method is generally used in server-side rendering. Don’t call subscriptions or side-effects in this method; use componentDidMount instead.
Note: This method is now deprecated.
UNSAFE_componentWillMount()
In this example, we will build a color-changing React application that changes the color of the text as soon as the component is loaded in the DOM tree.
Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.
App.jsx
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <ChangeName />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   constructor(props) {
      super(props);
      this.state = { color: 'lightgreen' };
   }
   UNSAFE_componentWillMount() {
      // Changing the state immediately.
      this.setState({ color: 'wheat' });
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
This will produce the following result.
How to convert a vector into matrix in R?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.
Here, we will read vectors by their names to make it easy but you can change their names if you want. There are four vectors of different lengths that are shown in these examples −
s
> Vector1<-1:9
> Vector1
[1] 1 2 3 4 5 6 7 8 9
> Vector1<-as.matrix(Vector1)
> Vector1
   [,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
> Vector1<-matrix(Vector1,nrow=3)
> Vector1
   [,1] [,2] [,3]
[1,] 1   4    7
[2,] 2   5    8
[3,] 3   6    9
> Vector2<-c(24,26,14,15,39,18,17,25,17,19,18,23,24,19,27,15)
> Vector2
[1] 24 26 14 15 39 18 17 25 17 19 18 23 24 19 27 15
> Vector2<-as.matrix(Vector2)
> Vector2
    [,1]
[1,] 24
[2,] 26
[3,] 14
[4,] 15
[5,] 39
[6,] 18
[7,] 17
[8,] 25
[9,] 17
[10,] 19
[11,] 18
[12,] 23
[13,] 24
[14,] 19
[15,] 27
[16,] 15
> Vector2<-matrix(Vector2,nrow=4,byrow=TRUE)
> Vector2
    [,1] [,2] [,3] [,4]
[1,] 24   26   14   15
[2,] 39   18   17   25
[3,] 17   19   18   23
[4,] 24   19   27   15
> Vector3<-sample(1:100,25)
> Vector3
[1] 86 84 32 14 4 78 7 82 71 38 98 87 58 54 46 44 88 65 97 60 31 89 63 91 90
> Vector3<-matrix(Vector3,nrow=5)
> Vector3
    [,1] [,2] [,3] [,4] [,5]
[1,] 86   78   98   44   31
[2,] 84    7   87   88   89
[3,] 32   82   58   65   63
[4,] 14   71   54   97   91
[5,]  4   38   46   60   90
> Vector3<-matrix(Vector3,nrow=2)
Warning message:
In matrix(Vector3, nrow = 2) :
data length [25] is not a sub-multiple or multiple of the number of rows [2]
> Vector4<-1:10
> Vector4
[1] 1 2 3 4 5 6 7 8 9 10
> Vector4<-matrix(Vector4,nrow=2)
> Vector4
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> Vector4<-matrix(Vector4,ncol=2)
> Vector4
   [,1] [,2]
[1,] 1    6
[2,] 2    7
[3,] 3    8
[4,] 4    9
[5,] 5   10
Getting rounded value of a number in Julia - round() Method - GeeksforGeeks

21 Apr, 2020
The round() is an inbuilt function in julia which is used to round the specified number in different ways which are illustrated below-
The default round process is done to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.
The specified value x is rounded to an integer value and returns a value of the given type T or of the same type of x.
If the digits keyword parameter is given, it rounds to the specified number of digits after the decimal place (or before if negative), in the given base.
If the sigdigits keyword parameter is given, it rounds to the specified number of significant digits, in the given base.
Syntax:round(x)round(T, x)round(x, digits::Integer, base)round(x, sigdigits::Integer, base)
Parameters:
x: Specified number
T: Specified number type
digits: Specified digit values
base: Specified base in which results are coming
sigdigits: Specified significant digits
Returns: It returns the rounded value of the specified number.
Example 1:
# Julia program to illustrate # the use of round() method  # Getting the rounded valuesprintln(round(2))println(round(2.3))println(round(2.9))println(round(0.5))println(round(2.5))println(round(3.5))
Output:
2
2.0
3.0
0.0
2.0
4.0

Example 2:
# Julia program to illustrate # the use of round() method  # Getting the rounded valuesprintln(round(pi; digits = 3))println(round(56.7685; digits = 3))println(round(pi; digits = 3, base = 2))println(round(55.98634; digits = 3, base = 2))println(round(324.675; sigdigits = 2))println(round(232.97634; sigdigits = 4, base = 2))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Working with Excel Files in Julia
Getting last element of an array in Julia - last() Method
Join an array of strings into a single string in Julia - join() Method
File Handling in Julia
How to create typewriter effect in ReactJS ?

25 Jan, 2021
The typewriter effect in ReactJS is a JS package that can be used for a better UI design. This effect allows us to create a simple typing animation in ReactJS. For using Typewriter in ReactJS we need to install the typewriter-effect package.
Prerequisites:
Basics of ReactJS
Already created ReactJSapp
Below all the steps are described order-wise to use styled-components in React.
Installation:
Step 1: Before moving further, firstly we have to install the typewriter-effect, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.npm install --save typewriter-effectyarn add typewriter-effect
npm install --save typewriter-effect
yarn add typewriter-effect
Step 2: After installing the package, now open your App.js file which is present inside your project’s directory, under the src folder, and delete the code present inside it.
Step 3: Now import React and typewriter-effect package.
Step 4: In your app.js file, add this code snippet to import React and typewriter-effect package.import React from 'react';
import Typewriter from "typewriter-effect";
import React from 'react';
import Typewriter from "typewriter-effect";
Below is a sample program to illustrate the use of the typewriter-effect :
Filename- App.js:
Javascript
import React from 'react';  //importing typewriter-effectimport Typewriter from "typewriter-effect";import './App.css';  function App() {  return (    <div className="App">      <Typewriter         onInit={(typewriter)=> {         typewriter               .typeString("GeeksForGeeks")                .pauseFor(1000)       .deleteAll()       .typeString("Welcomes You")       .start();       }}       />    </div>  );}  export default App;
Filename- App.css
CSS
.App {  font-family: sans-serif;  font-weight:800;  font-size:40px;  text-align: center;  display:flex;  justify-content:center;  align-items:center;  min-height:100vh;  background:green;}
Output: Hence using the above-mentioned steps, we can use the typewriter-effect to import and change the typing animation React. 
Technical Scripter 2020
ReactJS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript SyntaxError – JSON.parse: bad parsing

31 Jul, 2020
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid.
Message:
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' 
             was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in 
             object
SyntaxError: JSON.parse: expected ',' or '}' after property-value 
             pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after 
             JSON data
SyntaxError: JSON.parse Error: Invalid character at position {0} 
             (Edge)

Error Type:
SyntaxError


Cause of Error: This string passed to JSON.parse() method is invalid and will throw this error.
Example 1:
HTML
<script>    var str = '{"Prop_1" : "Val_1"}';    JSON.parse(str);    document.write(str);</script>
Output:
{"Prop_1" : "Val_1"}

Example 2:
HTML
<script>    var str = '{"Prop_1" : "Val_1"}}';    JSON.parse(str);    document.write(str);</script>
Output(in console):
Unexpected token } in JSON at position 2

javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TensorFlow – How to create one hot tensor

01 Aug, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
One hot tensor is a Tensor in which all the values at indices where i =j and i!=j is same. 
Method Used:
one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified.
Example 1:
Python3
# importing the libraryimport tensorflow as tf  # Initializing the Inputindices = tf.constant([1, 2, 3])  # Printing the Inputprint("Indices: ", indices)  # Generating one hot Tensorres = tf.one_hot(indices, depth = 3)  # Printing the resulting Tensorsprint("Res: ", res )
Output:
Indices:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[0. 1. 0.]
 [0. 0. 1.]
 [0. 0. 0.]], shape=(3, 3), dtype=float32)


Example 2: This example explicitly defines the on and off values for the one hot tensor.
Python3
# importing the libraryimport tensorflow as tf  # Initializing the Inputindices = tf.constant([1, 2, 3])  # Printing the Inputprint("Indices: ", indices)  # Generating one hot Tensorres = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1)  # Printing the resulting Tensorsprint("Res: ", res )
Output:
Indices:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[-1  3 -1]
 [-1 -1  3]
 [-1 -1 -1]], shape=(3, 3), dtype=int32)



Python-Tensorflow
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Python OpenCv: Write text on video

30 Jan, 2020
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human.
cv2.putText() method inserts a text on the video frame at the desired position specified by the user. We can style the type of font and also it’s color and thickness.
Syntax : cv2.putText(frame, Text, org, font, color, thickness)
Parameters:frame: current running frame of the video.Text: The text string to be inserted.org: bottom-left corner of the text stringfont: the type of font to be used.color: the colour of the font.thickness: the thickness of the font
Example:
# Python program to write# text on video    import cv2    cap = cv2.VideoCapture('sample_vid.mp4')  while(True):          # Capture frames in the video    ret, frame = cap.read()      # describe the type of font    # to be used.    font = cv2.FONT_HERSHEY_SIMPLEX      # Use putText() method for    # inserting text on video    cv2.putText(frame,                 'TEXT ON VIDEO',                 (50, 50),                 font, 1,                 (0, 255, 255),                 2,                 cv2.LINE_4)      # Display the resulting frame    cv2.imshow('video', frame)      # creating 'q' as the quit     # button for the video    if cv2.waitKey(1) & 0xFF == ord('q'):        break  # release the cap objectcap.release()# close all windowscv2.destroyAllWindows()
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.ticker.LinearLocator Class in Python

16 Jun, 2022
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.ticker.LinearLocator class is used to determine the tick locations. At its first call the function tries to set up the number of ticks to make a nice tick partitioning. There after the interactive navigation improves as  the number of ticks get fixed. The preset parameter is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs.
Syntax: class matplotlib.ticker.LinearLocator(numticks=None, presets=None) 
Parameters:
numticks: Number of ticks in total.
presets: It is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs.
Methods of the class:
set_params(self, numticks=None, presets=None): It is used to set parameters within this locator.
tick_values(self, vmin, vmax): It returns the values of located ticks between the vmin and vmax.
view_limits(self, vmin, vmax): It is used to intelligently choose the view limits.
Example 1: 
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker  xGrid = np.linspace(1-1e-14, 1-1e-16, 30,                    dtype = np.longdouble) y = np.random.rand(len(xGrid)) plt.plot(xGrid, y)plt.xlim(1-1e-14, 1) loc = matplotlib.ticker.LinearLocator(numticks = 5)plt.gca().xaxis.set_major_locator(loc) plt.show()
Output:
  
Example 2: 
Python3
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as ticker  # Setup a plot such that only the bottom# spine is showndef setup(ax):         ax.spines['right'].set_color('green')    ax.spines['left'].set_color('red')         ax.yaxis.set_major_locator(ticker.NullLocator())    ax.spines['top'].set_color('pink')    ax.xaxis.set_ticks_position('bottom')         ax.tick_params(which ='major', width = 1.00)    ax.tick_params(which ='major', length = 5)    ax.tick_params(which ='minor', width = 0.75)    ax.tick_params(which ='minor', length = 2.5)         ax.set_xlim(0, 5)    ax.set_ylim(0, 1)    ax.patch.set_alpha(0.0) plt.figure(figsize =(8, 6))n = 8ax = plt.subplot(n, 1, 4)setup(ax)ax.xaxis.set_major_locator(ticker.LinearLocator(3))ax.xaxis.set_minor_locator(ticker.LinearLocator(31)) ax.text(0.0, 0.1, "LinearLocator",        fontsize = 14,        transform = ax.transAxes) plt.subplots_adjust(left = 0.05,                    right = 0.95,                    bottom = 0.05,                    top = 1.05) plt.show()
Output:
 
surinderdawra388
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to initialize all the imported modules in PyGame?

27 Apr, 2022
PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it’s operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post describes how all the imported modules can be initialized at a time.
Methods Used:  
pygame.init() – To initialize all the modules. It takes no arguments and return a tuple (numpass,numfail) which indicate the no of modules initialized successfully and the number of modules failed.  
pygame.get_init() – This method is used to check whether pygame modules are initialized or not.  
Example 1: This example initialize all the pygame modules and print the number of modules initialized successfully.
Python3
# importing the libraryimport pygame # initializing all the imported# pygame modules(numpass,numfail) = pygame.init() # printing the number of modules# initialized successfullyprint('Number of modules initialized successfully:',      numpass)
  
Output:  
 
Number of modules initialized successfully: 6
 
Example 2: This example uses pygame.get_init() function to check whether pygame module is initialized or not.
 
Python3
# importing the libraryimport pygame # initializing the modulespygame.init() # checking the initializationis_initialized = pygame.get_init() # printing the resultprint('Is pygame modules initialized:',      is_initialized)
  
Output:
 
Is pygame modules initialized: True
 
sooda367
avtarkumar719
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of python program | Set 11(Lists)

22 Apr, 2022
Pre-requisite: List in python 1) What is the output of the following program? 
Python
data = [2, 3, 9]temp = [[x for x in[data]] for x in range(3)]print (temp)
a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]] c) [[[2, 3, 9]], [[2, 3, 9]]] d) None of these Ans. (a) Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer for statement prints the newly created list 3 times. 2) What is the output of the following program? 
Python
data = [x for x in range(5)]temp = [x for x in range(7) if x in data and x%2==0]print(temp)
a) [0, 2, 4, 6] b) [0, 2, 4] c) [0, 1, 2, 3, 4, 5] d) Runtime error Ans. (b) Explanation: The is statement checks whether the value lies in list data and if it does whether it’s divisible by 2. It does so for x in (0, 7). 3) What is the output of the following program? 
Python
temp = ['Geeks', 'for', 'Geeks']arr = [i[0].upper() for i in temp]print(arr)
a) [‘G’, ‘F’, ‘G’] b) [‘GEEKS’] c) [‘GEEKS’, ‘FOR’, ‘GEEKS’] d) Compilation error Ans. (a) Explanation: The variable i is used to iterate over each element in list temp. i[0] represent the character at 0th index of i and .upper() function is used to capitalize the character present at i[0]. 4) What is the output of the following program? 
Python
temp = 'Geeks 22536 for 445 Geeks'data = [x for x in (int(x) for x in temp if x.isdigit()) if x%2 == 0]print(data)
a) [2, 2, 6, 4, 4] b) Compilation error c) Runtime error d) [‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’] Ans. (a) Explanation: This is an example of nested list comprehension. The inner list created contains a list of integer in temp. The outer list only procures those x which are a multiple of 2. 5) What is the output of the following program? 
Python
data = [x for x in (x for x in 'Geeks 22966 for Geeks' if x.isdigit()) if(x in ([x for x in range(20)]))]print(data)
a) [2, 2, 9, 6, 6] b) [] c) Compilation error d) Runtime error Ans. (b) Explanation: Since here x have not been converted to int, the condition in the if statement fails and therefore, the list remains empty. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
python-list
Python-Output
Program Output
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.dtype

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.dtype attribute returns the data type of the underlying data for the given Series object.
Syntax: Series.dtype
Parameter : None
Returns : data type
Example #1: Use Series.dtype attribute to find the data type of the underlying data for the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.dtype attribute to find the data type of the given Series object.
# return the data typesr.dtype
Output :
As we can see in the output, the Series.dtype attribute has returned ‘O’ indicating the data type of the underlying data is object type.
Example #2 : Use Series.dtype attribute to find the data type of the underlying data for the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([1000, 5000, 1500, 8222])  # Print the seriesprint(sr)
Output :
Now we will use Series.dtype attribute to find the data type of the given Series object.
# return the data typesr.dtype
Output :As we can see in the output, the Series.dtype attribute has returned ‘int64’ indicating the data type of the underlying data is of int64 type.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between = and IN operator in SQL - GeeksforGeeks

21 Aug, 2020
Prerequisite – SQL CommandsIn this article we are going to see the difference between = and IN operator in SQL.
1. = Operator :The = operator is used with Where Clause in SQL.For Example consider the student table given below,
Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using = operator would be,
 SELECT * 
FROM Student 
WHERE ADDRESS='Delhi' OR ADDRESS='ROHTAK'; 
Output :
2. IN Operator :The IN operator is used with Where Clause to test if the expression matches any value in the list of values. The advantage of using IN operator is that it avoids the use of multiple OR Operator.
Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using IN operator would be,
SELECT * 
FROM Student 
WHERE ADDRESS IN ('Delhi', 'ROHTAK'); 
Output :
Difference between = and IN Operator :
DBMS-SQL
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between TCP and UDP
Difference between Process and Thread
How can we sort a JSONArray in Java?

The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. 
We can sort a JSONArray in the below example.
import java.util.*;
import org.json.*;
public class SortJSONArrayTest {
   public static void main(String[] args) {
      String jsonStr = "[ { \"ID\": \"115\", \"Name\": \"Raja\" },{ \"ID\": \"120\", \"Name\": \"Jai\" },{ \"ID\": \"125\", \"Name\": \"Adithya\" }]";
      JSONArray jsonArray = new JSONArray(jsonStr);
      JSONArray sortedJsonArray = new JSONArray();
      List list = new ArrayList();
      for(int i = 0; i < jsonArray.length(); i++) {
         list.add(jsonArray.getJSONObject(i));
      }
      System.out.println("Before Sorted JSONArray: " + jsonArray);
      Collections.sort(list, new Comparator() {
         private static final String KEY_NAME = "Name";
         @Override
         public int compare(JSONObject a, JSONObject b) {
            String str1 = new String();
            String str2 = new String();
            try {
               str1 = (String)a.get(KEY_NAME);
               str2 = (String)b.get(KEY_NAME);
            } catch(JSONException e) {
               e.printStackTrace();
            }
            return str1.compareTo(str2);
         }
      });
      for(int i = 0; i < jsonArray.length(); i++) {
         sortedJsonArray.put(list.get(i));
      }
      System.out.println("Sorted JSON Array with Name: " + sortedJsonArray);
   }
}
Before Sorted JSONArray:
[{"ID":"115","Name":"Raja"},
   {"ID":"120","Name":"Jai"},
   {"ID":"125","Name":"Adithya"}]
Sorted JSON Array with Name:
[{"ID":"125","Name":"Adithya"},
   {"ID":"120","Name":"Jai"},
   {"ID":"115","Name":"Raja"}]
Group array by equal values JavaScript

Let’s say, we have an array of string / number literals that contains some duplicate values like
this −
const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night'];
We are required to write a function groupSimilar() that takes in this array and returns a new
array where all the repeating entries are group together in a subarray as the first element and
their total count in the original array as the second element.
So, for this example, the output should be −
[
   [ 'day', 3 ],
   [ 'night', 4 ],
   [ 'afternoon', 2 ],
   [ 'noon', 2 ]
]
Let’s write the code for this function. We will use the Array.prototype.map() function to construct
a new, required, array, and we will use a Map to keep track of the repeating entries in the
array −
const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night',
'noon', 'day', 'afternoon', 'day', 'night'];
const groupSimilar = arr => {
   return arr.reduce((acc, val) => {
      const { data, map } = acc;
      const ind = map.get(val);
      if(map.has(val)){
         data[ind][1]++;
      } else {
         map.set(val, data.push([val, 1])-1);
      }
      return { data, map };
   }, {
      data: [],
      map: new Map()
   }).data;
};
console.log(groupSimilar(array));
The output in the console will be −
[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]
Perform min/max with MongoDB aggregation

For min/max in MongoDB, use minandmax. Let us create a collection with documents −
> db.demo251.insertOne({"Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46c0001627c0c63e7dba74")
}
> db.demo251.insertOne({"Marks":87});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46c0031627c0c63e7dba75")
}
> db.demo251.insertOne({"Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46c0061627c0c63e7dba76")
}
> db.demo251.insertOne({"Marks":76});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46c00c1627c0c63e7dba77")
}
Display all documents from a collection with the help of find() method −
> db.demo251.find();
This will produce the following output −
{ "_id" : ObjectId("5e46c0001627c0c63e7dba74"), "Marks" : 78 }
{ "_id" : ObjectId("5e46c0031627c0c63e7dba75"), "Marks" : 87 }
{ "_id" : ObjectId("5e46c0061627c0c63e7dba76"), "Marks" : 56 }
{ "_id" : ObjectId("5e46c00c1627c0c63e7dba77"), "Marks" : 76 }
Following is the query to implement min/max aggregation in MongoDB −
> db.demo251.aggregate([
...   { "$group": {
...      "_id": null,
...      "MaxMarks": { "$max": "$Marks" },
...      "MinMarks": { "$min": "$Marks" }
...   }}
...])
This will produce the following output −
{ "_id" : null, "MaxMarks" : 87, "MinMarks" : 56 }
How to skip empty dates (weekends) in a financial Matplotlib Python graph?

To skip weekends in a financial graph in matplotlib, we can iterate the time in dataframe and skip the plot if weekday is 5 or 6.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a dataframe with keys time.
Create a dataframe with keys time.
Iterate zipped index and time of a date frame.
Iterate zipped index and time of a date frame.
If iterated timestamp is having weekday 5 or 6, don't plot them.
If iterated timestamp is having weekday 5 or 6, don't plot them.
Other than 5 or 6 weekday, plot the points.
Other than 5 or 6 weekday, plot the points.
Set the current tick locations of Y-axis.
Set the current tick locations of Y-axis.
Lay out a plot with grid lines.
Lay out a plot with grid lines.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(dict(time=list(pd.date_range(start="2021-01-01", end="2021-01-15"))))
for i, t in zip(df.index, df.time):
   if t.weekday() in (5, 6):
      pass
   else:
      plt.plot(i, t, marker="*", ms=10)
plt.yticks(df.time)
plt.grid(True)
plt.show()
Java - tan() Method

The method returns the tangent of the specified double value.
double tan(double d)

Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns the tangent of the specified double value.
public class Test { 

   public static void main(String args[]) {
      double degrees = 45.0;
      double radians = Math.toRadians(degrees);

      System.out.format("The value of pi is %.4f%n", Math.PI);
      System.out.format("The tangent of %.1f degrees is %.4f%n", degrees, Math.tan(radians));
   }
}
This will produce the following result −
The value of pi is 3.1416
The tangent of 45.0 degrees is 1.0000


    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
How to use Boto3 to get the details of a single crawler?

Problem Statement − Use boto3 library in Python to get the details of a crawler.
Example − Get the details of a crawler, crawler_for_s3_file_job.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − crawler_name is the mandatory parameter. It is a string so user can send only one crawler name at a time to fetch details.
Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4 − Create an AWS client for glue.
Step 5 − Now use get_crawler function and pass the crawler_name.
Step 6 − It returns the metadata of the crawler.
Step 7 − Handle the generic exception if something went wrong while checking the job.
Use the following code to fetch the details of a crawler −
import boto3
from botocore.exceptions import ClientError

def get_one_crawler_details(crawler_name:str)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      crawler_details = glue_client.get_crawler(Name= crawler_name)
      return crawler_details
   except ClientError as e:
      raise Exception("boto3 client error in get_one_crawler_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in get_one_crawler_details: " + e.__str__())
print(get_one_crawler_details("crawler_for_s3_file_job"))
{'Crawler': {'Name': 'crawler_for_s3_file_job', 'Role': 'glue-role',
'Targets': {'S3Targets': [{'Path': 's3://test/', 'Exclusions': []}],
'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []},
'DatabaseName': 'default', 'Classifiers': [], 'SchemaChangePolicy':
{'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior':
'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'TablePrefix': 'prod_scdk_',
'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2018, 9, 24,
20, 42, 7, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4,
27, 14, 49, 12, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED',
'LogGroup': '/aws-glue/crawlers', 'LogStream':
'crawler_for_s3_file_job', 'MessagePrefix': ************-90ad1',
'StartTime': datetime.datetime(2020, 4, 27, 14, 49, 19,
tzinfo=tzlocal())}, 'Version': 15}, 'ResponseMetadata': {'RequestId':
'8c7dcbde-***********************-774', 'HTTPStatusCode': 200,
'HTTPHeaders': {'date': 'Sun, 28 Feb 2021 11:34:32 GMT', 'content-type':
'application/x-amz-json-1.1', 'content-length': '805', 'connection':
'keep-alive', 'x-amzn-requestid': '8c7dcbde-**********************774'},
'RetryAttempts': 0}}
How to change the value of an attribute using jQuery?

The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value. In the example, we will change the attribute value tutorialspoint.com to tutorialspoint.com/java.
You can try to run the following code to learn how to change the value of an attribute using jQuery −
Live Demo
<html>
   <head>
      <title>Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
       $(document).ready(function(){
         $("button").click(function(){
           $("#tpoint").attr("href", "https://www.tutorialspoint.com/java");
         });
       });
      </script>
   </head>
   <body>
      <p><a href="https://www.tutorialspoint.com" id="tpoint">tutorialspoint.com</a></p>
      <button>Change attribute value</button>
      <p>The value of above link will change on clicking the above button. Check before and after clicking the link.</p>
   </body>
</html>