code-rag-bench/online-tutorials huggingface dataset:
numpy.argwhere() in Python - GeeksforGeeks

24 Dec, 2018
numpy.argwhere() function is used to find the indices of array elements that are non-zero, grouped by element.
Syntax : numpy.argwhere(arr)
Parameters :arr : [array_like] Input array.
Return : [ndarray] Indices of elements that are non-zero. Indices are grouped by element.
Code #1 :
# Python program explaining# argwhere() function   import numpy as geek  # input arrayin_arr = [[ 2, 0, 7], [ 0, 5, 9]]print ("Input array : ", in_arr)   out_arr = geek.argwhere(in_arr)print ("Output indices of non zero array element: \n", out_arr)
Input array :  [[2, 0, 7], [0, 5, 9]]
Output indices of non zero array element: 
 [[0 0]
 [0 2]
 [1 1]
 [1 2]]

 Code #2 :
# Python program explaining# argwhere() function   import numpy as geek  # input arrayin_arr = geek.arange(8).reshape(4, 2)print ("Input array : ", in_arr)   out_arr = geek.argwhere(in_arr>4)print ("Output indices greater than 4: \n", out_arr)
Input array :  [[0 1]
 [2 3]
 [4 5]
 [6 7]]
Output indices greater than 4: 
 [[2 1]
 [3 0]
 [3 1]]

Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How to insert element as a first child using jQuery?

To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.
You can try to run the following code to learn how to insert element as a first child using jQuery:
Live Demo
<html>

   <head>
      <title>jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         var x = 0;
         $(document).ready(function() {
            $('.add').on('click', function (event) {
               var html = "<div class='child-div'>demo text " + x++ + "</div>";
               $("#parent-div").prepend(html);
            });
         });
      </script>
       
      <style>
         .div {
            margin:10px;
            padding:12px;
            border:2px solid #F38B00;
            width:60px;
         }
      </style>
   </head>
   
<body>
<div id="parent-div">
    <div>Hello World</div>
</div>
<input type="button" value="Click to add" class="add" />
</body>    
</html>
How to delete a file using PHP ? - GeeksforGeeks

28 Mar, 2022
To delete a file by using PHP is very easy. Deleting a file means completely erase a file from a directory so that the file is no longer exist. PHP has an unlink() function that allows to delete a file. The PHP unlink() function takes two parameters $filename and $context. Syntax:
unlink( $filename, $context );
Below programs illustrate the above approach: Program 1: This program uses unlink() function to remove file from directory. Suppose there is a file named as “gfg.txt” 
php
<?php// PHP program to delete a file named gfg.txt// using unlink() function  $file_pointer = "gfg.txt";  // Use unlink() function to delete a fileif (!unlink($file_pointer)) {    echo ("$file_pointer cannot be deleted due to an error");}else {    echo ("$file_pointer has been deleted");} ?>
Output:
gfg.txt has been deleted
Program 2: This program uses unlink() function to delete a file from folder after using some operation. 
php
<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt', 'w+');   // writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer);   // Use unlink() function to delete a fileif (!unlink($file_pointer)) {    echo ("$file_pointer cannot be deleted due to an error");}else {    echo ("$file_pointer has been deleted");}  ?>
Output:
Warning: unlink() expects parameter 1 to be a valid path, resource
given in C:\xampp\htdocs\server.php on line 12
Resource id #3 cannot be deleted due to an error
Note: If the file does not exist then it will display an error.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
tomasmr
seanmckenzie428
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Download file from URL using PHP
How to fetch data from localserver database and display on HTML table using PHP ?
How to run JavaScript from PHP?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass JavaScript variables to PHP ?
How to run JavaScript from PHP?
How to get the Azure VM virtual Network and the Subnet name using PowerShell?

