code-rag-bench/online-tutorials huggingface dataset:
How to Execute SQL Server Stored Procedure in SQL Developer?

23 Sep, 2021
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again.
In this article let us see how to execute SQL Server Stored Procedure in MSSQL.
Syntax: For creating a stored procedure
CREATE PROCEDURE (or CREATE PROC) proc_name
AS
BEGIN
  QUERY
END
Step 1: We creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Output:
Step 2:To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Output:
Step 3:Now we creating a table. Create a table student_details with  3 columns using the following SQL query.
Query:
CREATE TABLE student_details(
   stu_id VARCHAR(8),
   stu_name VARCHAR(20),
   stu_cgpa DECIMAL(4,2) );
Output:
Step 4: The query for Inserting rows into the Table. Inserting rows into student_details table using the following SQL query.
Query:
INSERT INTO student_details VALUES('40001','PRADEEP',9.6);
INSERT INTO student_details VALUES('40002','ASHOK',8.2);
INSERT INTO student_details VALUES('40003','PAVAN KUMAR',7.6);
INSERT INTO student_details VALUES('40004','NIKHIL',8.2);
INSERT INTO student_details VALUES('40005','RAHUL',7.0);
Output:
 Step 5: Viewing the inserted data
Query:
SELECT * FROM student_details;
Output:
Query to create a stored procedure to view the table:
Query:
CREATE PROCEDURE view_details
AS
BEGIN 
  SELECT * FROM student_details;
END
Output:
 For executing a stored procedure we use the below syntax:
Syntax:
 EXEC proc_name
 or
 EXECUTE proc_name
 or 
 proc_name
Query:
EXECUTE view_details
Output:
Query to create a stored procedure that takes the argument as stu_id and displays the cgpa of that id.
Query:
CREATE PROCEDURE get_student_cg_details
@stu_id VARCHAR(20)
AS
BEGIN  
 SELECT stu_id, stu_cgpa FROM student_details
 WHERE stu_id= @stu_id
END
Output:
Query:
EXECUTE get_student_cg_details '40002'
Output:
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert Ordereddict to JSON?

02 Feb, 2021
In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through  some concepts:
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. 
The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features
An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict and OrderedDict() is that:
OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.
To define the OrderedDict, we are using the collections module in python.
Python3
# import packagefrom collections import OrderedDict  # define OrderedDictod1 = OrderedDict([('1','one'),                    ('2','two')])  # display dictionaryprint(type(od1))print(od1)
Output:
<class 'collections.OrderedDict'>
OrderedDict([('1', 'one'), ('2', 'two')])
To convert OrderedDict to JSON, we are using json.dumps(). 
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.
The json.dumps() function converts a Python object into a JSON string.
Python3
# import packagefrom collections import OrderedDictimport json  # define OrderedDictod1 = OrderedDict([('1','one'),                    ('2','two')])  # check type i.e; OrderedDictprint(type(od1))  # convert to jsonod1 = json.dumps(od1)  # check type i.e; strprint(type(od1))  # view valueprint(od1)
<class 'collections.OrderedDict'>
<class 'str'>
{"1": "one", "2": "two"}
We can give indent value to show the dictionary pattern.
Python3
# import packagefrom collections import OrderedDictimport json  # define OrderedDictod1 = OrderedDict([('1', 'one'),                   ('2', 'two')])  # check type i.e; OrderedDictprint(type(od1))  # convert to jsonod1 = json.dumps(od1, indent=4)  # check type i.e; strprint(type(od1))  # view valueprint(od1)
Output:
<class 'collections.OrderedDict'>
<class 'str'>
{
    "1": "one",
    "2": "two"
}
Picked
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Exclude Multiple Values

