code-rag-bench/online-tutorials huggingface dataset:
How to integrate Mysql database with Django?

16 Mar, 2021
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. 
How to integrate Mysql database with Django ?
Install Mysql database
https://dev.mysql.com/downloads/installer/
After downloading install the setup and set the admin and password.
Install Django
pip install django
Then install another library to use mysql database
pip install mysqlclient
Create new project
django-admin startproject MyDB
cd MyDB
settings.py
Python3
DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'mydb',        'USER': 'root',        'PASSWORD': 'admin',        'HOST':'localhost',        'PORT':'3306',    }}
Open settings.py here inside the DATABASES variable configure mysql database values, and add values of your database.
python manage.py migrate
Then create new app
python manage.py startapp main
main/models.py
Python3
from django.db import modelsfrom django.contrib.auth.models import User  #Create your models here.class PublishedArticle(models.Model):    todo = models.CharField(max_length=40)    date = models.DateField(auto_now=True)
python manage.py migrate
The published article table would have been created in the Database. Hence, Mysql database is successfully integrated
mysql
Python Django
Python Framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Add One in Python

Suppose we have a list of integers called n, this is representing a decimal number and n[i] is between [0, 9]. So, if the n is [2, 4, 9] represents the number 249. We have to find the same list in the same representation except modified so that 1 is added to the number.
So, if the input is like n = [9,9], then the output will be [1, 0, 0]
To solve this, we will follow these steps −
n := add 0 at the beginning of n
n := add 0 at the beginning of n
increase last element of n by 1
increase last element of n by 1
for i in range size of n - 1 to 0, decrease by 1, don[i-1] := n[i-1] + quotient of (n[i] / 10)n[i] := n[i] mod 10
for i in range size of n - 1 to 0, decrease by 1, do
n[i-1] := n[i-1] + quotient of (n[i] / 10)
n[i-1] := n[i-1] + quotient of (n[i] / 10)
n[i] := n[i] mod 10
n[i] := n[i] mod 10
return n if n[0] > 0 otherwise n from index 1 to end
return n if n[0] > 0 otherwise n from index 1 to end
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n):
      n = [0] + n
      n[-1] += 1
      for i in range(len(n) - 1, 0, -1):
         n[i-1] += n[i] // 10
         n[i] = n[i] % 10
      return n if n[0] > 0 else n[1:]
ob = Solution()
print(ob.solve([9,9]))
[9,9]
[1, 0, 0]
Quine in Python

23 Apr, 2020
Quine is a program which takes no input but outputs a copy of its own code. We have discussed quine in C.
The shortest possible quine in python is just a single line of code!
_='_=%r;print _%%_';print _%_
In case of Python3.x
_='_=%r;print (_%%_)';print (_%_)
Explanation:The above code is a classic use of string formatting. Firstly, we are defining a variable _ and assigning it ‘_=%r;print _%%_’. Secondly, we are printing _%_. Here we are printing _ with _ as input to string formatting. So %r in _ gets the value of _. You can even use %s instead of %r. We used double % in ‘_=%r;print _%%_’ to escape %.
But you may say that the below code is the smallest, right!
print open(__file__).read()
You need to note that it is indeed the smallest python program that can print its own source code but it is not a quine because a quine should not use open() function to print out its source code.
This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
vivek_reddy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if a table is empty or not in MySQL using EXISTS

The following is the syntax to check whether a table is empty or not using MySQL EXISTS −
SELECT EXISTS(SELECT 1 FROM yourTableName);
First, let us create a table. The query to create a table is as follows −
mysql> create table ReturnDemo
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ReturnDemo values(100,'Larry');
Query OK, 1 row affected (0.18 sec)
mysql> insert into ReturnDemo values(101,'Bob');
Query OK, 1 row affected (0.28 sec)
mysql> insert into ReturnDemo values(102,'Sam');
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 ReturnDemo;
+------+-------+
| Id   | Name |
+------+-------+
|  100 | Larry |
|  101 |   Bob |
|  102 |   Sam |
+------+-------+
3 rows in set (0.00 sec)
Here is the query to check if MySQL table is empty or not −
mysql> select exists(select 1 from ReturnDemo) AS Output;
+--------+
| Output |
+--------+
|      1 |
+--------+
1 row in set (0.00 sec)
The output 1 tells that the MySQL table isn’t empty.
How to link back out of a folder using the a-href tag?