To retrieve the Azure VM virtual network and subnet name, we first need to retrieve the Azure
VM NIC information. To get the Azure VM NIC information, we need to use the Get-AzVM command, and then we can use the NetworkProfile property to retrieve the NIC name as shown below.
PS C:\> $vm = Get-AzVM -Name TestVM
$vmnic = ($vm.NetworkProfile.NetworkInterfaces.id).Split('/')[-1]
Once we have the NIC name stored from the above command in the $vmnic variable, we can retrieve the NIC information using the Get-AzNetworkInterface command as shown below.
$vmnicinfo = Get-AzNetworkInterface -Name $vmnic
To get the Virtual Network name attached to the VM use the below operation on the command.
(($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-3]
To get the Subnet Attached to the VM use the below operation on the command
(($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-1]
The overall script will look like below
$vm = Get-AzVM -Name 'VMName'
$vmnic = ($vm.NetworkProfile.NetworkInterfaces.id).Split('/')[-1]
$vmnicinfo = Get-AzNetworkInterface -Name $vmnic
Write-Output "Virtual Network: : $((($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-3])"
Write-Output "Subnet: $((($vmnicinfo.IpConfigurations.subnet.id).Split('/'))[-1])"
Decryption of Transposition Cipher

In this chapter, you will learn the procedure for decrypting the transposition cipher.
Observe the following code for a better understanding of decrypting a transposition cipher. The cipher text for message Transposition Cipher with key as 6 is fetched as Toners raiCntisippoh.
import math, pyperclip
def main():
   myMessage= 'Toners raiCntisippoh'
   myKey = 6
   plaintext = decryptMessage(myKey, myMessage)
   
   print("The plain text is")
   print('Transposition Cipher')

def decryptMessage(key, message):
   numOfColumns = math.ceil(len(message) / key)
   numOfRows = key
   numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
   plaintext = float('') * numOfColumns
   col = 0
   row = 0
   
   for symbol in message:
      plaintext[col] += symbol
      col += 1
      if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
         col = 0 row += 1 return ''.join(plaintext)
if __name__ == '__main__':
   main()
The cipher text and the mentioned key are the two values taken as input parameters for decoding or decrypting the cipher text in reverse technique by placing characters in a column format and reading them in a horizontal manner.
You can place letters in a column format and later combined or concatenate them together using the following piece of code −
for symbol in message:
   plaintext[col] += symbol
   col += 1
   
   if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
   col = 0
   row += 1
return ''.join(plaintext)
The program code for decrypting transposition cipher gives the following output −

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
PyQt5 - QGridLayout Class

A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. Optionally, a spanning factor for row as well as column, if specified makes the widget wider or taller than one cell. Two overloads of addWidget() method are as follows −
addWidget(QWidget, int r, int c)
Adds a widget at specified row and column
addWidget(QWidget, int r, int c, int rowspan, int columnspan)
Adds a widget at specified row and column and having specified width and/or height
A child layout object can also be added at any cell in the grid.
addLayout(QLayout, int r, int c)
Adds a layout object at specified row and column
The following code creates a grid layout of 16 push buttons arranged in a grid layout of 4 rows and 4 columns.
import sys 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
   grid = QGridLayout()
	
   for i in range(1,5):
      for j in range(1,5):
         grid.addWidget(QPushButton("B"+str(i)+str(j)),i,j)
			
   win.setLayout(grid)
   win.setGeometry(100,100,200,100)
   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()
The code uses two nested for loops for row and column numbers, denoted by variables i and j. They are converted to string to concatenate the caption of each push button to be added at ith row and jth column.
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Difference between a virtual function and a pure virtual function in C++

Following table shows the difference between Virtual and Pure Virtual Function:
 Live Demo
#include <iostream>
using namespace std;
class B {
   public:
      virtual void s() //virtual function {
         cout<<" In Base \n";
      }
};

class D: public B {
   public:
      void s() {
         cout<<"In Derived \n";
      }
};

int main(void) {
   D d; // An object of class D
   B *b= &d;// A pointer of type B* pointing to d
   b->s();// prints"D::s() called"
   return 0;
}
In Derived
 Live Demo
#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
   public:
      void s() {
         cout << " Virtual Function in Derived class\n";
      }
};

int main() {
   B *b;
   D dobj; // An object of class D
   b = &dobj;// A pointer of type B* pointing to dobj
   b->s();// prints"D::s() called"
}
Virtual Function in Derived class
Ruby on Rails - Callback Functions