13 Sep, 2021
To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement.
In this article let us see the SQL query to exclude multiple values using both AND and NOT IN clauses.
Use the below command to create a database named GeeksforGeeks:
CREATE DATABASE GeeksforGeeks
To use the GeeksforGeeks database use the below command:
USE GeeksforGeeks
Create a table student_details with  4 columns using the following SQL query:
CREATE TABLE student_details(
stu_id VARCHAR(8),
branch VARCHAR(20),
course_code VARCHAR(10),
backlogs VARCHAR(10)
);
To view the description of the tables in the database using the following SQL query:
EXEC sp_columns student_details;
Inserting rows into student_details tables using the following SQL query:
INSERT INTO student_details VALUES
  ('191401','E.C.E','ECPC-251', 'NO'),
  ('191302','I.C.E','ICPC-221','YES'),
  ('191305','I.C.E','ICPC-225','YES'),
  ('191410','E.C.E','ECPC-251', 'YES'),
  ('191210','M.E','MEPC-103', 'YES'),
  ('191215','M.E','MEPC-101', 'NO'),
   ('191505','C.E','CEPC-501', 'NO'),
  ('191525','C.E','CEPC-502', 'NO');
Viewing the table student_details after inserting rows by using the following SQL query:
SELECT* FROM employee_details;
1. Query to find the students other than ‘ECE’, ‘ICE’, ‘ME’
Using NOT IN:
Syntax:
SELECT * FROM table_name
WHERE req_column NOT IN(data1,data2,data3,....)
Query:
SELECT* FROM student_details
WHERE branch NOT IN ('E.C.E','I.C.E','M.E');
Using AND:
Syntax:
SELECT * FROM table_name
WHERE condition1 AND condition2 AND condition3;
Query:
SELECT* FROM student_details
WHERE branch<>'E.C.E' AND branch <> 'I.C.E' AND branch<>'M.E';
2. Query to update the backlogs to NO other than students of C.E and M.E.
UPDATE student_details
SET backlogs='NO' WHERE branch NOT IN ('C.E','M.E');
SELECT* FROM student_details;
Blogathon-2021
Picked
SQL-Query
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Shared ViewModel in Android
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to define an array class in C#?

The Array class is the base class for all the arrays in C#. It is defined in the System namespace and has the following properties −
To define an array class, you can try to run the following code, wherein we are sorting an array −
 Live Demo
using System;

