code-rag-bench/online-tutorials huggingface dataset:
Python program to check if number is palindrome (one-liner)

23 Apr, 2020
Sometimes, we have an application of checking a number is palindrome or not and it’s quite common while day-day programming or competitive programming, it’s easy to reverse a number and check it but sometimes for readability and reducing lines of code, we require to perform this in one-liner logic. Let’s discuss certain ways in which this can be achieved.
Input : test_number = 12321Output : True
Input : test_number = 1234Output : False
Method #1 : Using math.log() + recursion + list comprehensionThe combination of above three functions can perform this particular task easily, the logs function extracts the number of digits which is powered by 10 to get the number for that iteration for comparison. The process is recurred to test for palindrome.
# Python3 code to demonstrate# checking a number is palindrome# using math.log() + recursion + list comprehensionimport math   # the recursive function to reversedef rev(num):    return int(num != 0) and ((num % 10) * \             (10**int(math.log(num, 10))) + \                          rev(num // 10))  # initializing number test_number = 9669669  # printing the original number print ("The original number is : " + str(test_number))  # using math.log() + recursion + list comprehension# for checking a number is palindromeres = test_number == rev(test_number)  # printing resultprint ("Is the number palindrome ? : " + str(res))
The original number is : 9669669
Is the number palindrome ? : True

 Method #2 : Using str() + string slicingThis can also be done by converting the number into a string and then reversing it using the string slicing method and comparing it, truth of which returns the answer to it.
# Python3 code to demonstrate# checking a number is palindrome# using str() + string slicing  # initializing number test_number = 9669669  # printing the original number print ("The original number is : " + str(test_number))  # using str() + string slicing# for checking a number is palindromeres = str(test_number) == str(test_number)[::-1]  # printing resultprint ("Is the number palindrome ? : " + str(res))
The original number is : 9669669
Is the number palindrome ? : True

We can also read input as string and then simply check for palindrome.
num = input("Enter a number")if num == num[::-1]:    print("Yes its a palindrome")else:    print("No, its not a palindrome")
jackyuvaraj551
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | focus_set() and focus_get() method

25 Jun, 2019
Tkinter has a number of widgets to provide functionality in any GUI. It also supports a variety of universal widget methods which can be applied on any of the widget.focus_get() and focus_set() methods are also universal widget methods. They can also be applied on Tk() method.
This method is used to set the focus on the desired widget if and only if the master window is focused.
Syntax:
widget.focus_set()

Below is the Python program-
# Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import *  # creating master windowmaster = Tk()  # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH)  # Button widget which currently has the focuse2 = Button(master, text ="Button")  # here focus_set() method is used to set the focuse2.focus_set()e2.pack(pady = 5)  # Radiobuton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5)  # Infinite loopmainloop()
Output:
You may observe in above image that Button widget has the focus. For better understanding copy and run above program.
This method returns the name of the widget which currently has the focus.
Syntax:
master.focus_get()

Note: You can use it with any of the widget, master in not necessary.
Below is the Python program –
# Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import *  # creating master windowmaster = Tk()  # This method is used to get# the name of the widget# which currently has the focus# by clicking Mouse Button-1def focus(event):    widget = master.focus_get()    print(widget, "has focus")  # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH)  # Button Widgete2 = Button(master, text ="Button")e2.pack(pady = 5)  # Radiobutton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5)  # Here function focus() is binded with Mouse Button-1# so every time you click mouse, it will call the# focus method, defined abovemaster.bind_all("<Button-1>", lambda e: focus(e))  # infinite loopmainloop()
Output: Every time you click on any widget OR if you click the mouse button-1 above program will print the name of the widget which has the focus. For better understanding copy and run above program.
.!radiobutton has focus
.!entry has focus
.!button has focus

Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS findDOMNode() Method

26 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the FindDOMNode() method is used to return DOM of the given element.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import ReactDOM from 'react-dom';  // Defining our App Componentconst App = () => {    // Function to get element from findDOMNode()  function find() {    var node = document.getElementById("node");    var a = ReactDOM.findDOMNode(node);    console.log(a);    a.style.color = 'green';    a.style.fontSize = "x-large";  }    // Returning our JSX code  return <>    <div>      <h1>GeeksforGeeks</h1>      <div id='node'>DOM Node</div>      <button onClick={find}>Click to find</button>    </div>  </>;}  // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference:https://reactjs.org/docs/react-dom.html#finddomnode
ReactJS-Basics
ReactJS-Methods
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
EAFP Principle in Python - GeeksforGeeks