10 Sep, 2020
Introduction:
Whenever we make a project it is generally distributed among various folders. That is generally done to improve the connectivity and readability for the various web developers working on the same project. For example:
The above classification is just an example but the classification can be bigger. So if you have to call an image from the image folder for the home page or want to call a page in article form the home page it would be a direct URL ie. “Images/gfg.jpg” or “Other Pages/Articles/Gfg Article1.html“. But if you have to call an image from the image folder for the Gfg Article1 page then the general URL will not work. You have to use a relative file path.
To learn more about the relative path please follow this article.
Example 1:
It shows the path of the file present in a folder above the folder of the current web page file. The image file present in a folder called images and current web page file exists inside a subfolder, then the code will be as follows:
<!DOCTYPE html> <html>     <head>         <title>Relative file path</title>     </head>     <body>         <h2>File present in a folder above the current folder</h2>         <img src="../images/gfg.jpg" alt="My Image" style="width:200px">     </body> </html>
Output:
Example 2:
It shows the path of the file present in a folder which is located at the root of the current subdirectories.
<!DOCTYPE html> <html>     <head>         <title>Relative file path</title>     </head>     <body>         <h2>File present in a folder which is located at<br>         the root of the current subdirectories</h2>         <img src="/images/picture.jpg" alt="My Image" style="width:200px">     </body> </html>
Output:
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Count Strings with substring String List

05 Jul, 2022
The classical problem that can be handled quite easily by python and has been also dealt with many times is finding if a string is substring of other. But sometimes, one wishes to extend this on list of strings and find how many strings satisfy condition, and hence then requires to traverse the entire container and perform the generic algorithm. Lets discuss certain ways to perform this task. 
Method #1 : Using list comprehension + len() List comprehension is an elegant ways to perform any particular task as it increases readability in a long run. This task can be performed using naive method and hence can be reduced to list comprehension as well. The len() is used to compute length of list. 
Python3
# Python code to demonstrate# Count Strings with substring String List# using list comprehension + len() # initializing listtest_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original listprint ("The original list is : " + str(test_list)) # initializing substringsubs = 'Geek' # using list comprehension + len()# Count Strings with substring String Listres = len([i for i in test_list if subs in i]) # printing resultprint ("All strings count with given substring are : " + str(res))
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2
  Method #2 : Using filter() + lambda + len() This function can also perform this task of finding the strings with the help of lambda. It just filters out all the strings matching the particular substring and then adds it in a new list. The len() is used to compute length of list. 
Python3
# Python code to demonstrate# Count Strings with substring String List# using filter() + lambda + len() # initializing listtest_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original listprint ("The original list is : " + str(test_list)) # initializing substringsubs = 'Geek' # using filter() + lambda + len()# Count Strings with substring String Listres = len(list(filter(lambda x: subs in x, test_list))) # printing resultprint ("All strings count with given substring are : " + str(res))
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2
simmytarika5
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Java String contains() method with example

31 Oct, 2021
java.lang.String.contains() method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false. Implementation of this method :  
public boolean contains(CharSequence sequence)
{
   return indexOf(sequence.toString()) > -1;
}
Here conversion of CharSequence to a String takes place and then indexOf method is called. The method indexOf returns O or higher number if it finds the String, otherwise -1 is returned. So, after execution, contains() method returns true if sequence of char value exists, otherwise false. Syntax :  
public boolean contains(CharSequence sequence)
Parameter : sequence : This is the sequence of 
characters to be searched.
Exception :
NullPointerException : If seq is null
Example : To check whether the charSequence is present or not.  
Java
// Java program to demonstrate working// contains() methodclass Gfg {     // Driver code    public static void main(String args[])    {        String s1 = "My name is GFG";         // prints true        System.out.println(s1.contains("GFG"));         // prints false        System.out.println(s1.contains("geeks"));    }}
true
false
 
Example : Case sensitive method to check whether given CharSequence is present or not.  
Java
// Java code to demonstrate case// sensitivity of contains() methodclass Gfg1 {     // Driver code    public static void main(String args[])    {        String s1 = "Welcome! to GFG";         // prints false        System.out.println(s1.contains("Gfg"));         // prints true        System.out.println(s1.contains("GFG"));    }}
false
true
 