namespace Demo {
   class MyArray {
      static void Main(string[] args) {
         int[] list = { 45, 19, 9, 28, 87};
         int[] temp = list;
         Console.Write("Original Array: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine();

         Array.Sort(list);
         Console.Write("Sorted Array: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}
Original Array: 45 19 9 28 87
Sorted Array: 9 19 28 45 87
Python | Pandas Series.dt.floor

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.floor() function perform floor operation on the data to the specified freq.
Syntax: Series.dt.floor(*args, **kwargs)
Parameter :freq : The frequency level to floor the index to
Returns : DatetimeIndex, TimedeltaIndex, or Series
Example #1: Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30',               '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Daily frequency.
# floor to daily frequencyresult = sr.dt.floor(freq = 'D')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency.
Example #2 : Use Series.dt.floor() function to floor the datetime data of the given series object to the specified frequency.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'T',                            tz = 'Asia / Calcutta'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.floor() function to floor the datetime values in the given series object to Hourly frequency.
# floor to hourly frequencyresult = sr.dt.floor(freq = 'H')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.floor() function has successfully floored the datetime values in the given series object to the specified frequency.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install pip in macOS ?

01 Jul, 2022
Before we start with how to install pip for Python on macOS, let’s first go through the basic introduction to Python. 
Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. In this article, we will see How to Install PIP on a Mac. Using pip you can install any package using the following syntax:
pip install package_name
pip can be downloaded and installed usingthe  command line by going through the following steps:
Step 1: Download the  get-pip.py(https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as python is installed. or Use the following command to download pip directly
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Step 2: Now execute the downloaded file using the below command
python3 get-pip.py
Step 3:  Wait through the installation process. 
 
Voila! pip is now installed on your system.
One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:
pip3 --version
pip --version
 
You can use the following command in your terminal to upgrade your pip. 
python3 -m pip install –upgrade pip
To install a specific version you can enter the following version number to install the specific version.
pip install --upgrade pip==1.2.1
You can use one of the commands to uninstall the pip command based on your system.
pip uninstall pip
sudo apt-get remove python-pip
surajkumarguptaintern
Python-pip
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
bg - Unix, Linux Command

bg - Sends job to background.
bg [PID...]
bg sends the specified jobs to the background. A background job is executed simultaneously with fish, and does not have access to the keyboard. If no job is specified, the last job to be used is put in the background. The PID of the desired process is usually found by using process expansion.
To put the job with job id 0 in the background.
random.triangular() method in Python

17 May, 2020
triangular() is an inbuilt method of the random module. It is used to return a random floating point number within a range with a bias towards one extreme.
Syntax : random.triangular(low, high, mode)
Parameters :low : the lower limit of the random numberhigh : the upper limit of the random numbermode : additional bias; low < mode < high
if the parameters are (10, 100, 20) then due to the bias, most of the random numbers generated will be closer to 10 as opposed to 100.
Returns : a random floating number
Example 1:
# import the random moduleimport random  # determining the values of the parameterslow = 10high = 100mode = 20  # using the triangular() methodprint(random.triangular(low, high, mode))
Output :
22.614510550239572
Example 2: If we generate the number multiple times we can probably identify the bias.
# import the random moduleimport random  # determining the values of the parameterslow = 10high = 100mode = 20  # running the triangular method with the# same parameters multiple timesfor i in range(10):    print(random.triangular(low, high, mode))
Output :
58.645768016894735
46.690692250503226
33.57590419190895
52.331804090351305
33.09451214875767
12.03845752596168
32.816080679206294
20.4739124559502
82.49208123077557
63.511062284733015
Example 3: We can visualize the triangular pattern by plotting a graph.
# import the required librariesimport randomimport matplotlib.pyplot as plt    # store the random numbers in a listnums = []low = 10high = 100mode = 20  for i in range(10000):    temp = random.triangular(low, high, mode)    nums.append(temp)      # plotting a graphplt.hist(nums, bins = 200)plt.show()
Output :
Python-random
Python
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
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Matplotlib.pyplot.ginput() in Python

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The ginput() method pyplot module of matplotlib library is used to block call to interact with a figure.
Syntax: matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
Parameters: This method accept the following parameters that are described below:
n : This parameter is the number of mouse clicks to accumulate.
timeout : This parameter is the number of seconds to wait before timing out.
show_clicks : This parameter is used to show a red cross at the location of each click.
mouse_add : This parameter is the Mouse button used to add points.
mouse_pop : This parameter is the Mouse button used to remove the most recently added point.
mouse_stop : This parameter is the Mouse button used to stop input.
Returns: This method return the list of the clicked (x, y) coordinates.
Below examples illustrate the matplotlib.pyplot.ginput() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npt = np.arange(10)     plt.plot(t, np.sin(t))     plt.title('matplotlib.pyplot.ginput()\ function Example', fontweight ="bold")   print("After 3 clicks :")x = plt.ginput(3)print(x)   plt.show()
Output:
After 3 clicks :
[(4.460080645161289, 0.5915838985273842), 
(4.460080645161289, 0.5915838985273842), 
(4.460080645161289, 0.5915838985273842)]

Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np     np.random.seed(10**7)     x1 = np.random.rand(103, 53)      plt.title('matplotlib.pyplot.ginput() function\ Example', fontweight ="bold")   print("After 2 clicks :")plt.imshow(x1)x = plt.ginput(2) print(x)   plt.show()
Output:
After 2 clicks :
[(8.443181818181813, 38.90530303030302), 
(8.443181818181813, 38.90530303030302)]

Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
numpy.trunc() in Python

04 Dec, 2020
The numpy.trunc() is a mathematical function that returns the truncated value of the elements of array. The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function.
Syntax : numpy.trunc(x[, out]) = ufunc ‘trunc’)Parameters :
a : [array_like] Input array
Return :The truncated of each element, with float data-type
Code #1 : Working
# Python program explaining# trunc() function  import numpy as np  in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array)  truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values)    in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array)  truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values)  in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array)  truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values)
Output :
Input array : 
 [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values : 
 [  0.   1.   2.   3.   4.  10.]

Input array : 
 [0.53, 1.54, 0.71]

Rounded values : 
 [ 0.  1.  0.]

Input array : 
 [0.5538, 1.33354, 0.71445]

Rounded values : 
 [ 0.  1.  0.]
 
Code 2 : Working
# Python program explaining# trunc() function  import numpy as np  in_array = [1.67, 4.5, 7, 9, 12]print ("Input array : \n", in_array)  truncoff_values = np.trunc(in_array)print ("\nRounded values : \n", truncoff_values)    in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print ("\nInput array : \n", in_array)  truncoff_values = np.trunc(in_array)print ("\nRounded values upto 2: \n", truncoff_values)
Output :
Input array : 
 [1.67, 4.5, 7, 9, 12]

Rounded values : 
 [  1.   4.   7.   9.  12.]

Input array : 
 [133.0, 344.54, 437.56, 44.9, 1.2]

Rounded values upto 2: 
 [ 133.  344.  437.   44.    1.]
 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.trunc.html#numpy.trunc.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
How to make a C++ class whose objects can only be dynamically allocated?

21 Jun, 2022
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class ‘Test’ with following rules. 
CPP
Test t1;  // Should generate compiler errorTest *t3 = new Test; // Should work fine
The idea is to create a private destructor in the class. When we make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use. Since compiler is not responsible for deallocation of dynamically allocated objects (programmer should explicitly deallocate them), compiler won’t have any problem with them. To avoid memory leak, we create a friend function destructTest() which can be called by users of class to destroy objects. 
CPP
#include <iostream>using namespace std; // A class whose object can only be dynamically createdclass Test{private:    ~Test() { cout << "Destroying Object\n"; }public:    Test() { cout << "Object Created\n"; }friend void destructTest(Test* );}; // Only this function can destruct objects of Testvoid destructTest(Test* ptr){    delete ptr;    cout << "Object Destroyed\n";} int main(){    /* Uncommenting following line would cause compiler error */    // Test t1;     // create an object    Test *ptr = new Test;     // destruct the object to avoid memory leak    destructTest(ptr);     return 0;}
Output:
Object Created
Destroying Object
Object Destroyed
Time Complexity: O(1)
Auxiliary Space: O(1)
If we don’t want to create a friend function, we can also overload delete and delete[] operators in Test, this way we don’t have to call a specific function to delete dynamically allocated objects. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sweetyty
tarakki100
cpp-constructor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
SQL Query to Find the Year from Date

26 Apr, 2021
Overview :You will be able to understand the implementation to Find the Year from Date in SQL with the help of an example. Here we will see, how to find or extract the year from the given date in MS SQL Server’s database table with the help of SQL query. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“.
Steps to implement SQL Query to Find the Year from Date :Here, we will discuss the steps to implement the SQL Query to Find the Year from Date as follows.
Step-1: Creating the Database :Use the below SQL statement to create a database called geeks as follows.
CREATE DATABASE geeks;
Step-2: Using the Database :Use the below SQL statement to switch the database context to geeks as follows.
USE geeks;
Step-3 : Creating Table :We have the following demo table in our geeks database.
CREATE TABLE demo_orders(
 ORDER_ID INT IDENTITY(1,1) PRIMARY KEY, 
 --IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.
 --Starts from 1 and increases by 1 with each inserted row.
 ITEM_NAME VARCHAR(30) NOT NULL,
 ORDER_DATE DATE
);
Step-4: Verifying table :You can use the below statement to query the description of the created table as follows.
EXEC SP_COLUMNS demo_orders;
Output :
Step-5: Adding data to the table :Use the below statement to add data to the demo_orders table as follows.
INSERT INTO demo_orders 
--no need to mention columns explicitly as we are inserting into all columns and ID gets 
--automatically incremented.
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
Step-6: Verifying Inserted data :To verify the contents of the table use the below statements as follows.
SELECT * FROM demo_orders;
Output :
Step-7: Implementation of Query to Find the Year from Date :Now let’s find the year of the order with ITEM_NAME as ‘Maserati’ with the help of the YEAR() function. Below is the syntax to retrieve the year from the given date.
Syntax –
SELECT YEAR(<date_string>);
--or within a table--
SELECT YEAR(<column_table>) FROM <table_name>;
Example –
SELECT YEAR(ORDER_DATE) AS YEAR_OF_ORDER
FROM demo_orders
WHERE ITEM_NAME='Maserati';
Output :
Step-8: Implementation of Query to Find day, month and year from Date :Similarly, we can find the respective day and month of the given date using DAY() and MONTH() functions.
Example –
SELECT day(order_date)[day], --here [day] is the identifier name for the column in the output.
       month(order_date)[month], 
       year(order_date)[year]
FROM demo_orders 
WHERE ITEM_NAME='Lamborghini';
Output :
DBMS-SQL
Picked
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
OLAP Guidelines (Codd's Rule)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
GATE | GATE-CS-2009 | Question 35

28 Jun, 2021
The running time of an algorithm is represented by the following recurrence relation:
    if  n <= 3  then   T(n) = n
    else T(n) = T(n/3) + cn

Which one of the following represents the time complexity of the algorithm? <pre>(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n) </pre>
 (A) A(B) B(C) C(D) DAnswer: (A)Explanation:
Answer(A)
T(n) = cn + T(n/3)
     = cn + cn/3 + T(n/9)
     = cn + cn/3 + cn/9 + T(n/27)
Taking the sum of infinite GP series. The value of T(n) will
be less than this sum.
T(n) <= cn(1/(1-1/3))
     <= 3cn/2

or we can say 
cn <= T(n) <= 3cn/2
Therefore T(n) = (n)
This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.
Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Square matrix rotation in JavaScript

We are required to write a JavaScript function that takes in an array of arrays of n * n order (square matrix). The function should rotate the array by 90 degrees (clockwise). The condition is that we have to do this in place (without allocating any extra array).
For example −
If the input array is −
const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
Then the rotated array should look like −
const output = [
   [7, 4, 1],
   [8, 5, 2],
   [9, 6, 3],
];
Following is the code −
const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const rotateArray = (arr = []) => {
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
      columnIndex += 1) {
         [
            arr[columnIndex][rowIndex],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[columnIndex][rowIndex],
         ];
      }
   }
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = 0; columnIndex < arr.length / 2;
      columnIndex += 1) {
         [
            arr[rowIndex][arr.length - columnIndex - 1],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[rowIndex][arr.length - columnIndex - 1],
         ];
      }
   }
};
rotateArray(arr);
console.log(arr);
Following is the output on console −
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]
How to add a button dynamically in android?

This example demonstrates how do I add a button dynamically 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"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:gravity="center"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   RelativeLayout relativeLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      relativeLayout = findViewById(R.id.relativeLayout);
      Button button = new Button(this);
      button.setText("Dynamically created Button");
      button.setLayoutParams(new
         RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
         ViewGroup.LayoutParams.WRAP_CONTENT));
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(MainActivity.this, "This button is created dynamically",
               Toast.LENGTH_SHORT).show();
         }
      });
      if (relativeLayout != null){
         relativeLayout.addView(button);
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
   xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action
               android:name="android.intent.action.MAIN" />
            <category
               android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
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 −
Excel Tutorial

Excel is the world's most used spreadsheet program
Excel is a powerful tool to use for mathematical functions
Start learning Excel now »
Learn Excel
We use practical examples to give the user a better understanding of the concepts.
Example values can be copied from the tutorial and into your spreadsheet, making it easy for you to tag along 
step-by-step:
We have created active learning activities, so you can test and build your knowledge. Making the learning experience more fun and engaging.
Solve Case »
Excel is the world's most used spreadsheet program.
Example use areas:

Data analytics
Project management
Finance and accounting

Data analytics
Project management
Finance and accounting
Complete the Excel formula:
1+1

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to insert an image in to Oracle database using Java program?

To hold an image in Oracle database generally blob type is used. Therefore, make sure that you have a table created with a blob datatype as:
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(255)
IMAGE BLOB
To insert an image in to Oracle database, follow the steps given below:
You can connect to a database using the getConnection() method of the DriverManager class
Connect to the Oracle database by passing the Oracle URL which is jdbc:oracle:thin:@localhost:1521/xe (for express edition), username and password as parameters to the getConnection() method.
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "user_name", "password");
Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");
Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.
And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters.
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertImageToOracleDB {
   public static void main(String args[]) throws Exception{
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("Connected to Oracle database.....");
      PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
      pstmt.setString(1, "sample image");
      //Inserting Blob type
      InputStream in = new FileInputStream("E:\\images\\cat.jpg");
      pstmt.setBlob(2, in);
      //Executing the statement
      pstmt.execute();
      System.out.println("Record inserted");
   }
}
Connected to Oracle database.....
Record inserted.....
Python Pandas - Sort DataFrame in descending order according to the element frequency