10 May, 2020
EAFP is a piece of gem advice in the Python community which may not be familiar to programmers of other communities. Quickly, EAFP or ‘Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later.
“Always remember that it’s much easier to apologize than to get permission. In this world of computers, the best thing to do is to do it.” — Grace Hopper
It is unlike the traditional method of LBYL or ‘Look Before You Leap’, where you check whether your code will succeed and proceed if and only if there is no error.
Example: Suppose you want to open a file and read its contents.
‘Permission’ code:
import os    # Race conditionFile_name ="test.txt"  if os.access(File_name, os.R_ok):    with open(File_name) as f:        print(f.read())else:    print("No such file accessed") 
When you ask for permission to read the file, the answer is ‘Yes’, but by the time you actually go for reading the answer is changed. This is where you open yourself to the Race condition.
‘Forgiveness’ code: What you should do instead is go ahead with the flow and ask for forgiveness i.e catch the error using Exception handling.
# No Race conditionFile_name ="test.txt"  try:    f = open(File_name)except IOError:    print("No such file accessed") else:    with f:        print(f.read())
The Advantages of the EAFP method:
Explicit is better than implicit
Fail, but Fail fast and Succeed faster
Fail, but Fail cheap
Don’t repeat yourself
Python-Miscellaneous
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
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Arranging clustering column in descending order in Cassandra - GeeksforGeeks

15 Jan, 2020
Perquisite – CassandraIn this article, we are going to discuss how we can arrange table data and how we can arrange clustering column in descending order in a table.
To arrange clustering column in descending order first, we are going to create a table with clustering column.
First, we will see the results without using order by clause.Let’s have a look.
CREATE TABLE Emp_track (
  emp_no int,
  dept text,
  name text,
  PRIMARY KEY (dept, emp_no)
); 
Now, we are going to insert some data into the table.Let’s have a look.
insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); 
insert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); 
insert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); 
insert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); 
insert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey');  
Now, to see the results used the following CQL query given below.
select * 
from Emp_track; 
Output:
Now, here we are going to using order by clause.Let’s have a look.
CREATE TABLE Emp_track (
  emp_no int,
  dept text,
  name text,
  PRIMARY KEY (dept, emp_no)
)
WITH CLUSTERING ORDER BY (emp_no desc); 
Here, we will see emp_no is a clustering column and to arrange it in descending order we will use order by clause at the time of table creation.
Now, we are going to insert some data into the table.Let’s have a look.
insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); 
insert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); 
insert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); 
insert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); 
insert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey'); 

Now, to see the results used the following CQL query given below.
select * 
from Emp_track; 
Output:
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
SQL Trigger | Student Database
CTE in SQL
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of ER Model
Data Preprocessing in Data Mining
Introduction of DBMS (Database Management System) | Set 1
SQL | GROUP BY
SQL | Views
How to Use Word() Function in Arduino?

The word() function converts a variable of any data type to the word data type. It is essentially a cast function.
The syntax is −
word(var)
Where var is a variable of any datatype.
Alternatively, you can also construct a word by specifying two bytes, the higher byte and the lower byte.
The syntax is −
word(highByte, lowByte)
For instance, word(2,5) will return 517 (2 is 0b00000010 and 5 is 0b00000101; word(2,5) will return 0b0000001000000101, which equals 517).
You can try out other combinations of characters and data types. You can read more about the word function from Arduino’s official documentation here.
C program to represent the numbers in spiral pattern

