code-rag-bench/online-tutorials huggingface dataset:
Different Methods to find Prime Number in Python Program

In this tutorial, we are going to explore different methods to find whether a given number is valid or not. Let's start without further due.
It's a general method to find prime numbers.
If the number is less than or equal to one, return False.
If the number is less than or equal to one, return False.
If the number is divisible by any number, then the function will return False.
If the number is divisible by any number, then the function will return False.
After the loop, return True.
After the loop, return True.
 Live Demo
# checking for prime
def is_prime(n):
   if n <= 1:
      return False
   else:
      for i in range(2, n):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
   return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
In this method, we are reducing the number of iterations by cutting them to the square root of n.Let's see the code.
 Live Demo
import math
# checking for prime
def is_prime(n):
   if n <= 1:
      return False
   else:
      # iterating loop till square root of n
      for i in range(2, int(math.sqrt(n)) + 1):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
      return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
In the previous method, we have checked for the even numbers. We all know that even numbers
can't be prime except two. So, in this method, we will remove all evens to reduce the time.
 Live Demo
import math
# checking for prime
def is_prime(n):
   # checking for less than 1
   if n <= 1:
      return False
   # checking for 2
   elif n == 2:
      return True
   elif n > 2 and n % 2 == 0:
      return False
   else:
      # iterating loop till square root of n
      for i in range(3, int(math.sqrt(n)) + 1, 2):
         # checking for factor
         if n % i == 0:
            # return False
            return False
      # returning True
      return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
If you have doubts in the tutorial, mention them in the comment section.
Python | Skipping Test Failures - GeeksforGeeks

12 Jun, 2019
Problem – To skip or mark selected tests as an anticipated failure in the unit tests.
The unittest module has decorators that can be applied to selected test methods to control their handling as shown in the code given below.
Code #1 :
import unittestimport osimport platform  class Tests(unittest.TestCase):    def test_0(self):        self.assertTrue(True)        @unittest.skip('skipped test')              def test_1(self):        self.fail('should have failed !')        @unittest.skipIf(os.name =='posix', 'Not supported on Unix')              def test_2(self):        import winreg    @unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific test')          def test_3(self):        self.assertTrue(True)        @unittest.expectedFailure    def test_4(self):        self.assertEqual(2 + 2, 5)          if __name__ == '__main__':    unittest.main()
Output:

bash % python3 testsample.py -v
test_0 (__main__.Tests) ... ok
test_1 (__main__.Tests) ... skipped 'skipped test'
test_2 (__main__.Tests) ... skipped 'Not supported on Unix'
test_3 (__main__.Tests) ... ok
test_4 (__main__.Tests) ... expected failure
----------------------------------------------------------------------
Ran 5 tests in 0.002s
OK (skipped = 2, expected failures = 1)

How it works :
The skip() decorator can be used to skip over a test that need not be run at all.
skipIf() and skipUnless() can be a useful way to write tests that only apply to certain platforms or Python versions, or which have other dependencies.
Use the @expectedFailure decorator to mark tests that are known failures, but for which the test framework need not report more information.
Code #2 : Applying decorators for skipping methods to entire testing classes
@unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific tests')class DarwinTests(unittest.TestCase):    ...
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
turtle.turtlesize() function in Python - GeeksforGeeks

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return or set the pen’s attributes x or y-stretchfactors and outline. 
Syntax :
turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)
Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue")  # loop for motionfor i in range(4):        # set turtle width    turtle.turtlesize(stretch_wid=(i+1)*0.5)    turtle.forward(100)    turtle.right(90)
Output :
Example 2 :
Python3
# import packageimport turtle  # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue")  # loop for motionfor i in range(4):      # set turtle length    turtle.turtlesize(stretch_len=(i+1)*0.5)    turtle.forward(100)    turtle.right(90)
Output :
Example 3 :
Python3
# import packageimport turtle  # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue")  # loop for motionfor i in range(4):        # set turtle outline    turtle.turtlesize(outline=i+1)    turtle.forward(100)    turtle.right(90)
Output :
Example 4 :
Python3
# import packageimport turtle  # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue")  # loop for motionfor i in range(4):        # set turtlesize properties all together    turtle.turtlesize(stretch_wid=(i+1)*0.5,                      stretch_len=(i+1)*0.5,                      outline=(i+1)                     )    turtle.forward(100)    turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
JSON with Python