To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −
ascending=False
Import the required library −
import pandas as pd

Create a DataFrame with 3 columns −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)
To sort DataFrame in descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −
dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)
Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)

print"DataFrame ...\n",dataFrame

# Sort DataFrame in descending order according to the element frequency
dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)

print"\nSorting DataFrame ...\n",dataFrame
This will produce the following output −
DataFrame ...
         Car     Place   Reg_Price
0       BMW       Pune        7000
1     Lexus      Delhi        1500
2       BMW     Mumbai        5000
3   Mustang  Hyderabad        8000
4  Mercedes  Bangalore        9000
5     Lexus Chandigarh        2000

Sorting DataFrame ...
        Car   Count
0       BMW       2
1     Lexus       2
2  Mercedes       1
3   Mustang       1
How to pass arguments to animation.FuncAnimation() in Matplotlib?

To pass arguments to animation.FuncAnimation() for a contour plot in Matplotlib in Python, we can take the following steps −
Create a random data of 10☓10 dimension.
Create a figure and a set of subplots using subplots() method.
Make an animation by repeatedly calling a function *func* using FuncAnimation() class
To update the contour value in the function, we can define a method animate() that can be used in FuncAnimation() class.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()

def animate(i):
   ax.clear()
   ax.contourf(data[:, :, i])

ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)

