code-rag-bench/online-tutorials huggingface dataset:
Python | shutil.unpack_archive() method

08 Nov, 2021
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. 
Syntax: shutil.unpack_archive(filename [, extract_dir [, format]])Parameter: filename: A path-like object representing the full path of archived file. A path-like object is either a string or bytes object representing a path. extract_dir (optional): A path-like object representing the path of the target directory where the archive is unpacked. A path-like object is either a string or bytes object representing a path. This is an optional parameter and if not provided the current working directory is used as target directory. formats (optional): A string representing an archive format. The value of format can be any one of “zip”, “tar”, “gztar”, “bztar”, or “xztar” or any other registered unpacking format. This is also an optional parameter and if not provided, the extension of archived file name is used as format. An unpacker must be registered for this extension otherwise ‘ValueError’ exception will be raised. Return Type: This method does not return any value. 
Code #1: Use of shutil.unpack_archive() method to unpack an archive file  
Python3
# Python program to explain shutil.unpack_archive() method  # importing shutil moduleimport shutil # Full path of# the archive filefilename = "/home/User/Downloads/file.zip" # Target directoryextract_dir = "/home/ihritik/Documents" # Format of archive filearchive_format = "zip" # Unpack the archive fileshutil.unpack_archive(filename, extract_dir, archive_format)print("Archive file unpacked successfully.")
Archive file unpacked successfully.
 
Code #2: Use of shutil.unpack_archive() method to unpack an archive file  
Python3
# Python program to explain shutil.unpack_archive() method  # importing shutil moduleimport shutil # Full path of# the archive filefilename = "/home/User/Downloads/file.zip"  # Unpack the archived fileshutil.unpack_archive(filename)print("Archive file unpacked successfully.") # As extract_dir and format parameters# are not provided So,# shutil.unpack_archive() method will# unpack the archive file in# current working directory and extension# of the archive filename i.e zip# will be taken as format to unpack   
Archive file unpacked successfully.
 
sooda367
prachisoda1234
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Conditional select between dates in MySQL for maximum and minimum values of price set in a table?