Further Thoughts : 
This method does not work to search for a character.
This method does not find index of string if it is not present.
For above two functionalities, there is a better function String indexOf 
bhaktiramnan
sweetyty
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Delete Node in a Linked List in Python

Suppose we have a linked list with few elements. Our task is to write a function that will delete the given node from the list. So if the list is like 1 → 3 → 5 → 7 → 9, and after deleting 3, it will be 1 → 5 → 7 → 9.
Consider we have the pointer ‘node’ to point that node to be deleted, we have to perform these operations to delete the node −
node.val = node.next.val
node.next = node.next.next
Let us see the following implementation to get a better understanding −
 Live Demo
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution(object):
   def deleteNode(self, node, data):
      """
      :type node: ListNode
      :rtype: void Do not return anything, modify node in-place instead.
      """
      while node.val is not data:
         node = node.next
      node.val = node.next.val
      node.next = node.next.next
head = make_list([1,3,5,7,9])
ob1 = Solution()
ob1.deleteNode(head, 3)
print_list(head)
linked_list = [1,3,5,7,9]
data = 3
[1, 5, 7, 9, ]
SQL | DEFAULT Constraint

28 Aug, 2020
The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will be added to all new records when no other value is provided.
1. Using DEFAULT on CREATE TABLE :
Syntax :
CREATE TABLE tablename (
Columnname DEFAULT 'defaultvalue' );
Example –To set a DEFAULT value for the “Location” column when the “Geeks” table is created –
CREATE TABLE Geeks (
ID int NOT NULL,
Name varchar(255),
Age int,
Location varchar(255) DEFAULT 'Noida');
INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi');
INSERT INTO Geeks VALUES (5, 'Hema', 27);
INSERT INTO Geeks VALUES (6, 'Neha', 25, 'Delhi');
INSERT INTO Geeks VALUES (7, 'Khushi', 26);
Output –
select *
from Geeks;
2. DROP a DEFAULT Constraint :
Syntax :
ALTER TABLE tablename
ALTER COLUMN columnname 
DROP DEFAULT;
Example –
ALTER TABLE Geeks
ALTER COLUMN Location
DROP DEFAULT;
Let us add 2 new rows in Geeks table :
INSERT INTO Geeks VALUES (8, 'Komal', 24, 'Delhi');
INSERT INTO Geeks VALUES (9, 'Payal', 26);
Note –Dropping the default constraint will not affect the current data in the table, it will only apply to new rows.
Output –
Select * 
from Geeks;
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Interview Questions
SQL | Views
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?
SQL Interview Questions
GATE | GATE-CS-2015 (Set 3) | Question 65

01 Apr, 2019
Consider a CSMA/CD network that transmits data at a rate of 100 Mbps (108 bits per second) over a 1 km (kilometre) cable with no repeaters. If the minimum frame size required for this network is 1250 bytes, what is the signal speed (km/sec) in the cable?(A) 8000(B) 10000(C) 16000(D) 20000Answer: (D)Explanation:
Data should be transmitted at the rate of 100 Mbps.
Transmission Time >= 2*Propagation Time
=> 1250*8 / (100 * 106) <= 2*length/signal_speed
=> signal_speed  <= (2 * 103 * 100 * 106) / (1250 * 8)
                 <= 2 * 10 * (103) km/sec 
                 <= 20000
Refer http://pet.ece.iisc.ernet.in/course/E2223/Problems.pdf for more details.Option (D) is correct.Quiz of this Question
AdarshGoyal
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
How to style icon color, size, and shadow by using CSS ?