This chapter covers how to encode and decode JSON objects using Python programming language. Let's start with preparing the environment to start our programming with Python for JSON.
Before you start with encoding and decoding JSON using Python, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed Demjson as follows −
$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install

Python encode() function encodes the Python object into a JSON string representation.
demjson.encode(self, obj, nest_level=0)

The following example shows arrays under JSON with Python.
#!/usr/bin/python
import demjson

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = demjson.encode(data)
print json
While executing, this will produce the following result −
[{"a":1,"b":2,"c":3,"d":4,"e":5}]

Python can use demjson.decode() function for decoding JSON. This function returns the value decoded from json to an appropriate Python type.
demjson.decode(self, txt)

The following example shows how Python can be used to decode JSON objects.
#!/usr/bin/python
import demjson

json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = demjson.decode(json)
print  text
On executing, it will produce the following result −
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}


    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to resolve exception Element Not Interactable Exception in Selenium?

We can resolve the exception – ElementNotInteractableException with Selenium webdriver. This exception is thrown if a webelement exists in DOM but cannot be accessed. The below image shows an example of such an exception.
If a specific webelement is overspread by another webelement we normally get this exception. To fix this, we can either apply explicit wait so that the webdriver waits for the expected condition - invisibilityOfElementLocated of the overlaying webelement.
Or, we can apply the expected condition - elementToBeClickable on the
webelement that we want to interact with. To resolve a permanent overlay, we have to use the JavaScript Executor to perform the click action. Selenium utilizes the executeScript method to run JavaScript commands.
WebDriverWait wait= (new WebDriverWait(driver, 5));
wait.until(ExpectedConditions . elementToBeClickable (By.id("element id")));
//alternate solution
wait.until(ExpectedConditions. invisibilityOfElementLocated(By.id("overlay element id")));
//fix with JavaScript executor
WebElement m = driver.findElement(By.id("element id"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();", m);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
public class InteractableExceptResolve{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://login.yahoo.com/");
      //identify element
      WebElement m = driver.findElement(By.xpath("//input[@id='persistent']"));
      //JavascriptExecutor to click element
      JavascriptExecutor jse = (JavascriptExecutor) driver;
      jse.executeScript("arguments[0].click();", m);
      boolean b = m.isSelected();
      if (b) {
         System.out.println("Checkbox is not checked");
      }else {
         System.out.println("Checkbox is checked");
      }
      driver.close();
   }
}
C Program for the Difference between sums of odd and even digits?

Given a number, find the difference between sum of odd digits and sum of even digits. Which means we will be count all even digits and all odd digits and the subtracting their sums.
Input:12345
Output:3
the odd digits is 2+4=6
the even digits is 1+3+5=9
odd-even=9-6=3
Taking every digit out of number and checking whether the digit is even or odd if even then add it to even sum if not then to odd sum and then take difference of them.
#include <iostream>
using namespace std;
int main() {
   int n, r=0;
   int diff =0;
   int even=0;
   int odd=0;
   n=12345;
   while(n != 0){
      r = n%10;
      if(r % 2 == 0) {
         even+=r;
      } else {
         odd+=r;
      }
      n/=10;
   }
   diff=odd-even;
   printf("%d",diff);
   return 0;
}
MySQL Tryit Editor v1.0

SELECT Country FROM Customers;
​
        
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.
How can we add FOREIGN KEY constraints to more than one fields of a MySQL table?

MySQL allows us to add a FOREIGN KEY constraint on more than one field in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.
Suppose we have a table ‘customer2’ which have a Primary Key constraint on the field ‘cust_unq_id’ as follows −
mysql> describe customer2;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| cust_id     | int(11)     | YES  |     | NULL    |       |
| First_name  | varchar(20) | YES  |     | NULL    |       |
| Last_name   | varchar(20) | YES  |     | NULL    |       |
| City        | varchar(10) | YES  |     | NULL    |       |
| cust_unq_id | int(11)     | NO   | PRI | 0       |       |
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
And we have a table orders1 which is already having a Foreign Key constraint on field ‘Cust_id’ referencing to the parent table ‘customer’.
mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
| cust_unq_id  | int(11)     | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.04 sec)
Now, with the help of following ALTER TABLE query we can add another foreign key constraint on the field ‘cust_unq_id’ referencing to the parent table ‘customer2’
mysql> Alter table orders1 add FOREIGN KEY(cust_unq_id) REFERENCES Customer2(Cust_unq_id);
Query OK, 0 rows affected (0.25 sec)
Records: 0  Duplicates: 0  Warnings: 0  

mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
| cust_unq_id  | int(11)     | YES  | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
From the above result set, it can be observed that ‘orders1’ table is having two, one on ‘cust_id’ and other on ‘cust_unq_id’ foreign key constraints.
What is Bubble Sort in Python? Explain with an example?

Bubble sort is a sorting algorithm to sort a list into ascending (or descending) order. This is the easiest sorting algorithm but it is not very efficient. It can be used on small input sizes but not time efficient for lists or arrays with larger length. Its time complexity is O(n^2). However, this is an in-place sorting algorithm, which means it doesn’t use any extra space. Thus, its efficient in terms of space complexity. However, it is not used much since there are better sorting algorithms than bubble sort.
In bubble sort, two for loops are used. The outer for loop iterates over the list. The inner for loop also iterates over the list for all the outer loop iterations.
The main operation in Bubble sort is to compare two consecutive elements. If the first element is greater than the next element, then swap both, so that the smaller element comes ahead and the greater element goes back.In one iteration of outer loop, the greatest element of the list goes at the last index. In the second iteration of the outer loop, the second largest element of the list goes at the second last index and so on. Therefore, we get the sorted list at the end of all the iterations.
We can better understand with the help of an example.
Example
We are required to sort the following list.
Outer loop=1
5>2, therefore swap both
5>1, therefore swap both
5>3, therefore swap both
5>4, therefore swap both
(The largest element 5 has reached at the last index after the first outer iteration)
Outer loop=2
2>1, therefore swap
No swapping required
No swapping required
As we can see the list is sorted in the 2nd outer iteration itself. But the outer loop will iterate 3 more times with no further swap operations. Hence,only 2 iterations are shown in the example. Sometimes, the list can be sorted in the first iteration itself. Sometimes, the list might be sorted in the last iteration. Thus, the outer loop will always iterate n times.
 Live Demo
def bubble_sort(arr):
   for i in range(len(arr)):
      for j in range(len(arr)-1):
         if(arr[j]>arr[j+1]):
            temp=arr[j]
            arr[j]=arr[j+1]
            arr[j+1]=temp
   return arr
array=[2,3,1,5,4]
print(bubble_sort(array))
[1, 2, 3, 4, 5]
StringTokenizer class in Java

The StringTokenizer class of the java.util package allows an application to break a string into tokens.
This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
Its methods do not distinguish among identifiers, numbers, and quoted strings.
This class methods do not even recognize and skip comments.
Live Demo
import java.util.*;  
public class Sample {
   public static void main(String[] args) {  
      // creating string tokenizer
      StringTokenizer st = new StringTokenizer("Come to learn");  
      // checking next token
      System.out.println("Next token is : " + st.nextToken());
  }    
}
Next token is : Come
.NET Core - Getting Started

Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start building a new .NET Core Application.
In the New Project dialog box, in the Templates list, expand the Visual C# node and select .NET Core and you should see the following three new project templates
Class Library (.NET Core)
Console Application (.NET Core)
ASP.NET Core Web Application (.NET Core)
In the middle pane on the New Project dialog box, select Console Application (.NET Core) and name it "FirstApp", then click OK.
Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project.
To test that .NET core console application is working, let us add the following line.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
  
namespace FirstApp { 
   public class Program { 
      public static void Main(string[] args) { 
         Console.WriteLine("Hello guys, welcome to .NET Core world!"); 
      } 
   } 
}
Now, run the application. You should see the following output.
 Print
 Add Notes
 Bookmark this page
Perl join Function

This function combines the elements of LIST into a single string using the value of EXPR to separate each element. It is effectively the opposite of split.
Note that EXPR is only interpolated between pairs of elements in LIST; it will not be placed either before the first or after the last element in the string. To join together strings without a separator, supply an empty string rather than undef.
Following is the simple syntax for this function −
join EXPR, LIST

This function returns the joined string.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$string = join( "-", "one", "two", "three" );
print"Joined String is $string\n";