You need to use CASE statement to conditional select between dates to find the minimum and maximum price. Wrap up the CASE statement with aggregate function MIN() and MAX(). The syntax is as follows:
SELECT
MIN(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName,

MAX(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table ConditionalSelect
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> StartDate datetime,
   -> EndDate datetime,
   -> LowerPrice int,
   -> HigherPrice int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-01-02','2019-04-02',5,10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-02','2019-04-20',0,20);
Query OK, 1 row affected (0.17 sec)
mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-03','2019-04-21',0,30);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from ConditionalSelect;
The following is the output:
+----+---------------------+---------------------+------------+-------------+
| Id | StartDate           | EndDate             | LowerPrice | HigherPrice |
+----+---------------------+---------------------+------------+-------------+
|  1 | 2019-01-02 00:00:00 | 2019-04-02 00:00:00 |          5 |          10 |
|  2 | 2019-04-02 00:00:00 | 2019-04-20 00:00:00 |          0 |          20 |
|  3 | 2019-04-03 00:00:00 | 2019-04-21 00:00:00 |          0 |          30 |
+----+---------------------+---------------------+------------+-------------+
3 rows in set (0.00 sec)
Here is the query to select min and max price between dates:
mysql> SELECT
   -> MIN(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MinimumValue,
   -> MAX(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MaximumValue
   -> from ConditionalSelect;
The following is the output:
+--------------+--------------+
| MinimumValue | MaximumValue |
+--------------+--------------+
|            5 |           30 |
+--------------+--------------+
1 row in set (0.00 sec)
Machine Learning - Bagged Decision Tree

As we know that bagging ensemble methods work well with the algorithms that have high variance and, in this concern, the best one is decision tree algorithm. In the following Python recipe, we are going to build bagged decision tree ensemble model by using BaggingClassifier function of sklearn with DecisionTreeClasifier (a classification & regression trees algorithm) on Pima Indians diabetes dataset.
First, import the required packages as follows −
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
Now, we need to load the Pima diabetes dataset as we did in the previous examples −
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names=headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
Next, give the input for 10-fold cross validation as follows −
seed = 7
kfold = KFold(n_splits = 10, random_state = seed)
cart = DecisionTreeClassifier()
We need to provide the number of trees we are going to build. Here we are building 150 trees −
num_trees = 150

Next, build the model with the help of following script −
model = BaggingClassifier(base_estimator = cart, n_estimators = num_trees, random_state = seed)

Calculate and print the result as follows −
results = cross_val_score(model, X, Y, cv=kfold)
print(results.mean())

Output
0.7733766233766234

The output above shows that we got around 77% accuracy of our bagged decision tree classifier model.

    168 Lectures 
     13.5 hours 

 Er. Himanshu Vasishta

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions

    91 Lectures 
     10 hours 

 Abhilash Nelson

    54 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     4 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Python | os.WIFSTOPPED() method - GeeksforGeeks

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.WIFSTOPPED() method in Python is used to check whether a process has been stopped. This method takes process status code as returned by os.wait(), os.system() or os.waitpid() method as a parameter and returns True if the process has been stopped, otherwise returns False.
Syntax: os.WIFSTOPPED(status)
Parameter:status: This parameter takes process status code (an integer value) as returned by os.system(), os.wait() or os.waitpid() method.
Return type: This method returns a boolean value of class ‘bool’. This method returns True if the process has been stopped, otherwise returns False.
Code: Use of os.WIFSTOPPED() method
# Python program to explain os.WIFSTOPPED() method   # importing os and signal module  import os, signal  # Create a child process# using os.fork() method pid = os.fork()    # pid greater than 0# indicates the parent process if pid :          # Send signal 'SIGSTOP'    # to child process    # using os.kill() method    # signal will cause the child    # process to stop    os.kill(pid, signal.SIGSTOP)              # Get the child's pid and     # status code using    # os.waitpid() method    info = os.waitpid(pid, os.WSTOPPED)      # info is a tuple    # info[0] represents child's pid    # info[1] represents exit status code      print("\nIn parent process")          # Check whether the child process    # has been stopped or not        # using os.WIFSTOPPED() method    isStopped = os.WIFSTOPPED(info[1])       print("Has child process been stopped?")    print(isStopped)    else :    print("In Child process")    print("Process ID:", os.getpid())    print("Hello ! Geeks")     
In Child process
Process ID: 10224
Hello! Geeks

In parent process
Has child process been stopped?
True

References: https://docs.python.org/3/library/os.html#os.WIFSTOPPED
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Decrease a row value by 1 in MySQL?

You can increase and decrease row value by 1 in MySQL using UPDATE command. The syntax is as follows −
UPDATE yourTableName set yourColumnName = yourColumnName-1 where condition;
Let us create a table to decrease row value by 1. The following is the query −
mysql> create table IncrementAndDecrementValue
   −> (
   −> UserId int,
   −> UserScores int
   −> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into IncrementAndDecrementValue values(101,20000);
Query OK, 1 row affected (0.13 sec)

mysql> insert into IncrementAndDecrementValue values(102,30000);
Query OK, 1 row affected (0.20 sec)

mysql> insert into IncrementAndDecrementValue values(103,40000);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from IncrementAndDecrementValue;
The following is the output;
+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 | 20000      |
|    102 | 30000      |
|    103 | 40000      |
+--------+------------+
3 rows in set (0.00 sec)
Here is the query to decrease the UserScores value by 1 with where condition.
mysql> update IncrementAndDecrementValue set UserScores = UserScores-1 where UserId = 103;
Query OK, 1 row affected (0.41 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check whether the value is updated or not. The query is as follows −
mysql> select *from IncrementAndDecrementValue;
The following is the output displaying that we have successfully decremented a row value −
+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 | 20000      |
|    102 | 30000      |
|    103 | 39999      |
+--------+------------+
3 rows in set (0.00 sec)
How can I get enum possible values in a MySQL database using PHP?

You can get the enum possible values in a MySQL database with the help of INFORMATION_SCHEMA.COLUMNS table. The syntax is as follows −
SELECT
   COLUMN_TYPE AS anyAliasName
FROM
   INFORMATION_SCHEMA.COLUMNS
WHERE
   TABLE_SCHEMA = ‘yourDatabaseName’ AND TABLE_NAME = 'yourTableName' AND COLUMN_NAME = 'yourEnumColumnName';
To understand the above syntax, let us create a table with an ENUM data type. The query to create a table is as follows −
mysql> create table EnumDemo
-> (
-> Id int,
-> Color ENUM('RED','GREEN','BLUE','BLACK','ORANGE')
-> );
Query OK, 0 rows affected (0.66 sec)
Here the table ‘EnumDemo’ is present in the ‘sample’ database. Now you can implement the above syntax to get the all possible enum values from a column.
The query is as follows −
mysql> SELECT
-> COLUMN_TYPE as AllPossibleEnumValues
-> FROM
-> INFORMATION_SCHEMA.COLUMNS
-> WHERE
-> TABLE_SCHEMA = 'sample' AND TABLE_NAME = 'EnumDemo' AND COLUMN_NAME = 'Color';
+---------------------------------------------+
| AllPossibleEnumValues                       |
+---------------------------------------------+
| enum('RED','GREEN','BLUE','BLACK','ORANGE') |
+---------------------------------------------+
1 row in set (0.00 sec)
How to make JOptionPane to handle Yes, No and Closed buttons in Java?

For this, create JOptionPane.QUESTION_MESSAGE and with the user action display individual messages, for example −
int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?", "Hobbies",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION);
if (res == JOptionPane.YES_OPTION) {
   System.out.println("Selected Yes!");
}
Above, we have displayed a message on console if the user will selects YES button. The following is an example to make JOptionPane to handle Yes, No and Closed buttons −
package my;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(String args[]) {
      int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?","Hobbies",
         JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
         new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION);
      if (res == JOptionPane.YES_OPTION) {
         System.out.println("Selected Yes!");
      } else if (res == JOptionPane.NO_OPTION) {
         System.out.println("Selected No!");
      } else if (res == JOptionPane.CLOSED_OPTION) {
         System.out.println("Window closed without selecting!");
      }
   }
}
Let’s say you selected “Yes” above. The following will be visible in the Console in that case −
Let’s say you selected “No” above. The following will be visible in the Console in that case −
Let’s say you pressed “Cancel” (close) above. The following will be visible in the Console in that case −
Python | Numpy matrix.itemset() - GeeksforGeeks

15 Apr, 2019
With the help of Numpy matrix.itemset() method, we can set the items in a given matrix by just providing index number and item.
Syntax : matrix.itemset(index, item)
Return : Return new matrix having item
Example #1 :In this example we can see that we are able to set the item with the help of method matrix.itemset() by providing index number and item.
# import the important module in pythonimport numpy as np          # make matrix with numpygfg = np.matrix('[6, 1; 2, 3]')          # applying matrix.itemset() methodgfg.itemset((1, 0), 5)    print(gfg)
[[6 1]
 [5 3]]

Example #2 :
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')          # applying matrix.itemset() methodgfg.itemset((2, 0), 10)    print(gfg)
[[ 1  2  3]
 [ 4  5  6]
 [10  8  9]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
sum() function in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Print lists in Python (4 Different Ways)
How to hide action bar in android?

This example demonstrate about How to hide action bar in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   android:background="#000"
   tools:context=".MainActivity">
   <DigitalClock android:id="@+id/digital"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="30sp"
      android:textColor="#FFF"
      android:layout_centerHorizontal="true"/>
</LinearLayout>
In the above code, we have taken the digital clock view to show a clock.
Step 3− Add the following code to java/MainActivity.xml
package com.example.myapplication;

import android.annotation.TargetApi;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {
   @TargetApi(Build.VERSION_CODES.LOLLIPOP)
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      getSupportActionBar().hide();
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
Code Generation and Optimization - GeeksforGeeks

21 Jan, 2014
In the following code:

a = b * c + g;
d = b * c * e;

it may be worth transforming the code to:

tmp = b * c;
a = tmp + g;
d = tmp * e;

4*j is common subexpression elimination so B is true.

5*i can be moved out of inner loop so can be i%2. 
Means, A is true as we have loop invariant computation.

Next, 4*j as well as 5*i can be replaced with a = - 4;
before j loop then a = a + 4; where 4*j is computed,
likewise for 5*i. C is true as there is scope of strength 
reduction. 

By choice elimination, we have D.
1. i = 1
2. j = 1
3. t1 = 5 * i
4. t2 = t1 + j
5. t3 = 4 * t2
6. t4 = t3
7. a[t4] = –1
8. j = j + 1
9. if j <= 5 goto(3)
10. i = i + 1
11. if i < 5 goto(2) 
x = u - t;
y = x * v;
x = y + w;
y = t - z;
y = x * y; 
x = u - t;
x = y + w;

y = x * v;
y = t - z;
y = x * y 
x1 = u - t;
y1 = x1 * v;
x2 = y1 + w;
y2 = t - z;
y3 = x2 * y2;
S → n
B → BbB 
S → L.L   { S.val=L1.val  + L2.val / 2^L2.nb  }
S  → L     {  S.val = L.val } 
L → LB     {  L.val =  2 *  L.val  + B.val   ,  L.nb = L.nb +  B.nb } 
L →  B     {  L.val = B.val   ,  L.nb = B.nb } 
B → 0     {  B.val = 0  ,  B.nb = 1 } 
B  →  1   {  B.val = 1  ,  B.nb = 1 }  
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
How to Install Flutter on Visual Studio Code?
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Show Images on Click using HTML ?
What is the difference between position:sticky and position:fixed in CSS ?
Microsoft Interview Experience for Internship (Via Engage)
Retrofit with Kotlin Coroutine in Android
Difference between sh and bash
Plot a lineplot with Seaborn – Python Pandas

Lineplot in Seaborn is used to draw a line plot with possibility of several semantic groupings. The seaborn.lineplot() is used for this.
Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv
At first, import the required 3 libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")
print("\nReading the CSV file...\n",dataFrame)

# Age in kgs
x = dataFrame['Age']

# Height in Inches
y = dataFrame['Height']

# plot lineplot with Age and Height
sb.lineplot(x,y)
plt.ylabel("Height (inches)")
plt.show()
This will produce the following output −
AWK - Assignment Operators

AWK supports the following assignment operators −
It is represented by =. The following example demonstrates this −
[jerry]$ awk 'BEGIN { name = "Jerry"; print "My name is", name }'
On executing this code, you get the following result −
My name is Jerry

It is represented by +=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 10; cnt += 10; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 20

In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator increments its value by 10.
It is represented by -=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 100; cnt -= 10; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 90

In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator decrements its value by 10.
It is represented by *=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 10; cnt *= 10; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 100

In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator multiplies its value by 10.
It is represented by /=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 100; cnt /= 5; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 20

In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator divides it by 5.
It is represented by %=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 100; cnt %= 8; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 4

It is represented by ^=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 2; cnt ^= 4; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 16

The above example raises the value of cnt by 4.
It is represented by **=. The following example demonstrates this −
[jerry]$ awk 'BEGIN { cnt = 2; cnt **= 4; print "Counter =", cnt }'
On executing this code, you get the following result −
Counter = 16

This example also raises the value of cnt by 4.
 Print
 Add Notes
 Bookmark this page
Python 3 - Number abs() Method

The abs() method returns the absolute value of x i.e. the positive distance between x and zero.
Following is the syntax for abs() method −
abs( x )

x − This is a numeric expression.
This method returns the absolute value of x.
The following example shows the usage of the abs() method.
#!/usr/bin/python3

print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))
When we run the above program, it produces the following result −
abs(-45) :  45
abs(100.12) :  100.12


    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
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a system with byte-addressable memory, 32 bit logical addresses, 4 kilobyte page size and page table entries of 4 bytes each. The size of the page table in the system in megabytes is ___________(A) 2(B) 4(C) 8(D) 16Answer: (B)Explanation:
Number of entries in page table = 232 / 4Kbyte  
                                = 232 / 212 
                                        = 220

Size of page table = (No. page table entries)*(Size of an entry) 
                   = 220 * 4 bytes 
                   = 222 
                   = 4 Megabytes

Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How can we insert current date and time automatically on inserting values in other columns in MySQL?

In MySQL, we can insert the current date and time automatically to a column on inserting the values in another column by declaring that column as DEFAULT CURRENT_TIMESTAMP.
mysql> Create table testing
   -> (
   -> StudentName varchar(20) NOT NULL,
   -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
   -> );
Query OK, 0 rows affected (0.49 sec)
Above query will create a table ‘testing’ with a column named StudentName and other column named ‘RegDate’ declared as DEFAULT CURRENT_TIMESTAMP. Now, on inserting the values i.e. names in StudentName column, the current date and time will be inserted in the other column automatically.
mysql> Insert into testing(StudentName) values ('Ram');
Query OK, 1 row affected (0.14 sec)

mysql> Insert into testing(StudentName) values ('Shyam');
Query OK, 1 row affected (0.06 sec)

mysql> Select * from testing;
+-------------+---------------------+
| StudentName | RegDate             |
+-------------+---------------------+
| Ram         | 2017-10-28 21:24:24 |
| Shyam       | 2017-10-28 21:24:30 |
+-------------+---------------------+
2 rows in set (0.02 sec)

mysql> Insert into testing(StudentName) values ('Mohan');
Query OK, 1 row affected (0.06 sec)

mysql> Select * from testing;
+-------------+---------------------+
| StudentName | RegDate             |
+-------------+---------------------+
| Ram         | 2017-10-28 21:24:24 |
| Shyam       | 2017-10-28 21:24:30 |
| Mohan       | 2017-10-28 21:24:47 |
+-------------+---------------------+
3 rows in set (0.00 sec)
From the above queries, we can see that on inserting the values in StudentName, the date and time is also inserting automatically.
With the help of the above concept, we can also know that exactly on what date and time the values in other column inserted.
How to print without newline in Python?

09 Aug, 2021
Generally, people switching from C/C++ to Python wonder how to print two or more variables or statements without going into a new line in python. Since the python print() function by default ends with a newline. Python has a predefined format if you use print(a_variable) then it will go to the next line automatically.  
For example: 
Python3
print("geeks")print("geeksforgeeks")
Will result in this: 
geeks
geeksforgeeks
But sometimes it may happen that we don’t want to go to the next line but want to print on the same line. So what we can do?  
For Example: 
Input : print("geeks") print("geeksforgeeks")
Output : geeks geeksforgeeks

Input : a = [1, 2, 3, 4]
Output : 1 2 3 4 
The solution discussed here is totally dependent on the python version you are using.  
python
# Python 2 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print("geeks"),print("geeksforgeeks") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4):    print(a[i]),
Output: 
geeks geeksforgeeks
1 2 3 4
python3
# Python 3 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print("geeks", end =" ")print("geeksforgeeks") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4):    print(a[i], end =" ")
Output: 
geeks geeksforgeeks
1 2 3 4
Python3
# Print without newline in Python 3.x without using for loop l=[1,2,3,4,5,6] # using * symbol prints the list# elements in a single lineprint(*l) #This code is contributed by anuragsingh1022
Output:
1 2 3 4 5 6
anuragsingh1022
python-basics
Python
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python | Pandas dataframe.rdiv()

22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.rdiv() function compute Floating division of dataframe and other, element-wise (binary operator rtruediv). Other object could be a scalar, pandas series or pandas dataframe. This function is essentially same as doing other / dataframe but with support to substitute a fill_value for missing data in one of the inputs.
Syntax: DataFrame.rdiv(other, axis=’columns’, level=None, fill_value=None)
Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelnumeric_only : Include only float, int, boolean data. Valid only for DataFrame or Panel objectsfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing
Returns : result : DataFrame
Example #1: Use rdiv() function to divide a series with a dataframe element-wise
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, 2, 4, 3, 4],                    "C":[2, 2, 7, 3, 4],                   "D":[4, 3, 6, 12, 7]})  # Print the dataframedf
Lets create a series
# importing pandas as pdimport pandas as pd  # Create a seriessr = pd.Series([5, 10, 15, 20], index =["A", "B", "C", "D"])  # Print the seriessr
Let’s use the dataframe.rdiv() function to divide the series with a dataframe
# perform division of series with # dataframe element-wise over the column axisdf.rdiv(sr, axis = 1)
Output : Example #2: Use rdiv() function to divide one dataframe with other which contains NaN value.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2],                    "B":[3, 2, 4, 3, 4],                     "C":[2, 2, 7, 3, 4],                    "D":[4, 3, 6, 12, 7]})  # Creating the second dataframedf2 = pd.DataFrame({"A":[14, 5, None, 4, 12],                    "B":[7, 6, 4, 5, None],                    "C":[2, 11, 4, 3, 6],                     "D":[4, None, 6, 2, 4]})  # divide df2 by df1 element-wise# Fill all the missing values by 100df1.rdiv(df2, fill_value = 100)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
PostgreSQL – RENAME COLUMN