plt.show()
Python | sympy.sympify() method - GeeksforGeeks

18 Jun, 2019
With the help of sympy.sympify() method, we are able to convert the expression of string type to general mathematical expression.
Syntax : sympy.sympify()Return : Return the expression.
Example #1 :In this example we can see that by using sympy.sympify(), we are converting the string of expression into real mathematical expression.
# Import sympyfrom sympy import *  # Define symbols and trigo expressionx, y = symbols('x y')expn = "x**2 + 3 * x - 1 / 2"  # Use sympy.sympify() methodgfg = sympify(expn)  print(gfg)
Output :
x**2 + 3*x – 1/2
Example #2 :
# Import sympyfrom sympy import *  # Define symbols and trigo expressionx, y = symbols('x y')expn = "x**2 + 3 * x - 1 / 2"  # Use sympy.sympify() methodgfg = sympify(expn)gfg = gfg.subs(x, 3)  print(gfg)
Output :
35/2
SymPy
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()
How to Draw a Circle Using Matplotlib in Python? - GeeksforGeeks

13 Sep, 2021
A Circle is a mathematical figure formed by joining all points lying on the same plane and are at equal distance from a given point. We can plot a circle in python using Matplotlib. There are multiple ways to plot a Circle in python using Matplotlib. 
Method 1: Using matplotlib.patches.Circle() function.
Matplotlib has a special function matplotlib.patches.Circle() in order to plot circles. 
Syntax: class matplotlib.patches.Circle(xy, radius=5, **kwargs)
Example 1: Plotting a colored Circle using matplotlib.patches.Circle()
Python3
# Demonstrating use of matplotlib.patches.Circle() function# to plot a colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_colored_circle = plt.Circle(( 0.6 , 0.6 ), 0.2 ) axes.set_aspect( 1 )axes.add_artist( Drawing_colored_circle )plt.title( 'Colored Circle' )plt.show()
Output:
Example 2: Plotting an un-colored Circle using matplotlib.patches.Circle()
Python3
# Demonstrating use of matplotlib.patches.Circle() function# to plot an un-colored Circle import matplotlib.pyplot as plt figure, axes = plt.subplots()Drawing_uncolored_circle = plt.Circle( (0.6, 0.6 ),                                      0.3 ,                                      fill = False ) axes.set_aspect( 1 )axes.add_artist( Drawing_uncolored_circle )plt.title( 'Circle' )plt.show()
Output:
Method 2: Using Circle Equation
Example 1: Plotting a Circle using Parametric equation of a circle
Python3
# Program to plot a Circle# using Parametric equation of a Circle import numpy as npimport matplotlib.pyplot as plt theta = np.linspace( 0 , 2 * np.pi , 150 ) radius = 0.4 a = radius * np.cos( theta )b = radius * np.sin( theta ) figure, axes = plt.subplots( 1 ) axes.plot( a, b )axes.set_aspect( 1 ) plt.title( 'Parametric Equation Circle' )plt.show()
Output:
Example 2: Using Center-Radius form of a circle equation
Python3
# Program to plot a Circle# using Center-Radius form of circle equation import numpy as npimport matplotlib.pyplot as plt x = np.linspace( -0.7 , 0.7 , 150 )y = np.linspace( -0.7 , 0.7 , 150 ) a, b = np.meshgrid( x , y ) C = a ** 2 + b ** 2 - 0.2 figure, axes = plt.subplots() axes.contour( a , b , C , [0] )axes.set_aspect( 1 ) plt.title( 'Center-Radius form Circle' )plt.show()
Output:
Method 3: Using the Scatter Plot of points 
Example:
Python3
# Program to plot a Circle# using Scatter plot of points import matplotlib.pyplot as plt plt.scatter( 0 , 0 , s = 7000 )plt.title( 'Circle' ) plt.xlim( -0.85 , 0.85 )plt.ylim( -0.95 , 0.95 ) plt.title( "Scatter plot of points Circle" )plt.show()
Output:
simmytarika5
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
numpy.isnan() in Python - GeeksforGeeks