The spiral pattern to represent the numbers is shown below −
The logic applied to print the numbers in spiral pattern is as follows −
for(i=1;i<=rows*2;i+=2){
   if(k%2==1){
      printf("%3d %3d",i,i+1);
      k++;
   }else{
      printf("%3d %3d",i+1,i);
      k++;
   }
   printf("\n");
}
Following is the C program for representing the numbers in spiral pattern −
#include<stdio.h>
main(){
   int i,rows,k=1;
   printf("Enter number of Rows for Spiral Pattern\n");
   scanf("%d",&rows);
   for(i=1;i<=rows*2;i+=2){
      if(k%2==1){
         printf("%3d %3d",i,i+1);
         k++;
      }else{
         printf("%3d %3d",i+1,i);
         k++;
      }
      printf("\n");
   }
}
When the above program is executed, it produces the following result −
Enter number of Rows for Spiral Pattern
10
1 2
4 3
5 6
8 7
9 10
12 11
13 14
16 15
17 18
20 19
Python Program to find the cube of each list element - GeeksforGeeks

17 Feb, 2021
Given a list, the task is to write a python program to cube all the list elements.
Input: [1, 2, 3, 4]
Output: [1, 8, 27, 64]
Explanation: Cubing all the list elements
Input: [2, 4, 6]
Output: [8, 64, 216]
Method 1 : Using loop
This is the brute force way. In this, we just multiply the same element two times to itself.
Example:
Python3
# Initializing listl = [1, 2, 3, 4]  # Cube List using loopres = []for i in l:    res.append(i*i*i)  # printing resultprint(res)
Output:
[1, 8, 27, 64]
Method 2 : Using pow() function
This is also the brute force way. In this, we use in-built pow() function
Example:
Python3
# Initializing listl = [1, 2, 3, 4]  # Cube List using loopres = []for i in l:    res.append(pow(i, 3))  # printing resultprint(res)
Output:
[1, 8, 27, 64]
Method 3 : Using list comprehension
This task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner.
Example:
Python3
# Initializing listl = [1, 2, 3, 4]  # Cube List using list comprehensionres = [pow(i, 3) for i in l]  # printing resultprint(res)
Output:
[1, 8, 27, 64]
Method 4: Using lambda
This can also be achieved using lambda function
Example:
Python3
# Initializing listl = [1, 2, 3, 4]  res = list(map(lambda x: x ** 3, l))print(res)
Output:
[1, 8, 27, 64]
Python list-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Count common characters in two strings in C++

We are given with the two strings let’s say str1 and str2 and the task is to find the count of common characters in two strings i.e. if str1[i] = str[j], then they will be considered as a pair and count will increased to 1 and if str1[i]!=str2[j] then they willn’t be considered as a pair and count willn’t increase to 1.
Input − str1 = “hello”
      str2 = “heoo”
Output − count is: 3
Explanation − str1[0] = str2[0] i.e. h ; str1[1] = str2[1] i.e. e ; str1[2]!=str2[2] i.e. l and o; str1[3]=str2[3] i.e. o. So, the pairs with similar letters are 3 and 1 pair containing different letters.
Input − str1 = “point”
      str2 = “print”
Output − count is: 4
Explanation − str1[0] = str2[0] i.e. p ; str1[1] != str2[1] i.e. o and r ; str1[2] =str2[2] i.e. i; str1[3]=str2[3] i.e. n; str1[4]=str2[4] i.e. t. So, the pairs with similar letters are 4 and 1 pair containing different letters.
Input the two strings str1 and str2
Input the two strings str1 and str2
Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces.
Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces.
Initially, Initialize the frequency of characters in both the string with 0.
Initially, Initialize the frequency of characters in both the string with 0.
Now, for updating the frequency of str1 apply “f1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2
Now, for updating the frequency of str1 apply “f1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2
For calculating the count of pairs apply min() function for f1 and f2.
For calculating the count of pairs apply min() function for f1 and f2.
Display the result
Display the result
 Live Demo
#include <iostream>
using namespace std;
// Function to count the valid indices pairs
int pairs(string str1, int size1, string str2, int size2){
   // f1 and f2 for frequencies of characters
   // of string str1 and str2
   int f1[26] = { 0 };
   int f2[26] = { 0 };
   // 'c' To count the valid pairs
   int i, c = 0;
   //updating the frequencies of str1 and st2
   for (i = 0; i < size1; i++){
      f1[str1[i] - 'a']++;
   }
   for (i = 0; i < size2; i++){
      f2[str2[i] - 'a']++;
   }
   // Find the count of valid pairs
   for (i = 0; i < 26; i++){
      c += (min(f1[i], f2[i]));
   }
   return c;
}
// main function
int main(){
   string str1 = "tutorialspoint", str2 = "codingground";
   int size1 = str1.length(), size2 = str2.length();
   cout<<”Total pairs with str1[i]=str2[j] are: ”;
   cout << pairs(str1, size1, str2, size2);
   return 0;
}
If we run the above code it will generate the following output −
Total pairs with str1[i]=str2[j] are − 6
What is the difference between IEnumerable and IQueryable in C#?