28 Aug, 2020
In PostgreSQL, the RENAME COLUMN clause is used with the ALTER TABLE statement to rename one or more columns in a table.
Syntax:
ALTER TABLE table_name 
RENAME COLUMN column_name TO new_column_name;
Let’s analyze t5he above syntax:
First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause.
Second, provide the column name after the RENAME COLUMN clause.
Third, give the new column name after the TO keyword.
Let’s take some examples of using the ALTER TABLE RENAME COLUMN to get a better understanding.
Example 1:First, let’s create two new tables namely customers and customer_groups using the below statement:
CREATE TABLE customer_groups (
    id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

CREATE TABLE customers (
    id serial PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone VARCHAR NOT NULL,
    email VARCHAR,
    group_id INT,
    FOREIGN KEY (group_id) REFERENCES customer_groups (id)
);
Then we create a new view named customer_data based on the customers and customer_groups tables as follows:
CREATE VIEW customer_data 
AS SELECT
    c.id,
    c.name,
    g.name customer_group
FROM
    customers c
INNER JOIN customer_groups g ON g.id = c.group_id;
Now we will use the ALTER TABLE RENAME COLUMN statement to rename the email column of the customers table to contact_email:
ALTER TABLE customers 
RENAME COLUMN email TO contact_email;
Now verify the changes made using the below statement:
SELECT * FROM customers;
Output:
Example 2:These statements rename two columns name and phone of the customers table to customer_name and contact_phone respectively:
ALTER TABLE customers 
RENAME COLUMN name TO customer_name;

ALTER TABLE customers
RENAME COLUMN phone TO contact_phone;
Now verify the changes made using the below statement:
SELECT * FROM customers;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column
PostgreSQL - SELECT
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL – Create Auto-increment Column using SERIAL

28 Aug, 2020
In PostgreSQL, a sequence is a special kind of database object that generates a sequence of integers. A sequence is often used as the primary key column in a table.The SERIAL pseudo-type can be used to generate a sequence while creating a new table.
Syntax:
CREATE TABLE table_name(
    id SERIAL
);
In the above syntax by setting the SERIAL pseudo-type to the id column, PostgreSQL performs the following:
First, create a sequence object and set the next value generated by the sequence as the default value for the column.
Second, add a NOT NULL constraint to the id column because a sequence always generates an integer, which is a non-null value.
Third, assign the owner of the sequence to the id column; as a result, the sequence object is deleted when the id column or table is dropped.
The above syntax is equivalent to the below statement:
CREATE SEQUENCE table_name_id_seq;

CREATE TABLE table_name (
    id integer NOT NULL DEFAULT nextval('table_name_id_seq')
);

ALTER SEQUENCE table_name_id_seq
OWNED BY table_name.id;
PostgreSQL provides three serial pseudo-types SMALLSERIAL, SERIAL, and BIGSERIAL with the following characteristics:
Now let’s look into an example for better understanding.Example:The following statement creates the animals table with the id column as the SERIAL column:
CREATE TABLE animals(
   id SERIAL PRIMARY KEY,
   name VARCHAR NOT NULL
);
Now we will insert a single value to the animal table as below:
INSERT INTO animals(name) 
VALUES('Dog');
We repeat the above statement wit5h a different value as below:
INSERT INTO animals(name) 
VALUES('Cat');
PostgreSQL inserted two rows into the animals table with the values for the id column are 1 and 2. To verify so use the below statement:
SELECT * FROM animals;
Output:
Example 2:The following statement inserts a new row into the animals table and returns the value generated for the id column:
INSERT INTO animals(name) 
VALUES('Tiger')
RETURNING id; 
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - IF Statement
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - SELECT
PostgreSQL - REPLACE Function
PostgreSQL - GROUP BY clause
PostgreSQL - Create Database
PostgreSQL Tutorial
PostgreSQL - FETCH clause
PostgreSQL - INSERT
PostgreSQL - BETWEEN operator
matplotlib.pyplot.scatter() in Python

15 Feb, 2022
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is used for plotting various plots in Python like scatter plot, bar charts, pie charts, line plots, histograms, 3-D plots and many more. We will learn about the scatter plot from the matplotlib library. Note: For more information, refer to Python Matplotlib – An Overview 
Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relation among variables and how change in one affects the other. Syntax The syntax for scatter() method is given below: 
matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)  
The scatter() method takes in the following parameters:  
x_axis_data- An array containing x-axis data
y_axis_data- An array containing y-axis data
s- marker size (can be scalar or array of size equal to size of x or y)
c- color of sequence of colors for markers
marker- marker style
cmap- cmap name
linewidths- width of marker border
edgecolor- marker border color
alpha- blending value, between 0 (transparent) and 1 (opaque)
Except x_axis_data and y_axis_data all other parameters are optional and their default value is None. Below are the scatter plot examples with various parameters.Example 1: This is the most basic example of a scatter plot.  
Python3
import matplotlib.pyplot as plt  x =[5, 7, 8, 7, 2, 17, 2, 9,    4, 11, 12, 9, 6] y =[99, 86, 87, 88, 100, 86,    103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y, c ="blue") # To show the plotplt.show()
Output  
Example 2: Scatter plot with different shape and colour for two datasets.  
Python3
import matplotlib.pyplot as plt # dataset-1x1 = [89, 43, 36, 36, 95, 10,      66, 34, 38, 20] y1 = [21, 46, 3, 35, 67, 95,      53, 72, 58, 10] # dataset2x2 = [26, 29, 48, 64, 6, 5,      36, 66, 72, 40] y2 = [26, 34, 90, 33, 38,      20, 56, 2, 47, 15] plt.scatter(x1, y1, c ="pink",            linewidths = 2,            marker ="s",            edgecolor ="green",            s = 50) plt.scatter(x2, y2, c ="yellow",            linewidths = 2,            marker ="^",            edgecolor ="red",            s = 200) plt.xlabel("X-axis")plt.ylabel("Y-axis")plt.show()
Output  
 