$string = join( "", "one", "two", "three" );
print"Joined String is $string\n";
When above code is executed, it produces the following result −
Joined String is one-two-three
Joined String is onetwothree


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Is it possible to use UPDATE query with LIMIT in MySQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL. Let us see how.
For our example, we will first create a table. The CREATE command is used to create a table.
mysql>CREATE table tblUpdateLimit
-> (
-> id int,
-> name varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
Records are inserted with the help of INSERT command.
mysql>INSERT into tblUpdateLimit values(1,'John');
Query OK, 1 row affected (0.54 sec)

mysql>INSERT into tblUpdateLimit values(2,'Carol');
Query OK, 1 row affected (0.12 sec)

mysql>INSERT into tblUpdateLimit values(3,'Smith');
Query OK, 1 row affected (0.10 sec)

mysql>INSERT into tblUpdateLimit values(4,'Kayle');
Query OK, 1 row affected (0.44 sec)

mysql>INSERT into tblUpdateLimit values(5,'David');
Query OK, 1 row affected (0.13 sec)

mysql>INSERT into tblUpdateLimit values(6,'Jason');
Query OK, 1 row affected (0.18 sec)

mysql>INSERT into tblUpdateLimit values(7,'Larry');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into tblUpdateLimit values(8,'Serhat');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into tblUpdateLimit values(9,'Winny');
Query OK, 1 row affected (0.18 sec)
To display the above table, here is the query.
mysql> SELECT *from tblUpdateLimit;
The following is the output.
+------+--------+
| id   |name    |
+------+--------+
| 1    | John   |
| 2    | Carol  |
| 3    | Smith  |
| 4    | Kayle  |
| 5    | David  |
| 6    | Jason  |
| 7    | Larry  |
| 8    | Serhat |
| 9    | Winny  |
+------+--------+
9 rows in set (0.00 sec)
Let us now see the syntax to use UPDATE query with limit.
UPDATE yourTableName SET column_name='some value’'
WHERE column_name1 IN (
SELECT column_name1 FROM (
select column_name1 from yourTableName order by column_name1 asc limit integerValue,integerValue)
anyAliasName );
Implementing the query now to fulfil our purpose and using it to set the name ‘Adam’, with limit 7.
mysql> UPDATE tblUpdateLimit SET name = 'Adam'
-> WHERE id IN (
SELECT id FROM ( select id from tblUpdateLimit order by id asc limit 0,7)l);
Query OK, 7 rows affected (0.27 sec)
Rows matched: 7 Changed: 7 Warnings: 0
Check whether the table is updated or not.
mysql> SELECT *from tblUpdateLimit;
Here is the output.
+------+--------+
| id   | name   |
+------+--------+
| 1    | Adam   |
| 2    | Adam   | 
| 3    | Adam   |
| 4    | Adam   |
| 5    | Adam   |
| 6    | Adam   |
| 7    | Adam   |
| 8    | Serhat |
| 9    | Winny  |
+------+--------+
9 rows in set (0.00 sec)
Python 3 - String islower() Method

The islower() method checks whether all the case-based characters (letters) of the string are lowercase.
Following is the syntax for islower() method −
str.islower()

NA
This method returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
The following example shows the usage of islower() method.
#!/usr/bin/python3

str = "THIS is string example....wow!!!"
print (str.islower())

str = "this is string example....wow!!!"
print (str.islower())
When we run above program, it produces the following result −
False
True


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Quickly search for a string in MySQL database?

Use FULLTEXT search to quickly search for a string. Let us first create a table −
mysql> create table DemoTable1554
   -> (
   -> Title text
   -> );
Query OK, 0 rows affected (0.63 sec)
Here is the query to create full text search −
mysql> create fulltext index faster_title on DemoTable1554(Title);
Query OK, 0 rows affected, 1 warning (7.09 sec)
Records: 0  Duplicates: 0  Warnings: 1
Insert some records in the table using insert command −
mysql> insert into DemoTable1554 values('John is working on MySQL database');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable1554 values('Adam Smith is working on Java language');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1554 values('John smith is working on Python Language');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1554;
This will produce the following output −
+------------------------------------------+
| Title                                    |
+------------------------------------------+
| John is working on MySQL database        |
| Adam Smith is working on Java language   |
| John smith is working on Python Language |
+------------------------------------------+
3 rows in set (0.00 sec)
Following is the query to quickly search for a string in a MySQL database. Here, we are searching for string “language” −
mysql> select * from DemoTable1554 where match(Title) against('language' in boolean mode);
This will produce the following output −
+------------------------------------------+
| Title                                    |
+------------------------------------------+
| Adam Smith is working on Java language   |
| John smith is working on Python Language |
+------------------------------------------+
2 rows in set (0.00 sec)
How to Convert .rpm package to .deb using alien Package Converter? - GeeksforGeeks

02 Nov, 2020
Most of the time there are packages (in repositories and GitHub) that are ready to use. But sometimes packages are not available in binaries (ready to install on the go) we have to download the source code and build from scratch. This is not an issue if you have time but for increasing Productivity. 
Here is where Alien (package converter) comes into place. If an application like Zenmap (Nmap should be pre-installed) is readily available in .rpm form instead of .deb. We can convert that .rpm package to .deb on the go using alien, and we could install zenmap directly.
Installing the alien tool
Alien is available in most of the repositories but, In case you don’t have it you can find and install it from alien-git here. Here is the list of commands to be executed for the installation of the tool.
For Kali or other Debian based Distribution:
sudo apt-get install alien 

To open the alien command manual page
1. Locate or download .rpm package of the software to be installed (Package used as an example can be downloaded from here).
2. Click on zenmap-7.91-1.noarch.rpm to get the rpm file(Skip this step if you are using your own rpm file)
3. The next step is to Use Alien to convert .rpm to .deb. Switch to the directory in which the package is located using the cd command.
alien --to-deb [file_name.rpm]

Note:-  Replace file_name.rmp with the respective rmp file.
4. Then it can be seen that the Debian file is created for the package
5. Install the package using the following commands
chmod +x [file_name.deb]
sudo apt-get install ./[file_name.deb]

Note:- Replace file_name.deb with the respective deb file.
6. That’s it our application got installed and could be launched from the terminal using the application name
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Array Basics in Shell Scripting | Set 1
How to join list of lists in python?

There are different ways to flatten a list of lists. Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.
L1=[[1,2],[3,4,5],[6,7,8,9]]
flat=[]
for i in L1:
  for j in i:
    flat.append(j)
print (flat)
Another method is to use a generator function to yield an iterator and convert it to a list
def flatten(list):
  for i in list:
    for j in i:
      yield j


L1=[[1,2,3],[4,5],[6,7,8,9]]
flat=flatten(L1)
print (list(flat))
Most compact method is to use chain() method from itertools module
L1=[[1,2,3],[4,5],[6,7,8,9]]
import itertools
flat=itertools.chain.from_iterable(L1)
print (list(flat))
All the above codes produce a flattened list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
How to use column with colours to change the colour of points using ggplot2 in R?

If we have a colour column in an R data frame and we want to change the point colours in ggplot2 using that column then colour argument will be used. For example, if we have a data frame called df that contains three columns say x, y, and color then the scatterplot between x and y with the colour of points using color column can be created by using the command ggplot(df,aes(x,y))+geom_point(colour=df$color)
Consider the below data frame −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> col<-sample(c("blue","red","green"),20,replace=T)
> df<-data.frame(x,y,col)
> df
             x          y   col
1   1.92321342  1.2183501 green
2   0.73342537 -0.6477975 green
3  -1.00606105 -1.2697246   red
4   0.73504980 -0.5593899   red
5  -0.39976314  0.1185340 green
6  -1.15940677 -0.7219141 green
7   1.81313147 -2.1268507  blue
8  -0.47278398 -1.0414317  blue
9  -1.33914777 -0.2756125  blue
10  0.05742411  1.4000877  blue
11 -0.13134085 -0.8916141 green
12  0.87743445 -0.4291995 green
13  0.55897765  0.2815842  blue
14  0.51374603 -1.0219416  blue
15  0.27037163  0.7545370  blue
16  0.02100292  0.2674216 green
17  0.73620835  0.6262369  blue
18 -0.11391829 -0.7456059 green
19 -0.64697468  0.6713425   red
20  0.37972640  3.7717047   red
Loading ggplot2 package and creating scatterplot between x and y −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Creating the scatterplot between x and y with colour of points in col column −
> ggplot(df,aes(x,y))+geom_point(colour=df$col)
Data objects and Structures

Data structures are defined as special classes implemented to hold data only, i.e. Pure models, e.g. Car, Kid, Animal, Event, Employee, Company, Customer ...etc. Those data are generally declared or considered as instance variables in other classes beginnings.
The methods of this class should not perform any real significant work, otherwise the data structure class is not a data structure anymore!
So mainly, the methods are getters and setters (i.e. accessors and mutators), generally because the instance variables are treated as private. There is alternative opinion: that Data structure variables should be public, and can be accessed directly from the instance of the class, but it is debatable that the private variables concept is better.
In that context, the data structure class, reveals or exposes its data (variables) and have no meaningful (significant) methods or functions.
A normal class (Called Object here), like MainActivity, ListAdapter, Calculator, Iterator, conceals their data, and reveals or exposes their methods that work on those data.
So, we have two approaches to solve the problem in hand, i.e. implement a data Structure in its purest form, while building another Object class to build operations on their data, OR, we can make the model classes as Object classes, that conceals their data while exposes their methods, like in the following example
public class Square {
   public Point topLeft1;
   public double side1;
}
public class Rectangle {
   public Point topLeft1;
   public double height1;
   public double width1;
}
public class Circle {
   public Point center1;
   public double radius1;
}
public class Geometry {
   public final double PI = 3.141592653589793;
   public double area(Object shape) throws NoSuchShapeException {
   if (shape instanceof Square) {
      Square s = (Square)shape;
      return s.side1 x s.side1;
   }else if (shape instanceof Rectangle) {
      Rectangle r = (Rectangle)shape;
      return r.height1 x r.width1;
   }else if (shape instanceof Circle) {
      Circle c = (Circle)shape;
      return PI x c.radius1 x c.radius1; }
      throw new NoSuchShapeException(); }
}
In this solution the shapes are treated as data structures, while Geometry class is treated as Object.
Advantage − If we require adding more methods we will add them only in the Geometry class (this is the time this solution should be implemented).
Disadvantage − If we require to add more Data Structures (i.e. more shapes), we will have to change all your methods in the Geometry class.
Objects expose behaviour and conceal data. This makes it simple to add new kinds of objects without changing existing behaviours. It also makes it difficult to add new behaviours to existing objects.
Data structures reveal or expose data and have no significant behaviour. This makes it simple to add new behaviours to existing data structures but makes it hard to add new data structures to existing functions.
Advanced master theorem for divide and conquer recurrences

Divide and conquer is an algorithm that works on the paradigm based on recursively branching problem into multiple sub-problems of similar type that can be solved easily.
Let’s take an example to learn more about the divide and conquer technique −
function recursive(input x size n)
   if(n < k)
      Divide the input into m subproblems of size n/p.
      and call f recursively of each sub problem
   else
      Solve x and return
Combine the results of all subproblems and return the solution to the original problem.
Explanation − In the above problem, the problem set is to be subdivided into smaller subproblems that can be solved easily.
Masters Theorem for divide and conquer is an analysis theorem that can be used to determine a big-0 value for recursive relation algorithms. It is used to find the time required by the algorithm and represent it in asymptotic notation form.
Example of runtime value of the problem in the above example −
T(n) = f(n) + m.T(n/p)
For most of the recursive algorithm, you will be able to find the Time complexity For the algorithm using the master's theorem, but there are some cases master's theorem may not be applicable. These are the cases in which the master's theorem is not applicable. When the problem T(n) is not monotone, for example, T(n) = sin n. Problem function f(n) is not a polynomial.
As the master theorem to find time complexity is not hot efficient in these cases, and advanced master theorem for recursive recurrence was designed. It is design to handle recurrence problem of the form −
T(n) = aT(n/b) + ø((n^k)logpn)
Where n is the size of the problem.
a = number of subproblems in recursion, a > 0
n/b = size of each subproblem b > 1, k >= 0 and p is a real number.
For solving this type of problem, we will use the following solutions,
If a>bk, then T(n) = ∅ (nlogba)
If a = bk, thenIf p> -1, then T(n) = ∅(nlogba logp+1n)If p = -1, then T(n) = ∅(nlogba loglogn)If p < -1, then T(n) = ∅(nlogba)
If p> -1, then T(n) = ∅(nlogba logp+1n)
If p = -1, then T(n) = ∅(nlogba loglogn)
If p < -1, then T(n) = ∅(nlogba)
If a<bk , thenIf p> = 0, then T(n)= ∅(nklogpn)If p< 0, then T(n) = ∅(nk)
If p> = 0, then T(n)= ∅(nklogpn)
If p< 0, then T(n) = ∅(nk)
Using the advanced master algorithm, we will calculate the complexity of some algorithms −
Binary search − t(n) = θ(logn)
Merge sort − T(n) = θ(nlogn)
Fade In Right Animation Effect with CSS

To implement Fade In Right Animation Effect on an image with CSS, you can try to run the following code −
Live Demo
<html>
   <head>

      <style>

         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }

         @-webkit-keyframes fadeInRight {
            0% {
               opacity: 0;
               -webkit-transform: translateX(20px);
            }
            100% {
               opacity: 1;
               -webkit-transform: translateX(0);
            }
         }
         @keyframes fadeInRight {
            0% {
               opacity: 0;
               transform: translateX(20px);
            }
            100% {
               opacity: 1;
               transform: translateX(0);
            }
         }

         .fadeInRight {
            -webkit-animation-name: fadeInRight;
            animation-name: fadeInRight;
         }
      </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeInRight"></div>
      <button onclick="myFunction()">Reload page</button>

      <script>
         function myFunction() {
            location.reload();
         }
      </script>

   </body>