11 Feb, 2019
The <i> tag and <span> tag are used widely to add icons on the webpages. To add any icons on the webpages, it need the fontawesome link inside the head tag. The fontawesome icon can be placed by using the fa prefix before the icon’s name.
fontawesome link:
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css
Note: No downloading or installation is required.
Example 1: This example set the size, color and shadow of icon using CSS.
<!DOCTYPE html><html>      <head>    <title>Font Awesome Icons</title>      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">          <style>        h1 {            color: Green;            text-shadow: 2px 3px 6px lime;        }        .icons {            color: red;        }        i {            text-shadow: 2px 4px 6px orange;        }        .fa{            font-size: 50px;        }    </style></head>  <body style = "text-align:center;">      <div class = "icons">                  <h1>GeeksforGeeks</h1>                  <i class="fa fa-cloud"></i>        <i class="fa fa-car"></i>        <i class="fa fa-road"></i>        <i class="fa fa-fire"></i>        <i class="fa fa-bolt"></i>        <i class="fa fa-apple"></i>        <i class="fa fa-ambulance"></i>    </div></body>  </html>                           
Output:
Example:2 This example makes the icons spin and pulse by using fa-spin after the name of the icon.
<!DOCTYPE html><html>      <head>    <title>Font Awesome Icons</title>          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">          <!-- CSS style to set the icon -->    <style>        h1 {            color: Green;            text-shadow: 2px 3px 6px lime;        }        .icons {            color: green;            width: 500px;            height: 200px;            border: 5px solid green;        }        i {            text-shadow:2px 4px 6px cyan;        }        .fa {            font-size:50px;        }        .fa-apple, .fa-car {            font-size:80px;        }    </style></head>  <body style = "text-align:center;">      <div class = "icons">              <h1>GeeksforGeeks</h1>                  <i class="fa fa-spinner fa-pulse"></i>        <i class="fa fa-car"></i>        <i class="fa fa-road"></i>        <i class="fa fa-fire"></i>        <i class="fa fa-bolt"></i>        <i class="fa fa-apple"></i>        <i class="fa fa-star fa-spin"></i>    </div></body>  </html>                    
Output:
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Absolute value of list elements

28 Aug, 2019
Sometimes, while working with Python list, we need to find the absolute number i.e all the elements with a positive magnitude in list. This problem has an application in various domains of Data Science. Let’s discuss certain ways in which this task can be done.
Method #1 : Using list comprehension + abs()This task can be performed using list comprehension technique in which we just iterate each element and keep finding it’s absolute value using the abs().
# Python3 code to demonstrate working of# Absolute value of list elements# using abs() + list comprehension  # initialize listtest_list = [5, -6, 7, -8, -10]  # printing original listprint("The original list is : " + str(test_list))  # Absolute value of list elements# using abs() + list comprehensionres =  [abs(ele) for ele in test_list]  # printing resultprint("Absolute value list : " + str(res))
The original list is : [5, -6, 7, -8, -10]
Absolute value list : [5, 6, 7, 8, 10]

 
Method #2 : Using map() + abs()This task can also be performed using map(). As above, the task of map is to perform the task of extending the absolute number logic to each element in list.
# Python3 code to demonstrate working of# Absolute value of list elements# using map() + abs()  # initialize listtest_list = [5, -6, 7, -8, -10]  # printing original listprint("The original list is : " + str(test_list))  # Absolute value of list elements# using map() + abs()res = list(map(abs, test_list))  # printing resultprint("Absolute value list : " + str(res))
The original list is : [5, -6, 7, -8, -10]
Absolute value list : [5, 6, 7, 8, 10]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
What is the maximum possible value of an integer in Python ?

24 May, 2022
Consider below Python program. 
Python3
# A Python program to demonstrate that we can store# large numbers in Python  x = 10000000000000000000000000000000000000000000x = x + 1print (x)
Output : 
10000000000000000000000000000000000000000001
In Python, value of an integer is not restricted by the number of bits and can expand to the limit of the available memory (Sources : this and this). Thus we never need any special arrangement for storing large numbers (Imagine doing above arithmetic in C/C++).As a side note, in Python 3, there is only one type “int” for all type of integers. In Python 2.7. there are two separate types “int” (which is 32 bit) and “long int” that is same as “int” of Python 3.x, i.e., can store arbitrarily large numbers. 
Python
# A Python program to show that there are two types in# Python 2.7 : int and long int# And in Python 3 there is only one type : int  x = 10print(type(x))  x = 10000000000000000000000000000000000000000000print(type(x))
Output in Python 2.7 :  
<type 'int'>
<type 'long'>
Python3
# A Python3 program to show that there are two types in# Python 2.7 : int and long int# And in Python 3 there is only one type : int  x = 10print(type(x))  x = 10000000000000000000000000000000000000000000print(type(x))
Output in Python 3 :  
<type 'int'>
<type 'int'>
We may want to try more interesting programs like below :  
Python3
# Printing 100 raise to power 100print(100**100)
Advantages of Python - Handling Large Numbers | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersAdvantages of Python - Handling Large Numbers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=76kZGrbSdps" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
mahiemiah35
amartyaniel20
large-numbers
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find next sibling element in Selenium, Python?