varshagumber28
simranarora5sos
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UCASE() or UPPER() Function in MySQL

16 Jun, 2021
1. UCASE() : This function could be used to convert a string to upper-case. This function is similar to the UPPER() function. UPPER()\UCASE() are built-in MySQL function. 
Syntax :  
SELECT UCASE(text)
Example –  
SELECT UCASE("MySQL on geeksforgeeks is FUN!") AS UpperText;
Output : 
 
Now, here you will see UPPER function. 
2. UPPER() : 
Syntax :  
SELECT UPPER(text)
Example –  
SELECT UPPER("MySQL on geeksforgeeks is FUN!") AS UpperText;
Output : 
 
Dealing with binary string data : The UPPER() function does not affect the binary strings such as BINARY, VARBINARY, or BLOB. Hence, to use binary string in the UPPER() function, it needed to convert to the string to non-binary string. 
Example –  
SET @str = BINARY 'Geeksforgeeks';
Now, If you want to read binary string used the following syntax given below.  
SELECT UPPER(@str), UPPER(CONVERT(@str USING utf8mb4)) AS UpperText;
Output : 
 
Note – It is clearly observed from the output, the UPPER() function has no effect on the binary string. 
rajeev0719singh
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala List min() method with example

26 Jul, 2019
The min() method is utilized to find the smallest element of all the elements in the stated list.
Method Definition: def min[B >: A](implicit ord: math.Ordering[B]): A
Return Type: It returns the smallest of all the elements in the stated list.
Example #1:
// Scala program of min()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 2, 3)                  // Applying min method        val result = m1.min                  // Displays output        println(result)          }}
1