28 Mar, 2022
The numpy.isnan() function tests element-wise whether it is NaN or not and returns the result as a boolean array. Syntax : 
numpy.isnan(array [, out])
Parameters : 
array : [array_like]Input array or object whose elements, we need to test for infinity
out   : [ndarray, optional]Output array placed with result.
      Its type is preserved and it must be of the right shape to hold the output.
Return : 
boolean array containing the result. For scalar input, the result is a new boolean with value
True if the input is positive or negative infinity; otherwise the value is False.
For array input, the result is a boolean array with the same shape as the input and the values
are True where the corresponding element of the input is positive or negative infinity; 
elsewhere the values are False.
Code 1 : 
Python
# Python Program illustrating# numpy.isnan() method  import numpy as geek print("Is NaN : ", geek.isnan(1), "\n") print("Is NaN : ", geek.isnan(0), "\n") # not a numberprint("Is NaN : ", geek.isnan(geek.nan), "\n") #  infinityprint("Is NaN : ", geek.isnan(geek.inf), "\n") print("Is NaN : ", geek.isnan(geek.NINF), "\n") x = geek.array([-geek.inf, 0., geek.inf])y = geek.array([2, 2, 2])print("Checking for NaN : ", geek.isnan(x, y))
Output : 
Is NaN :  False 