During the life cycle of an active record object, you can hook into 8 events −
(-) save
(-) valid?
before_validation
before_validation_on_create
(-) validate
(-) validate_on_create
after_validation
after_validation_on_create
before_save
before_create
(-) create
after_create
after_save
class Subscription < ActiveRecord::Base
   before_create :record_signup
   private
   
   def record_signup
      self.signed_up_on = Date.today
   end
end

class Firm < ActiveRecord::Base
   # Destroys the associated clients and 
   # people when the firm is destroyed

   before_destroy{
      |record|Person.destroy_all "firm_id= #{record.id}"
   }

   before_destroy{
      |record|Client.destroy_all "client_of= #{record.id}"
   }
end
Check the Callback Functions link for more detail on Callback Functions.
 Print
 Add Notes
 Bookmark this page
HTTP headers | X-Forwarded-For - GeeksforGeeks

22 Nov, 2019
The HTTP headers are used to communicate between client and server. HTTP headers let the client and server pass additional information with an HTTP request or response. The X-Forwarded-For Header is a request type header and is an alternative and de-facto standard version of the Forwarded header which is used when a client connects to a web server through an HTTP proxy or load balancer for identifying the original IP address. The privacy of the user is put at risk as the sensitive information is revealed by using this header. The HTTP X-Forwarded-For header is used to identify the client’s original IP address. The modified version of the HTTP X-Forwarded-For is HTTP Forwarded header.
Syntax:
X-Forwarded-For: <client>, <proxy>
Note: Multiple proxies are also possible.
Directives: The HTTP X-Forwarded-For accepts two directives as mentioned above and described below:
<client>: It is the IP address of the client.
<proxy>: It is the proxies that request has to go through. If there are multiple proxies then the IP addresses of each successive proxy is listed.
Examples:
This is an example when the request has to go through multiple proxies.X-Forwarded-For: 103.0.113.165, 60.91.3.17, 120.192.338.678
X-Forwarded-For: 103.0.113.165, 60.91.3.17, 120.192.338.678
This is an example when the request has to go through one proxy.X-Forwarded-For: fe80::780b:cd:b91:5b6d%6
X-Forwarded-For: fe80::780b:cd:b91:5b6d%6
To check the X-Forwarded-For in action go to Inspect Element -> Network check the request header for X-Forwarded-For like below.Supported Browsers: Compatibility of the HTTP header X-Forwarded-For for browsers is still unknown.
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Top 10 Angular Libraries For Web Developers
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to Open URL in New Tab using JavaScript ?
Convert from varchar to datetime and compare in MySQL?