Example #2:
// Scala program of min()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying min method        val result = m1.min                  // Displays output        println(result)          }}
3

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Scala | Arrays
Lambda Expression in Scala
How to Install Scala with VSCode?
Enumeration in Scala
How to get the first element of List in Scala
HashMap in Scala
Scala String replace() method with example
Sorting an array in Bash using Bubble sort

25 Nov, 2021
Prerequisite: Bubble Sort 
Given an array arr sort the array in ascending order using bash scripting.
Examples:  
Input : 9 7 2 5
Output :
Array in sorted order :
2 5 7 9
Approach :
For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they are in the wrong order. 
Example: 
Given array - (9, 7, 2, 5)
After first iteration - (7, 2, 5, 9)
After second iteration - (2, 5, 7, 9)
and so on...
In this way, the array is sorted by placing the greater element at the end of the array.  
# Sorting the array in Bash 
# using Bubble sort

# Static input of Array
arr=(10 8 20 100 12)

echo "Array in original order"
echo ${arr[*]}

# Performing Bubble sort 
for ((i = 0; i<5; i++))
do
    
    for((j = 0; j<5-i-1; j++))
    do
    
        if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
        then
            # swap
            temp=${arr[j]}
            arr[$j]=${arr[$((j+1))]}  
            arr[$((j+1))]=$temp
        fi
    done