IEnumerable exists in System.Collections Namespace.
IQueryable exists in System. Linq Namespace.
Both IEnumerable and IQueryable are forward collection.
IEnumerable doesn’t support lazy loading
IQueryable support lazy loading
Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data.
Querying data from a database, IQueryable execute the select query on the server side with all filters.
IEnumerable Extension methods take functional objects.
IQueryable Extension methods take expression objects means expression tree.
dbContext dc = new dbContext ();
IEnumerable
<SocialMedia>
list = dc.SocialMedias.Where(p => p.Name.StartsWith("T"));
list = list.Take<SocialMedia>(1);
</SocialMedia>
SELECT [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]
WHERE [t0].[Name] LIKE @p0
dbContext dc = new dbContext ();
IQueryable<SocialMedia> list = dc.SocialMedias.Where(p => p.Name.StartsWith("T"));
list = list.Take<SocialMedia>(1);
SELECT top 1 [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]
WHERE [t0].[Name] LIKE @p0
Calculate the Interquartile Range in R Programming - IQR() Function - GeeksforGeeks

17 Jun, 2020
IQR() function in R Language is used to calculate the interquartile range of a data set.
Mathematically,IQR = Q3 – Q1
where,Q3 specifies the median of n largest valuesQ1 specifies the median of n smallest values
But, R provides in-built IQR() function to perform the upgiven calculations
Syntax: IQR(x)
Parameters:x: Data set
Example 1:
# R program to calculate IQR value  # Defining vector x <- c(5, 5, 8, 12, 15, 16)     # Print Interquartile range print(IQR(x)) 
Output:
[1] 8.5

Example 2:
# R program to calculate IQR value  # Defining a matrix x <- matrix(c(1:9), 3, 3)    # Print Interquartile range print(IQR(x)) 
Output:
[1] 4

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
Maximum sum of pairwise product in an array with negative allowed in C++ program

In this problem, we are given an array arr[] that contains n integers values
(negative values allowed). Our task is to create a program to find the
maximum sum of pairwise products in an array with negative allowed.
Problem Description − We need to create pairs using the elements of the array such that the sum of the product of elements of pairs is maximum.
Let’s take an example to understand the problem,
arr[] = {−5, 2, 3, 7, −1, 1, −3, 12}
104
The pairs to be considered: (−5, −3), (2, 3), (−1, 1), (7, 12)
Sum of product = (−5 * −3) + (2 * 3) + (−1 * 1) + (7 * 12) = 15 + 6 − 1 + 84 =
104.
To solve the problem, we will be finding pairs in such a way that the sum of
their products is maximum. To maximize the sum, we need to pair the same
pair values together. And making this pairing easy, we need to sort the array
and then pair up negatives and positives. Then find if one positive or
negative or both values are present in the pair. If a positive/negative value is
remaining add it to the pair and if one negative and one positive are present
then add their product.
Initialize −
maxSum = 0.
Step 1 −
Sort the array arr[].
Step 2 −
Loop for all negative values of the array. Make pairs, and add their
product to maxSum.
Step 3 −
Loop for all positive values of the array. Make pairs, and add their
product to maxSum.
Step 4 −
At last check the remaining values.
Step 4.1 −
If one positive value remains, add it to maxSum.
Step 4.1 −
If one negative value remains, add it to maxSum.
Step 4.1 −
If one positive value and one negative value remains, add
their product to maxSum.
Step 5 −
Return maxSum.
Program to illustrate the working of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
long calcSumPairProd(int arr[], int n) {
   long maxSum = 0;
   sort(arr, arr + n);
   int i = 0, j = (n − 1);
   while (i < n && arr[i] < 0) {
      if (i != n − 1 && arr[i + 1] <= 0) {
         maxSum = (maxSum + (arr[i] * arr[i + 1]) );
         i += 2;
      }
      else
      break;
   }
   while (j >= 0 && arr[j] > 0) {
      if (j != 0 && arr[j − 1] > 0) {
         maxSum = (maxSum + (arr[j] * arr[j − 1]) );
         j −= 2;
      }
      else
      break;
   }
   if (j > i)
   maxSum = (maxSum + (arr[i] * arr[j]) );
   else if (i == j)
   maxSum = (maxSum + arr[i]);
   return maxSum;
}
int main() {
   int arr[] = { −5, 2, 3, 7, −1, 1, −3, 12 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum sum of pairwise product in an array is "<<calcSumPairProd(arr, n);
   return 0;
}
The maximum sum of pairwise product in an array is 104
C++ IOS Library - rdbuf

It is used to get/set stream buffer. If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit).
Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function).
Following is the declaration for ios::rdbuf function.
get (1)	streambuf* rdbuf() const;
set (2)	streambuf* rdbuf (streambuf* sb);
The first form (1) returns a pointer to the stream buffer object currently associated with the stream.
The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags.
sb − Pointer to a streambuf object.
A pointer to the stream buffer object associated with the stream before the call.
Basic guarantee − if an exception is thrown, the stream is in a valid state. It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit.
Accesses (1) or modifies (2) the stream object.
Concurrent access to the same stream object may cause data races.
In below example explains about ios::rdbuf function.
#include <iostream>     
#include <fstream>      