We can find a next sibling element from the same parent in Selenium webdriver. This is achieved with the help of xpath locator. It is important to note that it is only possible to traverse from current sibling to the next sibling with the help of xpath.
To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent.
Syntax −
driver.find_element_by_xpath("//div[@class='txt-bx']/following-sibling::p")
Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.
Code Implementation.
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/videotutorials/subscription.php")
# identify next sibling element with following-sibling
l=driver.find_element_by_xpath("//h1/following-sibling::h2")
print("Next Sibling Text: " + l.text)
driver.quit()
Returning Pointer from a Function in Go

17 Jul, 2020
Prerequisite: Pointers in Go and Passing Pointers to Function
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function in Golang. In C/C++, it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable.
Example: In the below program, the line of code(int lv = n1 * n1;) will give warning as it is local to the function. To avoid warnings make it static.
// C++ program to return the// pointer from a function#include <iostream>using namespace std;  // taking a function having// pointer as return typeint* rpf(int);  int main(){      int n = 745;      // displaying the value of n    cout << n << endl;      // calling the function    cout << *rpf(n) << endl;}  // defining functionint* rpf(int n1){      // taking a local variable    // inside the function    int lv = n1 * n1;      // remove comment or make the above    // declaration as static which    // result into successful    // compilation    // static int lv = n1 * n1;      // this will give warning as we    // are returning the address of    // the local variable    return &lv;}
Warnings
prog.cpp: In function ‘int* rpf(int)’:prog.cpp:24:9: warning: address of local variable ‘lv’ returned [-Wreturn-local-addr]int lv = n1 * n1;
Output:
745

The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also get removed which causes the local variables of functions goes out of scope. Making it static will resolve the problem. As static variables have a property of preserving their value even after they are out of their scope.
But the Go compiler is very Intelligent!. It will not allocate the memory on the stack to the local variable of the function. It will allocate this variable on the heap. In the below program, variable lv will have the memory allocated on the heap as Go compiler will perform escape analysis to escape the variable from the local scope.
Example:
// Go program to return the// pointer from the functionpackage main  import "fmt"  // main functionfunc main() {      // calling the function    n := rpf()      // displaying the value    fmt.Println("Value of n is: ", *n)  }  // defining function having integer// pointer as return typefunc rpf() *int {      // taking a local variable    // inside the function    // using short declaration    // operator    lv := 100      // returning the address of lv    return &lv}
Output:
Value of n is:  100

Note: Golang doesn’t provide any support for the pointer arithmetic like C/C++. If you will perform then the compiler will throw an error as invalid operation.
nidhi_biet
Golang
Golang-Pointers
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
View DICOM images using Pydicom and Matplotlib

17 Feb, 2021
Prerequisite: Matplotlib 
DICOM stands for Digital Imaging and Communications in Medicine. DICOM files were introduced to maintain uniformity among varied types of medical image modalities. It is a standard format to view, store, share and retrieve medical images.
Python offers a powerful module, pydicom to work with the DICOM files such as medical images, reports, and radiotherapy objects. pydicom reads modify and write data in DICOM files. 
Run the following commands in the command prompt:
pip install dicom
pip install matplotlib
pydicom enables us to work with DICOM files, in this article we will discuss the mechanism of viewing the DICOM file using pydicom and matplotlib. For reading the DICOM files we use pydicom package and to view the result we use matplotlib.
Import module
Read DICOM file using pydicom.data.data_manager.get_files() method
Syntax : 
pydicom.data.data_manager.get_files(base,pass_dicom)[0]
Parameter:
Base : is base directory to recursively search as a string.
Pattern : By default it is “*”. It is a string pattern which is used to filter the files.
Provide 2 arguments: base and pattern
Display the data as image i.e. on 2D regular raster.
Display image
Note: Enter the location of the dcm file excluding the file name in the base of the variable name and enter the file name in the pass_dicom variable. In this case, the file is stored at a directory named dicom_image as shown:
Download the dcm file from here and rename it to: 1-12.dcm
Compare the path shown in the address bar with the values stored in the variable base and pass_dicom
Program:
Python3
import matplotlib.pyplot as pltimport pydicomimport pydicom.data  # Full path of the DICOM file is passed in basebase = r"C:\Users\Ajit Gupta\Documents\dicom image"pass_dicom = "1-12.dcm"  # file name is 1-12.dcm  # enter DICOM image name for pattern# result is a list of 1 elementfilename = pydicom.data.data_manager.get_files(base, pass_dicom)[0]  ds = pydicom.dcmread(filename)  plt.imshow(ds.pixel_array, cmap=plt.cm.bone)  # set the color map to boneplt.show()
Output:
Python-matplotlib
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add timestamp to excel file in Python