</html>
Swing Examples - Show Standard Progress Bar

Following example showcase how to show a standard Progress bar in a Java Swing application.
We are using the following APIs.
JProgressBar − To create a progress bar field.
JProgressBar − To create a progress bar field.
JProgressBar.setValue − To set the progress in progress bar.
JProgressBar.setValue − To set the progress in progress bar.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingTester {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   
   public SwingTester(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingTester  swingControlDemo = new SwingTester();      
      SwingTester.showProgressBarDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private JProgressBar progressBar;
   private Task task;
   private JButton startButton;
   private JTextArea outputTextArea;
   
   private void showProgressBarDemo(){
      headerLabel.setText("Control in action: JProgressBar"); 
      progressBar = new JProgressBar(0, 100);
      progressBar.setValue(0);
      progressBar.setStringPainted(true);
      startButton = new JButton("Start");
      outputTextArea = new JTextArea("",5,20);
      JScrollPane scrollPane = new JScrollPane(outputTextArea);    
      
      startButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            task = new Task();                
            task.start();
         }
      });
      controlPanel.add(startButton);
      controlPanel.add(progressBar);
      controlPanel.add(scrollPane);
      mainFrame.setVisible(true);  
   }
   private class Task extends Thread {    
      public Task(){
      }
      public void run(){
         for(int i =0; i<= 100; i+=10){
            final int progress = i;
            
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  progressBar.setValue(progress);
                  outputTextArea.setText(outputTextArea.getText() 
                     + String.format("Completed %d%% of task.\n", progress));
               }
            });
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {}
         }
      }
   }   
}
Verify the following output.
 Print
 Add Notes
 Bookmark this page