int main () {
   std::streambuf *psbuf, *backup;
   std::ofstream filestr;
   filestr.open ("test.txt");

   backup = std::cout.rdbuf();     

   psbuf = filestr.rdbuf();        
   std::cout.rdbuf(psbuf);         

   std::cout << "This is written to the file";

   std::cout.rdbuf(backup);        

   filestr.close();

   return 0;
}
 Print
 Add Notes
 Bookmark this page
Path toFile() method in Java with Examples

18 Jul, 2019
The toFile() method of java.nio.file.Path interface used to return a java.io.File object representing this path object. if this Path is associated with the default provider, then this method returns a java.io.File object constructed with the String representation of this path. If this path was created by invoking the java.io.File toPath method then there is no guarantee that the File object returned by this method is equal to the original File. This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Syntax:
default File toFile()

Parameters: This method accepts nothing.
Return value: This method returns a java.io.File object representing this path.
Exception: This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Below programs illustrate toFile() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toFile() method  import java.io.File;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path = Paths.get("D:\\Apps\\"                              + "NewTextDocument.txt");          // call toFile() to get        // File object from path        File file = path.toFile();          // print file details        System.out.println("File:" + file.toString()                           + " is readable "                           + file.canRead());    }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.toFile() method  import java.io.File;import java.nio.file.Path;import java.nio.file.Paths;public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path = Paths.get("D:\\temp\\"                              + "AmanSinghCV.docx");          // call toFile() to get        // File object from path        File file = path.toFile();          // print file details        System.out.println("File Name:"                           + file.getName());    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toFile()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
C++ Program to Check if a string can be obtained by rotating another string 2 places

06 Jan, 2022
Given two strings, the task is to find if a string can be obtained by rotating another string two places. 
Examples: 
Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise
Asked in: Amazon Interview
1- There can be only two cases:
    a) Clockwise rotated
    b) Anti-clockwise rotated

2- If clockwise rotated that means elements
   are shifted in right.
   So, check if a substring[2.... len-1] of 
   string2 when concatenated with substring[0,1]
   of string2 is equal to string1. Then, return true.

3- Else, check if it is rotated anti-clockwise 
   that means elements are shifted to left.
   So, check if concatenation of substring[len-2, len-1]
   with substring[0....len-3] makes it equals to
   string1. Then return true.