Is NaN :  False 

Is NaN :  True 

Is NaN :  False 

Is NaN :  False 

Checking for NaN :  [0 0 0]
Code 2 : 
Python
# Python Program illustrating# numpy.isnan() method   import numpy as geek  # Returns True/False value for each elementb = geek.arange(20).reshape(5, 4)                print("\n",b)print("\nIs NaN(Not a Number): \n", geek.isnan(b))  b = [[1j],     [geek.nan]]print("\nIs NaN(Not a Number) : \n", geek.isnan(b))
Output : 
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]

Is NaN(Not a Number): 
 [[False False False False]
 [False False False False]
 [False False False False]
 [False False False False]
 [False False False False]]

Is NaN(Not a Number) : 
 [[False]
 [ True]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isnan.html 
Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
vinayedula
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Multi-Line printing in Python - GeeksforGeeks

21 Jan, 2019
We have already seen the basic use of print function previous article. Now, let’s see how to use print function for multi-line printing. This can easily be done using multiline string i.e. three single quotes ''' Geeksforgeeks ''' .
Let’s see different examples to see the demonstration for the same.
Example #1:
# basic example for multi-line printingprint('''=======================================|                                     ||                                     ||          GeeksforGeeks              ||                                     ||                                     |======================================='''    )
=======================================
|                                     |
|                                     |
|          GeeksforGeeks              |
|                                     |
|                                     |
=======================================

Example #2:
# basic example2 for multi-line printingprint(  '''list.head        second              third          |                |                  |          |                |                  |     +----+------+     +----+------+     +----+------+     | 1  | None |     | 2  | None |     |  3 | None |     +----+------+     +----+------+     +----+------+     '''    )
list.head        second              third 
         |                |                  | 
         |                |                  | 
    +----+------+     +----+------+     +----+------+ 
    | 1  | None |     | 2  | None |     |  3 | None | 
    +----+------+     +----+------+     +----+------+

python-basics
python-io
Python
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python