done

echo "Array in sorted order :"
echo ${arr[*]}
Output : 
Array in sorted order :
8 10 12 20 100
Optimized Implementation:  The above function always runs O(n^2) time even if the array is sorted. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. 
n=5
arr=(10 8 20 100 12) 

echo "Original array is: ${arr[*]}";

flag=1;
for (( i = 0; i < $n-1; i++ ))
do
    flag=0;
    for ((j = 0; j < $n-1-$i; j++ ))
    do
        if [[ ${arr[$j]} -gt ${arr[$j+1]} ]]
        then
            temp=${arr[$j]};
            arr[$j]=${arr[$j+1]};
            arr[$j+1]=$temp;
            flag=1;
        fi
    done

    if [[ $flag -eq 0 ]]; then
          break;
    fi
Output:
Original array is: 10 8 20 100 12
Final sorted Array is 8 10 12 20 100
Worst and Average Case Time Complexity: O(n*n). The worst-case occurs when an array is reverse sorted.
Best Case Time Complexity: O(n). The best-case occurs when the array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes
nitin_19520
kr123manish
ruhelaa48
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Zoho Interview Preparation Process and Experience - GeeksforGeeks

29 Jan, 2020
Zoho is one of the best product based company in India with friendly environment. Many engineers are passionate toward coding nowadays. But many face lot of difficulty in cracking the interview. There are few tips i like to share based on my interview experience and past guidance from my college staff and seniors. There are three stage to crack the Zoho.  Learn, practice and fail. The success teach us to about us but failure teaches how we need to improve our-self. This is a cyclic process.In Zoho Software Development role there are several few round as stated below:
Written testCodingCoding related to oopsHR Round
Written test
Coding
Coding related to oops
HR Round
Written test:
The candidate must be strong in the syntax and how it work for the given input. The candidate must be very strong in the loop and conditional statement. The pointer concept plays a major role in the shortlisting the candidate. For example,
//Write C code here#include<stdio.h>#include<conio.h>void main(){ int a; if(a=0){printf("%d", a); else {printf("zoho");   break; }}
Options:
a. zoho                b.Error
c. 0                   d.no output 