4- Else, return false.
Below is the implementation of the above approach.
C++
// C++ program to check if a string // is two time rotation of another string.#include<bits/stdc++.h>using namespace std;  // Function to check if string2 is // obtained by string 1bool isRotated(string str1,                string str2){    if (str1.length() != str2.length())        return false;    if(str1.length()<2){      return str1.compare(str2) == 0;    }    string clock_rot = "";    string anticlock_rot = "";    int len = str2.length();      // Initialize string as anti-clockwise     // rotation    anticlock_rot = anticlock_rot +                    str2.substr(len-2, 2) +                    str2.substr(0, len-2) ;      // Initialize string as clock wise     // rotation    clock_rot = clock_rot +                str2.substr(2) +                str2.substr(0, 2) ;      // check if any of them is equal     // to string1    return (str1.compare(clock_rot) == 0 ||            str1.compare(anticlock_rot) == 0);}  // Driver codeint main(){    string str1 = "geeks";    string str2 = "eksge";      isRotated(str1, str2) ? cout << "Yes"                          : cout << "No";    return 0;}
Output: 
Yes
Please refer complete article on Check if a string can be obtained by rotating another string 2 places for more details!
Accolite
Amazon
rotation
C++
C++ Programs
Strings
Accolite
Amazon
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
xdg-open command in Linux with Examples

24 May, 2019
xdg-open command in the Linux system is used to open a file or URL in the user’s preferred application.The URL will be opened in the user’s preferred web browser if a URL is provided. The file will be opened in the preferred application for files of that type if a file is provided. xdg-open supports ftp, file, https and http URLs. This can be used inside a desktop session only. It is not recommended to use xdg-open as root. Here, the zero is an indication of success while non-zero show the failure.
Syntax:
xdg-open {file | URL}

Example:
xdg-open read.html
Options:
xdg-open –version : This option will show the xdg-utils version information.xdg-open --version
xdg-open --version
xdg-open –help: This option will show command synopsis.xdg-open --help
xdg-open --help
xdg-open –manual: This option will show the manual page.xdg-open --manual
xdg-open --manual
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find indices of elements equal to zero in a NumPy array

05 Sep, 2020
Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements. 
Method 1: Finding indices of null elements using numpy.where()
This function returns the indices of elements in an input array where the given condition is satisfied.
Syntax : 
numpy.where(condition[, x, y])
When True, yield x, otherwise yield y

Python3
# importing Numpy packageimport numpy as np  # creating a 1-D Numpy arrayn_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,                    6, 7, 5, 0, 8])  print("Original array:")print(n_array)  # finding indices of null elements using np.where()print("\nIndices of elements equal to zero of the \given 1-D array:")  res = np.where(n_array == 0)[0]print(res)
Output:
Method 2: Finding indices of null elements using numpy.argwhere()
This function is used to find the indices of array elements that are non-zero, grouped by element.
Syntax : 
numpy.argwhere(arr)

Python3
# importing Numpy packageimport numpy as np  # creating a 3-D Numpy arrayn_array = np.array([[0, 2, 3],                    [4, 1, 0],                    [0, 0, 2]])  print("Original array:")print(n_array)  # finding indices of null elements # using np.argwhere()print("\nIndices of null elements:")res = np.argwhere(n_array == 0)  print(res)
Output:
Method 3: Finding the indices of null elements using numpy.nonzero()
This function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.
Syntax:
numpy.nonzero(arr)
Python3
# importing Numpy packageimport numpy as np  # creating a 1-D Numpy arrayn_array = np.array([1, 10, 2, 0, 3, 9, 0,                     5, 0, 7, 5, 0, 0])  print("Original array:")print(n_array)  # finding indices of null elements using # np.nonzero()print("\nIndices of null elements:")  res = np.nonzero(n_array == 0)print(res)
Output:
Python numpy-Indexing
Python-numpy
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
Declare a const array in C#

In C#, use readonly to declare a const array.
public static readonly string[] a = { "Car", "Motorbike", "Cab" };
In readonly, you can set the value at runtime as well unlike const.
Another alternative of achieving what we saw above −
public ReadOnlyCollection<string> a { get { return new List<string> { "Car", "Motorbike", "Cab" }.AsReadOnly();}}

.NET framework 4.5 brings an improvement to what we saw −
public ReadOnlyCollection<string> a { get; } = new ReadOnlyCollection<string>(
new string[] { "Car", "Motorbike", "Cab" }
);
MySQL query to get all characters before a specific character hyphen