22 Nov, 2021
In this article, we will discuss how to add a timestamp to an excel file using Python.
datetime: This module helps us to work with dates and times in Python.
pip install datetime
openpyxl: It is a Python library used for reading and writing Excel files.
pip install openpyxl
time: This module provides various time-related functions.
Step 1: Create the workbook object and select the active sheet:
wb = Workbook()
ws = wb.active
Step 2 (Optional): Write the heading in cell A1.
# Here column=1 represents column A and row=1 represents first row.
ws.cell(row=1, column=1).value = "Current Date and Time"
Step 3: Use the following command to get the current DateTime from the system.
time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation.
Step 4: Write the DateTime in cell A2.
ws.cell(row=2, column=1).value = time
Step 5: Initiate a sleep of 2 seconds using time.sleep(2)
Step 6: Similarly, get the current datetime again and write it in cell A3. Here you will notice a difference of 2 seconds from the previous DateTime since there was a sleep of 2 seconds in between.
Step 7: Finally, Save the excel workbook with a file name and close the workbook
wb.save('gfg.xlsx')
wb.close()
Below is the full implementation:
Python3
# Import the required modulesimport datetimefrom openpyxl import Workbookimport time    # Main Functionif __name__ == '__main__':        # Create a workbook object    wb = Workbook()      # Select the active sheet    ws = wb.active      # Heading of Cell A1    ws.cell(row=1, column=1).value = "Current Date and Time"      # Cell A2 containing the Current Date and Time    ws.cell(row=2, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')      # Sleep of 2 seconds    time.sleep(2)      # Cell A3 containing the Current Date and Time    ws.cell(row=3, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')    time.sleep(2)      # Cell A4 containing the Current Date and Time    ws.cell(row=4, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')      # Save the workbook with a    # filename and close the object    wb.save('gfg.xlsx')    wb.close()
Output:
abhishek0719kadiyan
Blogathon-2021
Picked
Python datetime-program
Python-excel
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove NA Values from ggplot2 Plot in R

23 Aug, 2021
In this article, we are going to see how to remove the NA values from the ggplot2 plot in the R programming language.
complete.cases() function: This function will be returning a logical vector indicating which cases are complete, i.e., have no missing values.
Syntax: complete.cases(...)
Arguments:
...: a sequence of vectors, matrices, and data frames.
Create dataframe with NA values for demonstration:
Python3
library("ggplot2")data <- data.frame(x = c(4,NA, 10,5, 1, NA, 2, 1, 6, 3),                   y = c(4, 2, NA, NA, 7, 2, 1, 8,NA,10))data
Output:
In this example, we will be plotting a ggplot2 line plot of 10 data points and further with the help of the complete.cases() function we will be removing the NA value to plot the ggplot2 line plot in the R programming language.
R
library("ggplot2")  data <- data.frame(x = c(4,NA, 10,5, 1, NA, 2, 1, 6, 3),                   y = c(4, 2, NA, NA, 7, 2, 1, 8,NA,10))  data_complete=data[complete.cases(data), ]ggplot(data_complete, aes(x, y)) +geom_line()
Output:
In this example, we will be plotting a ggplot2 plot of 5data points and further with the help of the complete.cases() function we will be removing the NA value to plot the ggplot2 plot in the R programming language.
R
library("ggplot2")  data <- data.frame(x =c(7,9,NA,4,NA),                   y=c(10,3,8,5,6) )  data_complete = data[complete.cases(data), ]ggplot(data_complete, aes(x, y)) +geom_point()
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
Joining of Dataframes in R Programming
C# and Multiple Inheritance