For this, you can use STR_TO_DATE(). Let us first create a table −
mysql> create table DemoTable1565
   -> (
   -> ArrivalDatetime varchar(40)
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1565 values('10/01/2019 21:29:35');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1565 values('10/13/2019 4:56:00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1565 values('10/13/2018 12:40:46');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1565 values('10/13/2019 21:30:00');
Query OK, 1 row affected (0.58 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1565;
This will produce the following output −
+---------------------+
| ArrivalDatetime     |
+---------------------+
| 10/01/2019 21:29:35 |
| 10/13/2019 4:56:00  |
| 10/13/2018 12:40:46 |
| 10/13/2019 21:30:00 |
+---------------------+
4 rows in set (0.00 sec)
The current date is as follows −
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-10-13 21:34:14 |
+---------------------+
1 row in set (0.00 sec)
Here is the query to convert from varchar to datetime and compare −
mysql> select * from DemoTable1565 where str_to_date(ArrivalDatetime,'%m/%d/%Y')=curdate();
This will produce the following output −
+---------------------+
| ArrivalDatetime     |
+---------------------+
| 10/13/2019 4:56:00  |
| 10/13/2019 21:30:00 |
+---------------------+
2 rows in set, 4 warnings (0.03 sec)
How to run an infinite loop in Tkinter?

To run an infinite loop in Tkinter, we will use the after method to call a method recursively after a specified time period until the user decides to stop the loop. Let's take a simple example and see how to start and stop an infinite loop.
Import the required libraries and create an instance of tkinter frame.
Import the required libraries and create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Set the size of the frame using win.geometry method.
Next, create a user-defined function "infinite_loop" which will call itself recursively and print a statement on the window.
Next, create a user-defined function "infinite_loop" which will call itself recursively and print a statement on the window.
Define two more user-defined functions, start() and stop(), to control the infinite_loop. Define a global variable "condition". Inside start(), set condition=True and inside stop(), set condition=False.
Define two more user-defined functions, start() and stop(), to control the infinite_loop. Define a global variable "condition". Inside start(), set condition=True and inside stop(), set condition=False.
Create two buttons to call the start() and stop() functions.
Create two buttons to call the start() and stop() functions.
Use the after() method to call the infinite_loop recursively after every 1 second.
Use the after() method to call the infinite_loop recursively after every 1 second.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win=Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Define a function to print something inside infinite loop
condition=True
def infinite_loop():
   if condition:
      Label(win, text="Infinite Loop!", font="Arial, 25").pack()

   # Call the infinite_loop() again after 1 sec win.after(1000, infinite_loop)

def start():
   global condition
   condition=True

def stop():
   global condition
   condition=False

# Create a button to start the infinite loop
start = Button(win, text= "Start the Loop", font="Arial, 12", command=start).pack()
stop = Button(win, text="Stop the Loop", font="Arial, 12", command=stop).pack()

# Call the infinite_loop function after 1 sec.
win.after(1000, infinite_loop)

win.mainloop()
When you run this code, it will produce the following output −
Click the button "Start the Loop" to run the infinite loop which will keep printing "Infinite Loop!" after every second. Click "Stop the Loop" to stop the infinite loop.
Python Number ceil() Method

Python number  method ceil() returns ceiling value of x - the smallest integer not less than x.
Following is the syntax for ceil() method −
import math

math.ceil( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric expression.
x − This is a numeric expression.
This method returns smallest integer not less than x.
The following example shows the usage of ceil() method.
#!/usr/bin/python
import math   # This will import math module

print "math.ceil(-45.17) : ", math.ceil(-45.17)
print "math.ceil(100.12) : ", math.ceil(100.12)
print "math.ceil(100.72) : ", math.ceil(100.72)
print "math.ceil(119L) : ", math.ceil(119L)
print "math.ceil(math.pi) : ", math.ceil(math.pi)
When we run above program, it produces following result −
math.ceil(-45.17) :  -45.0
math.ceil(100.12) :  101.0
math.ceil(100.72) :  101.0
math.ceil(119L) :  119.0
math.ceil(math.pi) : 4.0


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

CSS Style Images
Tryit: Place text in center of an image
Creating a Pandas Series from Dictionary - GeeksforGeeks

06 Jan, 2019
A Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type.
Let’s see how to create a Pandas Series from Dictionary.
In this case, dictionary keys are taken in a sorted order to construct index.
Code #1 : Dictionary keys are given in sorted order.
# import the pandas lib as pdimport pandas as pd  # create a dictionarydictionary = {'A' : 10, 'B' : 20, 'C' : 30}  # create a seriesseries = pd.Series(dictionary)  print(series)
A    10
B    20
C    30
dtype: int64

Code #2 : Dictionary keys are given in unsorted order.
# import the pandas lib as pdimport pandas as pd  # create a dictionarydictionary = {'D' : 10, 'B' : 20, 'C' : 30}  # create a seriesseries = pd.Series(dictionary)  print(series)
B    20
C    30
D    10
dtype: int64

In this case, the values in data corresponding to the labels in the index will be assigned.
Code #1 : Index list is passed of same length as the number of keys present in dictionary.
# import the pandas lib as pdimport pandas as pd  # create a dictionarydictionary = {'A' : 50, 'B' : 10, 'C' : 80}  # create a seriesseries = pd.Series(dictionary, index =['B', 'C', 'A'])  print(series)
B    10
C    80
A    50
dtype: int64

Code #2 : Index list is passed of greater length than the number of keys present in dictionary in this case, Index order is persisted and the missing element is filled with NaN (Not a Number).
# import the pandas lib as pdimport pandas as pd  # create a dictionarydictionary = {'A' : 50, 'B' : 10, 'C' : 80}  # create a seriesseries = pd.Series(dictionary, index =['B', 'C', 'D', 'A'])  print(series)
B    10
C    80
D   NaN
A    50
dtype: float64

pandas-series-program
Picked
Python pandas-series
Python-pandas
Technical Scripter 2018
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
Event bubbling in JavaScript

09 Nov, 2021
Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy. In event bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
Syntax: 
addEventListener(type, listener, useCapture)
type: Use to refer to the type of event.
listener: Function we want to call when the event of the specified type occurs.
userCapture: Boolean value. Boolean value indicates event phase. By Default useCapture is false. It means it is in the bubbling phase.
Example 1: This example shows the working of event bubbling in JavaScript.
HTML
<!DOCTYPE html><html> <head>    <title>        Bubbling Event in Javascript    </title></head> <body>     <h2>Bubbling Event in Javascript</h2>     <div id="parent">      <button>          <h2>Parent</h2>      </button>      <button id="child">           <p>Child</p>       </button>    </div><br>      <script>        document.getElementById("child").addEventListener("click", function () {            alert("You clicked the Child element!");        }, false);         document.getElementById("parent").addEventListener("click", function () {            alert("You clicked the parent element!");        }, false);    </script> </body> </html>
Output:
Output
After Clicking on the Parent button:
After Clicking on the Parent button
After Clicking on the Child button:
After Clicking on the Child button
After Clicking on the Child button
From above example we understand that in bubbling the innermost element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.
mahanteshpatil67
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
What is xpath in Selenium with python?

Xpath is one the locators used in Selenium to identify elements uniquely on a web page. It traverses the DOM to reach the desired element having a particular attribute with/without tagname.
The xpath can represented by the ways listed below −
//tagname[@attribute='value']
//tagname[@attribute='value']
//*[@attribute='value']
//*[@attribute='value']
The xpath can be created by the following methods −
OR & AND expression.
OR & AND expression.
following- sibling expression.
following- sibling expression.
parent.
parent.
child.
child.
ancestor.
ancestor.
self.
self.
descendant.
descendant.
starts-with()
starts-with()
ends-with()
ends-with()
text()
text()
preceding.
preceding.
There are two types of xpath – absolute and relative.
Relative xpath – This path begins from any part of the DOM html. It is represented by double slash // and helps to identify elements from any part of the web page and the xpath expression is not a lengthy one.
It is always better to use relative xpath since we need not start from the root to locate our element. So in case any attributes or their values are getting modified, the probability of getting affected to an incorrect xpath is less.
Syntax −
driver. find_element_by_xpath("//input[@class='gsc-input']")
Absolute xpath – This path starts from the root html to the desired element. It is represented by single slash /. It is lengthier compared to relative xpath and if any of the attributes or their values starting from the root element get changed, then we end up not being able to uniquely identify our desired object on the page.
Syntax −
driver. find_element_by_xpath("/html/body/div/input")
Xpath can perform bidirectional flow which means the traversal can be both ways from parent to child and vice- versa.
Syntax −
driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]")
Syntax −
driver. find_element_by_xpath("//input[@id='job']/parent::div")

In terms of speed, xpath is slower compared to css.
Python | Pandas DataFrame.empty

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.empty attribute checks if the dataframe is empty or not. It return True if the dataframe is empty else it return False.
Syntax: DataFrame.empty
Parameter : None
Returns : bool
Example #1: Use DataFrame.empty attribute to check if the given dataframe is empty or not.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.empty attribute to check if the given dataframe is empty or not.
# check if there is any element# in the given dataframe or notresult = df.empty  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.empty attribute has returned False indicating that the given dataframe is not empty. Example #2: Use DataFrame.empty attribute to check if the given dataframe is empty or not.
# importing pandas as pdimport pandas as pd  # Creating an empty DataFramedf = pd.DataFrame(index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'])  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.empty attribute to check if the given dataframe is empty or not.
# check if there is any element# in the given dataframe or notresult = df.empty  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.empty attribute has returned True indicating that the given dataframe is empty.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
PHP | Fibonacci Series

13 Sep, 2019
The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. In this article, we will learn about how to generate a Fibonacci series in PHP using iterative and recursive way. Given a number n, we need to find the Fibonacci series up to the nth term.Examples:
Input : 10
Output : 0 1  1 2 3 5 8 13 21 34

Input : 15
Output : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

Method 1: Using Recursive wayRecursion is a way where we repeatedly call the same function until a base condition is matched to end the recursion.
<?php  // PHP code to get the Fibonacci series// Recursive function for fibonacci series.function Fibonacci($number){          // if and else if to generate first two numbers    if ($number == 0)        return 0;        else if ($number == 1)        return 1;              // Recursive Call to get the upcoming numbers    else        return (Fibonacci($number-1) +                 Fibonacci($number-2));}  // Driver Code$number = 10;for ($counter = 0; $counter < $number; $counter++){      echo Fibonacci($counter),' ';}?>
Output:
0 1  1 2 3 5 8 13 21 34

Method 2: Using the iterative wayAt first, we initialize the first and second number to 0 and 1. Following this, we print the first and second number. Then we send the flow to the iterative while loop where we get the next number by adding the previous two number and simultaneously we swap the first number with the second and the second with the third.
<?php// PHP code to get the Fibonacci seriesfunction Fibonacci($n){      $num1 = 0;    $num2 = 1;      $counter = 0;    while ($counter < $n){        echo ' '.$num1;        $num3 = $num2 + $num1;        $num1 = $num2;        $num2 = $num3;        $counter = $counter + 1;    }}  // Driver Code$n = 10;Fibonacci($n);?>
Output:
0 1  1 2 3 5 8 13 21 34

PHP-basics
PHP
Web Technologies
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 ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to merge to arrays in C language?

Take two arrays as input and try to merge or concatenate two arrays and store the result in third array.
The logic to merge two arrays is given below −
J=0,k=0
for(i=0;i<o;i++) {// merging two arrays
   if(a[j]<=b[k]){
      c[i]=a[j];
      j++;
   } else {
      c[i]=b[k];
      k++;
   }
}
Given below is the program which shows how to merge two arrays in C programming language −
#include<stdio.h>
#include<stdlib.h>
int main(){
   int a[10],b[10],c[20],m,n,o,i,j,k,temp;
   printf("Enter size of Array1\n");
   scanf("%d",&n);
   printf("Enter size of Array2\n");
   scanf("%d",&m);
   o=m+n; //size of third array
   printf("Enter Elements of Array1\n");
   for(i=0;i<n;i++){
      scanf("%d",&a[i]);
   }
   printf("Enter Elements of Array2\n");
   for(i=0;i<m;i++){
      scanf("%d",&b[i]);
   }
   //sorting first array
   for(i=0;i<n;i++){
      for(j=0;j<n-1-i;j++){
         if(a[j]>a[j+1]){
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
         }
      }
   }
   //sorting second array
   for(i=0;i<m;i++){
      for(j=0;j<m-1-i;j++){
         if(b[j]>b[j+1]){
            temp=b[j];
            b[j]=b[j+1];
            b[j+1]=temp;
         }
      }
   }
   printf("Elements of Array1\n");
   for(i=0;i<n;i++){
      printf("a[%d]=%d\n",i,a[i]);
   }
   printf("Elements of Array2\n");
   for(i=0;i<m;i++){
      printf("b[%d]=%d\n",i,b[i]);
   }
   j=0;
   k=0;
   for(i=0;i<o;i++){ // merging two arrays
      if(a[j]<=b[k]){
         c[i]=a[j];
         j++;
      }
      else{
         c[i]=b[k];
         k++;
      }
   }
   printf("Merged array is :\n");
   for(i=0;i<o;i++){
      printf("c[%d]=%d\n",i,c[i]);
   }
}
When the above program is executed, it produces the following result −
Enter Elements of Array1
1
2
3
4
Enter Elements of Array2
6
8
3
Elements of Array1
a[0]=1
a[1]=2
a[2]=3
a[3]=4
Elements of Array2
b[0]=3
b[1]=6
b[2]=8
Merged array is:
c[0]=1
c[1]=2
c[2]=3
c[3]=3
c[4]=4
c[5]=6
c[6]=8
fork() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
fork - create a child process
#include <sys/types.h>
#include <unistd.h> 
pid_t fork(void); 


pid_t fork(void); 

fork() creates a child process that differs from the parent process only in its
PID and PPID, and in the fact that resource utilizations are set to 0.
File locks and pending signals are not inherited.
Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs
is the time and memory required to duplicate the parent’s page tables,
and to create a unique task structure for the child.
On success, the PID of the child process is returned in the parent’s thread
of execution, and a 0 is returned in the child’s thread of execution.  On
failure, a -1 will be returned in the parent’s context, no child process
will be created, and errno will be set appropriately.
SVr4, 4.3BSD, POSIX.1-2001.
PyQt5 QCalendarWidget – Setting Background Color

21 Jun, 2020
In this article we will see how we can set background color to the QCalendarWidget, setting background color to QCalendarWidget is not like setting border to the other widgets, calendar is widget which has many child i.e component we can set background color to independent component as well. Below is how the calendar with background color will look like
In order to do this we will use setStyleSheet method with the QCalendarWidget object, below is the style sheet code
background-color : lightgreen;

Note : This will remove all the previous style sheet of the calendar
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys  # QCalendarWidget Classclass Calendar(QCalendarWidget):      # constructor    def __init__(self, parent = None):        super(Calendar, self).__init__(parent)      class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()        # method for components    def UiComponents(self):          # creating a QCalendarWidget object        # as Calendar class inherits QCalendarWidget        self.calendar = Calendar(self)          # setting cursor        self.calendar.setCursor(Qt.PointingHandCursor)          # setting size of the calendar        self.calendar.resize(350, 240)          # move the calendar        self.calendar.move(10, 10)          # setting stylesheet        # adding background color to the calendar        self.calendar.setStyleSheet("background-color : lightgreen;")      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
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
Keras - Pre-Trained Models

In this chapter, we will learn about the pre-trained models in Keras. Let us begin with VGG16.
VGG16 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows −
keras.applications.vgg16.VGG16(
   include_top = True, 
   weights = 'imagenet', 
   input_tensor = None, 
   input_shape = None, 
   pooling = None, 
   classes = 1000
)
The default input size for this model is 224x224.
MobileNetV2 is another pre-trained model. It is also trained uing ImageNet.
The syntax to load the model is as follows −
keras.applications.mobilenet_v2.MobileNetV2 (
   input_shape = None, 
   alpha = 1.0, 
   include_top = True, 
   weights = 'imagenet', 
   input_tensor = None, 
   pooling = None, 
   classes = 1000
)
Here,
alpha controls the width of the network. If the value is below 1, decreases the number of filters in each layer. If the value is above 1, increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer.
The default input size for this model is 224x224.
InceptionResNetV2 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows −
keras.applications.inception_resnet_v2.InceptionResNetV2 (
   include_top = True, 
   weights = 'imagenet',
   input_tensor = None, 
   input_shape = None, 
   pooling = None, 
   classes = 1000)
This model and can be built both with ‘channels_first’ data format (channels, height, width) or ‘channels_last’ data format (height, width, channels).
The default input size for this model is 299x299.
InceptionV3 is another pre-trained model. It is also trained uing ImageNet. The syntax to load the model is as follows −
keras.applications.inception_v3.InceptionV3 (
   include_top = True, 
   weights = 'imagenet', 
   input_tensor = None, 
   input_shape = None, 
   pooling = None, 
   classes = 1000
)

Here,
The default input size for this model is 299x299.
Keras is very simple, extensible and easy to implement neural network API, which can be used to build deep learning applications with high level abstraction. Keras is an optimal choice for deep leaning models.
ReactJS useReducer Hook

03 Aug, 2021
The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized.
The useReducer hook takes three arguments including reducer, initial state, and the function to load the initial state lazily.
Syntax:
const [state, dispatch] = useReducer(reducer, initialArgs, init);
Example: Here reducer is the user-defined function that pairs the current state with the dispatch method to handle the state, initialArgs refers to the initial arguments and init is the function to initialize the state lazily.
App.js: Program to demonstrate the use of useReducer Hook:
Javascript
import React, { useReducer } from "react"; // Defining the initial state and the reducerconst initialState = 0;const reducer = (state, action) => {  switch (action) {    case "add":      return state + 1;    case "subtract":      return state - 1;    case "reset":      return 0;    default:      throw new Error("Unexpected action");  }}; const App = () => {    // Initialising useReducer hook  const [count, dispatch] = useReducer(reducer, initialState);  return (    <div>      <h2>{count}</h2>      <button onClick={() => dispatch("add")}>        add      </button>      <button onClick={() => dispatch("subtract")}>        subtract      </button>      <button onClick={() => dispatch("reset")}>        reset      </button>    </div>  );}; export default App;
Output:
AaravChandra
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
ReactJS | Router
How to get character array from string in JavaScript?
How to copy tables or databases from one MySQL server to another MySQL server?

If we want to copy tables or databases from one MySQL server to another, then use the mysqldump with database name and table name.
Run the following command at the source host. This will dump the complete database into dump.txt file.
$ mysqldump -u root -p database_name table_name > dump.txt
password *****
We can copy complete database without using a particular table name as explained above.
Now, ftp dump.txt file on another host and use the following command. Before running this command, make sure we have created database_name on the destination server.
$ mysql -u root -p database_name < dump.txt
password *****
Another way to accomplish this without using an intermediary file is to send the output of the MySQL dump directly over the network to the remote MySQL server. If we can connect to both the servers from the host where the source database resides, use the following command (Make sure we have access to both the servers).
$ mysqldump -u root -p database_name \
| mysql -h other-host.com database_name
In mysqldump, half of the command connects to the local server and writes the dump output to the pipe. The remaining half of the command connects to the remote MySQL server on the other-host.com. It reads the pipe for input and sends each statement to the other-host.com server.
Access to the Password Database in Python

To access the password database, we should use the pwd module. Using this module, we can access users account and password database. The password database entries are like tuple like object.
To use the pwd module, we should import it using.
import pwd
The attributes of the password database are −
Note − Generally, the pw_passwd holds the encrypted passwords. But in the new systems, they use the shadow password system. So now, in the pw_passwd, we can find ‘*’ or ‘x’ symbol only.
Some methods of this module are −
This method will return the password database entry for the given numeric user ID.
This method will return the password database entry for the given user name.
This method will return the all password database entry.
 Live Demo
import pwd
print("Root: " + str(pwd.getpwnam('root')) + '\n') #Password detail for root
for entry in pwd.getpwall():
   print("Name: " + entry[0] + "\t\tShell: " + entry.pw_shell)
$ python3 example.py
Root: pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')

Name: root       Shell: /bin/bash
Name: daemon       Shell: /usr/sbin/nologin
Name: bin       Shell: /usr/sbin/nologin
Name: sys       Shell: /usr/sbin/nologin
Name: sync       Shell: /bin/sync
Name: games       Shell: /usr/sbin/nologin
Name: man       Shell: /usr/sbin/nologin
.......
.......
.......
How to find the primary key of a DB2 table TAB1?

We can find the primary key of any table using the SYSIBM.SYSCOLUMNS table. The SYSIBM.SYSCOLUMNS is a DB2 system table which contains one row for every column of each table. It also contains the data related to the views. Below SQL query can be fired in order to find the primary key of a particular table.
SELECT NAME
FROM
SYSIBM.SYSCOLUMNS
WHERE TBNAME = 'TAB1’
AND KEYSEQ > 0
ORDER BY KEYSEQ ASC;
We will use our table name in the TBNAME column of SYSCOLUMNS table using the WHERE clause and KEYSEQ > 0 will return only primary keys.
Why can't we use the "super" keyword is in a static method in java?

A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference).
Where the "super" keyword in Java is used as a reference to the object of the superclass. This implies that to use "super" the method should be invoked by an object, which static methods are not.
Therefore, you cannot use the "super" keyword from a static method.
In the following Java program, the class "SubClass" contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using this keyword.
class SuperClass{
   protected String name;
}
public class SubClass extends SuperClass {
   private String name;
   public static void setName(String name) {
      super.name = name;
   }
   public void display() {
      System.out.println("name: "+super.name);
   }
   public static void main(String args[]) {
      new SubClass().display();
   }
}
SubClass.java:7: error: non-static variable super cannot be referenced from a static context
   super.name = name;
^
1 error