For this, you can use SUBSTRING_INDEX(). Let us first create a table −
mysql> create table DemoTable1857
     (
     Name varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1857 values('John-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1857 values('Brown-Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1857 values('David-Carol-Miller');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1857;
This will produce the following output −
+--------------------+
| Name               |
+--------------------+
| John-Smith         |
| Brown-Chris        |
| David-Carol-Miller |
+--------------------+
3 rows in set (0.00 sec)
Here is the query to get all characters before specific character hyphen −
mysql> select substring_index(Name,'-',1) Name from DemoTable1857;
This will produce the following output −
+-------+
| Name  |
+-------+
| John  |
| Brown |
| David |
+-------+
3 rows in set (0.00 sec)
Find the Nth term of the series 1, 3, 7, 15, 31 . . . - GeeksforGeeks

20 Jan, 2022
Given a positive integer N, the task is to find Nth term of the series:
1, 3, 7, 15, 31, .....
Examples:
Input: N = 5Output: 31
Input: N = 1Output: 1
Approach:
The sequence is formed by using the following pattern. For any value N-
TN = 2N – 1
Illustration:
Input: N = 5Output: 31Explanation:TN = 2N – 1     = 25 – 1     = 32 – 1      = 31
Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return// Nth term of the seriesint findTerm(int N){    return pow(2, N) - 1;} // Driver Codeint main(){    int N = 5;    cout << findTerm(N);    return 0;}
// Java program to implement// the above approachimport java.util.*; public class GFG{   // Function to return  // Nth term of the series  static int findTerm(int N)  {    return (int)Math.pow(2, N) - 1;  }   // Driver Code  public static void main(String args[])  {    int N = 5;    System.out.println(findTerm(N));   }} // This code is contributed by Samim Hossain Mondal.
# Python program to implement# the above approach # Function to return# Nth term of the seriesdef findTerm(N):         return pow(2, N) - 1 # Driver CodeN = 5print(findTerm(N)) # This code is contributed by samim2000.
// C# program to implement// the above approachusing System; class GFG{   // Function to return  // Nth term of the series  static int findTerm(int N)  {    return (int)Math.Pow(2, N) - 1;  }   // Driver Code  public static void Main()  {    int N = 5;    Console.Write(findTerm(N));   }} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript program to implement// the above approach // Function to return// Nth term of the seriesfunction findTerm(N){    return Math.pow(2, N) - 1;} // Driver Codelet N = 5;document.write(findTerm(N)); // This code is contributed by saurabh_jaiswal.</script>
  
31
 
Time Complexity: O(1)
 
Auxiliary Space: O(1)
 
samim2000
lokeshpotta20
_saurabh_jaiswal
Algo-Geek 2021
series
Algo Geek
Mathematical
Pattern Searching
Mathematical
series
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of operation required to water all the plants
Sort strings on the basis of their numeric part
Encode given String by inserting in Matrix column-wise and printing it row-wise
Check if the given string is valid English word or not
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Sweetviz: Automated EDA in Python | by Himanshu Sharma | Towards Data Science

Exploratory Data Analysis is a process where we tend to analyze the dataset and summarize the main characteristics of the dataset often using visual methods. EDA is really important because if you are not familiar with the dataset you are working on, then you won’t be able to infer something from that data. However, EDA generally takes a lot of time.
But, what if I told you that python can automate the process of EDA with the help of some libraries? Won’t it make your work easier? So let’s start learning about Automated EDA.
In this article, we will work on Automating EDA using Sweetviz. It is a python library that generates beautiful, high-density visualizations to start your EDA. Let us explore Sweetviz in detail.
Like any other python library, we can install Sweetviz by using the pip install command given below.
pip install sweetviz
In this article, I have used an advertising dataset contains 4 attributes and 200 rows. First, we need to load the using pandas.
import pandas as  pddf = pd.read_csv('Advertising.csv')
Sweetviz has a function named Analyze() which analyzes the whole dataset and provides a detailed report with visualization.
Let’s Analyze our dataset using the command given below.
# importing sweetvizimport sweetviz as sv#analyzing the datasetadvert_report = sv.analyze(df)#display the reportadvert_report.show_html('Advertising.html')
And here we go, as you can see above our EDA report is ready and contains a lot of information for all the attributes. It’s easy to understand and is prepared in just 3 lines of code.
Other than this Sweetviz can also be used to visualize the comparison of test and train data. For comparison let us divide this data into 2 parts, first 100 rows for train dataset and rest 100 rows for the test dataset.
Compare() function of Sweetviz is used for comparison of the dataset. The commands given below will create and compare our test and train dataset.
df1 = sv.compare(df[100:], df[:100])df1.show_html('Compare.html')
Other than this there are many more functions that Sweetviz provides for that you can go through this.
So what do you think about this beautiful library? Go ahead try this and mention your experiences in the response section.
There are some other libraries that automate the EDA process one of which is Pandas Profiling which I have explained earlier in an article given below.
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can also view the code and data I have used here in my Github.
How to write a singleton class in C++?

Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. For example, if you are using a logger, that writes logs to a file, you can use a singleton class to create such a logger. You can create a singleton class using the following code.
#include <iostream>
using namespace std;
class Singleton {
   static Singleton *instance;
   int data;
   // Private constructor so that no objects can be created.
   Singleton() {
      data = 0;
   }
   public:
      static Singleton *getInstance() {
         if (!instance)
         instance = new Singleton;
         return instance;
      }
   int getData() {
      return this -> data;
   }
   void setData(int data) {
      this -> data = data;
   }
};
//Initialize pointer to zero so that it can be initialized in first call to getInstance
Singleton *Singleton::instance = 0;
int main(){
   Singleton *s = s->getInstance();
   cout << s->getData() << endl;
   s->setData(100);
   cout << s->getData() << endl;
   return 0;
}
0
100
Period between() method in Java

The Period between two dates can be obtained using the between() method in the Period class in Java. This method requires two parameters i.e. the start date and the end date and it returns the Period between these two dates.
A program that demonstrates this is given as follows
 Live Demo
import java.time.Period;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] args) {
      LocalDate startDate = LocalDate.parse("2015-03-15");
      LocalDate endDate = LocalDate.parse("2019-05-20");
      System.out.println("The start date is: " + startDate);
      System.out.println("The end date is: " + endDate);
      Period p = Period.between(startDate, endDate);
      System.out.println("\nThe Period between the start and end date is : " + p);
   }
}
The start date is: 2015-03-15
The end date is: 2019-05-20
The Period between the start and end date is : P4Y2M5D
Now let us understand the above program.
First the start date and end date is displayed. Then the Period between these two dates is obtained using the between() method and displayed. A code snippet that demonstrates this is as follows:
LocalDate startDate = LocalDate.parse("2015-03-15");
LocalDate endDate = LocalDate.parse("2019-05-20");
System.out.println("The start date is: " + startDate);
System.out.println("The end date is: " + endDate);
Period p = Period.between(startDate, endDate);
System.out.println("\nThe Period between the start and end date is : " + p);
MySQL Tryit Editor v1.0

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Apache POI Word - Paragraph