PHP Basics of Class and Object

Class is a user defined data type in PHP. In order to define a new class, PHP provides a keyword class, which is followed by a name. Any label that is valid as per PHP's naming convention (excluding PHP's reserved words) can be used as name of class. Constituents of class are defined in curly bracket that follows name of class
class myclass{
   //
}
Class may contain constants, variables or properties and methods - which are similar to functions
This example shows how a Class is defined
<?php
class myclass{
   const MYCONSTANT=100;
   public $var1="Hello";
   function dispvar(){
      echo $this->var1;
   }
}
?>
Function defined inside class is called method. Calling object's context is available inside a method with a pseudo-variable $this. If method is defined as static, it is accessed with name of class. Calling a non-static method statically has been deprecated in PHP 7
The new operator declares a new object of given class. ame of class followed by paentheses should be mentioned in front of new keyword. An uninitialized object (or with default values to properties) is created if there are no arguments inside parentheses. If class provides definition of constructor with parameters, matching number of arguments must be given. Class must be defined before creating instance (or object)
 Live Demo
<?php
class myclass{
   const MYCONSTANT=100;
   public $var1="Hello";
   function dispvar(){
      echo $this->var1;
   }
}
$obj=new myclass();
$obj->dispvar();
?>
This will produce following result. −
Hello
Data Analysis with Unix - Part 1 - GeeksforGeeks