Multiple Inheritance isn’t supported in C#. To implement multiple inheritances, use Interfaces.
Here is our interface PaintCost in class Shape −
public interface PaintCost {
   int getCost(int area);
}
The shape is our base class whereas Rectangle is the derived class −
class Rectangle : Shape, PaintCost {
   public int getArea() {
      return (width * height);
   }
   public int getCost(int area) {
      return area * 80;
   }
}
Let us now see the complete code to implement Interfaces for multiple inheritances in C# −
Using System;
namespace MyInheritance {
   class Shape {
      public void setWidth(int w) {
         width = w;
      }
      public void setHeight(int h) {
         height = h;
      }
      protected int width;
      protected int height;
   }
   public interface PaintCost {
      int getCost(int area);
   }
   class Rectangle : Shape, PaintCost {
      public int getArea() {
         return (width * height);
      }

      public int getCost(int area) {
         return area * 80;
      }
   }
   class RectangleDemo {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
         int area;
         Rect.setWidth(8);
         Rect.setHeight(10);
         area = Rect.getArea();
         // Print the area of the object.
         Console.WriteLine("Total area: {0}", Rect.getArea());
         Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider the following statements:
  P: Good mobile phones are not cheap
  Q: Cheap mobile phones are not good

  L: P implies Q
  M: Q implies P
  N: P is equivalent to Q 
Which one of the following about L, M, and N is CORRECT?
(A) Only L is TRUE.(B) Only M is TRUE.(C) Only N is TRUE.(D) L, M and N are TRUEAnswer: (D)Explanation:
Let a and b be two proposition
a: Good Mobile phones.
b: Cheap Mobile Phones.

P and Q can be written in logic as
P: a-->~b
Q: b-->~a.

Truth Table
a   b   ~a  ~b   P   Q
T   T   F    F   F   F
T   F   F    T   T   T
F   T   T    F   T   T
F   F   T    T   T   T

it clearly shows P and Q are equivalent.
so option D is Correct
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to copy a file from one directory to another using PHP ? - GeeksforGeeks

25 Sep, 2019
The copy() function in PHP is used to copy a file from source to target or destination directory. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure.
Syntax:
bool copy( string $source, string $destination, resource $context )
Parameters: This function uses three parameters source, destination and context which are listed below:
$source: It specifies the path of the source file.
$destination: It specifies the path of the destination file or folder.
$context: It specifies the context resource created with stream_context_create() function. It is optional parameter.
Return: It returns a boolean value, either true (on success) or false (on failure).
Examples:
Input : $source = 'Source_file_location'
        $destination = 'Destination_file_location'
        copy( $source, $destination )

Output: true

<?php   // Copy the file from /user/desktop/geek.txt // to user/Downloads/geeksforgeeks.txt'// directory  // Store the path of source file$source = '/user/Desktop/geek.txt';   // Store the path of destination file$destination = 'user/Downloads/geeksforgeeks.txt';   // Copy the file from /user/desktop/geek.txt // to user/Downloads/geeksforgeeks.txt'// directoryif( !copy($source, $destination) ) {     echo "File can't be copied! \n"; } else {     echo "File has been copied! \n"; }   ?> 
Output:
File has been copied!
Reference: https://www.php.net/manual/en/function.copy.php
Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
Comparing two dates in PHP
Kotlin | Plus and minus Operators - GeeksforGeeks

05 Sep, 2019
In Kotlin, plus and minus operators are used to work with the list of objects which is usually referred to as Collections (List, Set, Maps).
As the name suggests, plus operator adds up or concatenates the elements or objects of the given collections. The elements of the first collection remains as it is and the elements of second collection are added with them and the result is then returned in a new read-only collection.
Another one minus operator also contains all the elements of first collection but it removes the elements of second collection, if it is a single element, minus operator removes its occurrence. Just like plus operator result is stored in a new read-only collection.
Syntax:
val result = collection1 + collection2
Kotlin example demonstrates the use of plus and minus operator for a list of elements –
fun main(args: Array<String>) {    // initialize collection with string elements    val firstcollection = listOf("three", "one", "twenty")      // perform plus operator on list    val plusList = firstcollection + "zero"    // perform minus operator on list    val minusList = firstcollection - listOf("three")    println("Result of plus operator is : " + plusList)    println("Result of minus operator is : " + minusList)}
Output:
Result of plus operator is : [three, one, twenty, zero]
Result of minus operator is : [one, twenty]

Plus and minus operators work slightly different on Maps than other collections. Plus operator returns a Map that contains elements from both Maps: a Map on the left and a Pair or another Map on the right.
Minus operator creates a Map from entries of a Map on the left except those with keys from the right-hand side operand.
Kotlin example demonstrates the use of both the operators on Maps –
fun main(args : Array<String>) {    // create and initialize map with keys and values    val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3)    // plus operator to add 4    print("Result of plus operator: ")    println(firstMap + Pair("four", 4))    // minus operator to minus 1    print("Result of minus operator: ")    println(firstMap - "one")}
Output:
{one=1, two=2, three=3, four=4}
{two=2, three=3}

Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
ImageView in Android with Example
How to Build a Weather App in Android?
Android SQLite Database in Kotlin
Suspend Function In Kotlin Coroutines
ScrollView in Android
Kotlin Coroutines on Android
Kotlin extension function
How to Use View Binding in RecyclerView Adapter Class in Android?
Python | Check if all values are 0 in dictionary - GeeksforGeeks

02 Aug, 2019
While working with dictionary, we might come to a problem in which we require to ensure that all the values are 0 in dictionary. This kind of problem can occur while checking status of start or checking for a bug/action that could have occurred. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + dictionary comprehensionThe combination of above functions can be used to perform the following task. The all function checks for each key and dictionary comprehension checks for the 0 value.
# Python3 code to demonstrate working of# Check if all values are 0 in dictionary# Using all() + dictionary comprehension  # Initialize dictionarytest_dict = {'gfg' : 0, 'is' : 0, 'best' : 0}  # Printing original dictionary print("The original dictionary is : " + str(test_dict))  # using all() + dictionary comprehension# Check if all values are 0 in dictionaryres = all(x == 0 for x in test_dict.values())  # printing result print("Does all keys have 0 value ? : " + str(res))
The original dictionary is : {'gfg': 0, 'is': 0, 'best': 0}
Does all keys have 0 value ? : True

 
Method #2 : Using any() + not operatorThe combination of above functions can be used to perform this particular task. Rather than checking for all 0, we check for any one non zero value, and negate the result.
# Python3 code to demonstrate working of# Check if all values are 0 in dictionary# Using any() + not operator  # Initialize dictionarytest_dict = {'gfg' : 0, 'is' : 1, 'best' : 0}  # Printing original dictionary print("The original dictionary is : " + str(test_dict))  # using any() + not operator# Check if all values are 0 in dictionaryres = not any(test_dict.values())  # printing result print("Does all keys have 0 value ? : " + str(res))
The original dictionary is : {'gfg': 0, 'is': 1, 'best': 0}
Does all keys have 0 value ? : False

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
turtle.seth() function in Python

21 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set the orientation of the turtle to to_angle. This method requires only one argument as an angle. 
These two are the Aliases – setheading, seth for this method.
Syntax : turtle.seth(to_angle) or turtle.setheading(to_angle)
Argument: 
to_angle: a number (integer or float)
Set the orientation of the turtle to to_angle. Here are some common directions in degrees (standard – mode) :
0 – east
90 – north
180 – west
270 – south
Below is the implementation of the above method with an example :
Example:
Python3
# import packageimport turtle    # set direction at 0# angle using sethturtle.seth(0)  # motionturtle.forward(80)turtle.write("East")  # back to hometurtle.home()  # set direction at 90# angle using sethadingturtle.setheading(90)  # motionturtle.forward(80)turtle.write("North")  # back to hometurtle.home()  # set direction at 180# angle using sethturtle.seth(180)  # motionturtle.forward(80)turtle.write("West",align="right")  # back to hometurtle.home()  # set direction at 270# angle using setheadingturtle.setheading(270)  # motionturtle.forward(80)turtle.write("South")  # hide the turtleturtle.ht()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.