In this chapter you will learn how to create a Paragraph and how to add it to a document using Java. Paragraph is a part of a page in a Word file.
After completing this chapter, you will be able to create a Paragraph and perform read operations on it.
First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph.
The following code snippet is used to create a spreadsheet −
//Create Blank document
XWPFDocument document = new XWPFDocument();

//Create a blank spreadsheet
XWPFParagraph paragraph = document.createParagraph();

You can enter the text or any object element, using Run. Using Paragraph instance you can create run.
The following code snippet is used to create a Run.
XWPFRun run = paragraph.createRun();

Let us try entering some text into a document. Consider the below text data −
At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose 
in the domains of Academics, Information Technology, Management and Computer Programming Languages.

The following code is used to write the above data into a paragraph.
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CreateParagraph {
   public static void main(String[] args)throws Exception {
      //Blank Document
      XWPFDocument document = new XWPFDocument(); 
      
      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File("createparagraph.docx"));
        
      //create Paragraph
      XWPFParagraph paragraph = document.createParagraph();
      XWPFRun run = paragraph.createRun();
      run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming Languages.");
			
      document.write(out);
      out.close();
      System.out.println("createparagraph.docx written successfully");
   }
}
Save the above Java code as CreateParagraph.java, and then compile and run it from the command prompt as follows −
$javac CreateParagraph.java
$java CreateParagraph

It will compile and execute to generate a Word file named createparagraph.docx in your current directory and you will get the following output in the command prompt −
createparagraph.docx written successfully

The createparagraph.docx file looks as follows.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page