14 Jul, 2019
To understand how to work with Unix, data – Weather Dataset is used.Weather sensors gather information consistently at numerous areas over the globe and assemble an enormous volume of log information, which is a decent possibility for investigation with MapReduce in light of the fact that is required to process every one of the information, and the information is record-oriented and semi-organized.
The information utilized is from the National Climatic Data Center, or NCDC. The information is put away utilizing a line-arranged ASCII group, in which each line is a record. The organization underpins a rich arrangement of meteorological components, huge numbers of which are discretionary or with variable information lengths. For straightforwardness, centre around the fundamental components, for example, temperature, which is constantly present and are of fixed width.Structure of NCDC record
0057
332130       # USAF weather station identifier
99999        # WBAN weather station identifier
19500101     # observation date
0300         # observation time
4 
+51317       # latitude ( degrees x 1000)
+028783      # longitude (degrees x 1000)
FM-12
+0171        # elevation (meters)
99999
V020
320          # wind direction (degrees)
1            # quality code
N 0072
1 00450      # sky ceiling height (meters)
1            # quality code
C
N 
010000       # visibility distance (meters)
1            # quality code
N
9 
-0128       # air temperature (degrees Celsius x 10)
1           # quality code
-0139       # dew point temperature (degrees Celsius x 10)
1           # quality code
10268       # atmospheric pressure (hectopascals x 10)
1           # quality code
Note – Fields are packed into one line with no delimiters in the actual file we’ll be working on. Datafiles are sorted out by date and climate station. There is an index for every year from 1901 to 2001, each containing a gzipped record for each climate station with its readings for that year.
First entries for 1995 :
% ls raw/1990 | head
010010-99999-1995.gz
010014-99999-1995.gz
010015-99999-1995.gz
010016-99999-1995.gz
010017-99999-1995.gz
010030-99999-1995.gz
010040-99999-1995.gz
010080-99999-1995.gz
010100-99999-1995.gz
010150-99999-1995.gz
There are countless climate stations, so the entire dataset is comprised of a huge number of generally little documents. It’s commonly simpler and increasingly proficient to process a more modest number of generally enormous records, so the information was preprocessed with the goal that every year’s readings were linked into a solitary record.
Hadoop
Linux-Unix
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
Conditional Statements | Shell Script
Mutex lock for Linux Thread Synchronization
curl command in Linux with Examples
Named Pipe or FIFO with example C program
echo command in Linux with Examples
Thread functions in C/C++
touch command in Linux with Examples
Convert PDF to CSV using Python