Answer: Error because of break statement
Coding
The candidate will be given a simple problem statement to solve. The candidate can use any programming language like c, c++ and java to solve the particular problem statement. If the candidate solves the particular problem statement within the particular time slot he/she will get the next problem statement and the process continues for the day. If not the candidate has to leave the company.
Coding related to oops
The candidate must be strong in oops concept the candidate will be tested based on the logical thinking. The candidate must be strong in the logic and he/she must be in the situation to execute those programs without any errors.
HR InterviewThe candidate’s attitude and the personality is checked and her/his programming ability. The HR round will be based on the candidate’s resume.
Marketing
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Directi Interview | Set 7 (Programming Questions)
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
hostname - Unix, Linux Command

hostname  - show or set the system's host name.
hostname [-v] [-a] [--alias] [-d] [--domain] [-f] [--fqdn] [-A] [--all-fqdns] [-i] [--ip-address] [-I] [--all-ip-addresses] [--long] [-s] [--short] [-y] [--yp] [--nis]

hostname [-v] [-F filename] [--file filename] [hostname]

hostname [-v] [-h] [--help] [-V] [--version]
Hostname is the program that is used to either set or display the current host, domain or node name of the system.
 These names are used by many of the networking programs to identify the machine.
Example-1:
To print the hostname of the system :
$ hostname
output:
# hostnametestserver.tutorialspoint.com
Example-2:
To print IP address of the computer :
$ hostname -i
output:
192.168.134.128
Example-3:
To print the domain name :
$ hostname -d
output:
tutorialspoint.com
Example-4:
To print short hostname :
$ hostname -s
output:
testserver

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page