Python is well known for its huge library of packages. With the help of libraries, we will see how to convert a PDF to a CSV file. A CSV file is nothing but a collection of data, framed along with a set of rows and columns. There are various packages available in the Python library to convert PDF to CSV, but we will use the Tabula-py module. The major part of tabula-py is written in Java that first reads the PDF document and converts the Python DataFrame into a JSON object.
In order to work with tabula-py, we must have Java preinstalled in our system. To convert the PDF file to CSV, we will follow these steps −
First, Install the required package by typing pip install tabula-py in the command shell.
First, Install the required package by typing pip install tabula-py in the command shell.
Now, read the file using read_pdf("file location", pages=number) function. This will return the DataFrame.
Now, read the file using read_pdf("file location", pages=number) function. This will return the DataFrame.
Convert the DataFrame into an Excel file using tabula.convert_into(‘pdf-filename’, ‘name_this_file.csv’,output_format= "csv", pages= "all"). It generally exports the pdf file into an excel file.
Convert the DataFrame into an Excel file using tabula.convert_into(‘pdf-filename’, ‘name_this_file.csv’,output_format= "csv", pages= "all"). It generally exports the pdf file into an excel file.
In this example, we have used IPL Match Schedule Document to convert it into an Excel file.
# Import the required Module
import tabula
# Read a PDF File
df = tabula.read_pdf("IPLmatch.pdf", pages='all')[0]
# convert PDF into CSV
tabula.convert_into("IPLmatch.pdf", "iplmatch.csv", output_format="csv", pages='all')
print(df)
Running the above code will convert the PDF file into an Excel (CSV) file.