code-rag-bench/online-tutorials huggingface dataset:
p5.js | windowWidth - GeeksforGeeks

15 Apr, 2019
The windowWidth variable in p5.js is a system variable that is used to store the width of the inner window and it maps to window.innerWidth.Syntax:
windowWidth

Parameters: This function does not accept any parameter.
Below program illustrates the windowWidth variable in p5.js:Example-1:
function setup() {        createCanvas(1000, 400);        // Set text size to 40px    textSize(20);}  function draw() {    background(200);        rect(mouseX, mouseY, 30, 30);        //Use of windowWidth Variable    text("Window Width is " + windowWidth, 30, 40);}
Output:
Example-2:
function setup() {      // set height to window width     width = windowWidth;      //create Canvas of size 380*80     createCanvas(width, 100);}  function draw() {    background(220);    textSize(16);    textAlign(CENTER);    fill(color('Green'));      //use of windowWidth variable    text("windowWidth of Canvas is : "         + width, width / 2, height / 2);}
Output:
Reference: https://p5js.org/reference/#/p5/windowWidth
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python - Join tuple elements in a list

In this article, we are going to learn how to join tuple elements in a list. It's a straightforward thing using join and map methods. Follow the below steps to complete the task.
Initialize list with tuples that contain strings.
Write a function called join_tuple_string that takes a tuple as arguments and return a string.
Join the tuples in the list using map(join_tuple_string, list) method.
Convert the result to list.
Print the result.
# initializing the list with tuples
string_tuples = [('A', 'B', 'C'), ('Tutorialspoint', 'is a', 'popular', 'site', 'for tech learnings')]

# function that converts tuple to string
def join_tuple_string(strings_tuple) -> str:
   return ' '.join(strings_tuple)

# joining all the tuples
result = map(join_tuple_string, string_tuples)

# converting and printing the result
print(list(result))
If you run the above code, then you will get the following result.
['A B C', 'Tutorialspoint is a popular site for tech learnings']

If you have any queries in the article, mention them in the comment section.
Check that the element is clickable or not in Selenium WebDriver

We can check if the element is clickable or not in Selenium webdriver using synchronization. In synchronization, there is an explicit wait where the driver waits till an expected condition for an element is met.
To verify, if the element can be clicked, we shall use the elementToBeClickable condition. A timeout exception is thrown if the criteria for the element is not satisfied till the driver wait time.
WebDriverWait wt = new WebDriverWait(driver, 5);
wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy")));
We have to add - import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait statements to implement ExpectedConditions in our code.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElemntClickable{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      WebElement n=driver.findElement(By.className("mui-btn"));
      n.click();
      // explicit wait
      WebDriverWait wt = new WebDriverWait(driver,6);
      // elementToBeClickable expected criteria
      wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy")));
      System.out.println("Current page title:" + driver.getTitle());
      driver.close();
   }
}
Tryit Editor v3.7

Tryit: HTML JavaScript
How to catch StopIteration Exception in Python?

When an iterator is done, it’s next method raises StopIteration. This exception is not considered an error.
We re-write the given code as follows to catch the exception and know its type.
import sys
try:
z = [5, 9, 7]
i = iter(z)
print i
print i.next()
print i.next()
print i.next()
print i.next()
except Exception as e:
print e
print sys.exc_type

<listiterator object at 0x0000000002AF23C8>
5
9
7
<type 'exceptions.StopIteration'>
C# Convert.ToInt32 Method

Use Convert.ToInt32 method to convert text to an integer.
Firstly, set a string.
string str = "12";
Now, use the Convert.ToInt32() method the above string to number.
Convert.ToInt32(str);
Let us see the complete example.
 Live Demo
using System;
class Program {
   static void Main() {
      string str = "12";
      Console.WriteLine("String: "+str);
      int n = Convert.ToInt32(str);
      Console.WriteLine("Number: "+n);
   }
}
String: 12
Number: 12
Java Program to append a row to a JTable in Java Swing

To append a row, you can use the addRow() method. Ley us first create a table wherein we need to append a row −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Add some columns to the table −
tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Difficulty Level");
Add some rows −
tableModel.insertRow(0, new Object[] { "CSS", "Easy" });
tableModel.insertRow(0, new Object[] { "HTML5", "Easy"});
tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" });
tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" });
tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"});
Now, if you need to append a row to the table we created above, use the addrow() method −
tableModel.addRow(new Object[] { "WordPress", "Easy" });
The following is an example to append a row to a JTable −
package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Difficulty Level");
      tableModel.insertRow(0, new Object[] { "CSS", "Easy" });
      tableModel.insertRow(0, new Object[] { "HTML5", "Easy"});
      tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"});
      // adding a new row
      tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS", "Intermediate" });
      // appending a new row
      tableModel.addRow(new Object[] { "WordPress", "Easy" });
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}
Python program to print odd numbers in a list

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a list iterable as input, we need to display odd numbers in the given iterable.
Here we will be discussing three different approaches to solve this problem.
list1 = [11,23,45,23,64,22,11,24]
# iteration
for num in list1:
   # check
   if num % 2 != 0:
      print(num, end = " ")
11, 23, 45, 23, 11
 Live Demo
list1 = [11,23,45,23,64,22,11,24]
# lambda exp.
odd_no = list(filter(lambda x: (x % 2 != 0), list1))
print("Odd numbers in the list: ", odd_no)
Odd numbers in the list: [11, 23, 45, 23, 11]
 Live Demo
list1 = [11,23,45,23,64,22,11,24]
#list comprehension
odd_nos = [num for num in list1 if num % 2 != 0]
print("Odd numbers : ", odd_nos)
Odd numbers in the list: [11, 23, 45, 23, 11]
In this article, we learned about the approach to find all odd numbers in the list given as input.
How to save matrix created in R as tables in a text file with column names same as the matrix?

Matrix data is sometimes need to be saved as table in text files, the reason behind this is storage capacity of text files. But when we save a matrix as text files in R, the column names are misplaced therefore we need to take care of those names and it can be done by setting column names to the desired value.
> M<-matrix(1:16,nrow=4)
> M
      [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
> colnames(M)<-c("A1","A2","A3","A4")
> rownames(M)<-c("R1","R2","R3","R4")
> M
   A1 A2 A3  A4
R1 1   5  9  13
R2 2   6 10  14
R3 3   7 11  15
R4 4   8 12  16
> write.table(M, 'M.txt')
This file will be saved in documents folder of your system and the output will look like below −
Now, here the column name A1 is above the rows but we don’t want it to be in this form because it is making our last column A4 blank. Therefore, we need to save the matrix M as table in a way that will be same as we have in R. It can be done as shown below −
> write.table(M, 'M.txt', col.names=NA)
Now the saved file should look like the below −
The main objective is to save the file with the column names above their values otherwise it will be confusing to read the table.
Let’s have a look at another example −
:
> new_matrix<-matrix(letters[1:16],nrow=4)
> new_matrix
  [,1] [,2] [,3] [,4]
[1,] "a" "e" "i" "m"
[2,] "b" "f" "j" "n"
[3,] "c" "g" "k" "o"
[4,] "d" "h" "l" "p"
> colnames(new_matrix)<-c("C1","C2","C3","C4")
> rownames(new_matrix)<-c("R1","R2","R3","R4")
> new_matrix
   C1  C2  C3  C4
R1 "a" "e" "i" "m"
R2 "b" "f" "j" "n"
R3 "c" "g" "k" "o"
R4 "d" "h" "l" "p"
> write.table(new_matrix, 'new_matrix.txt', col.names=NA)
The saved file will look like the below one −
Run Python script from Node.js using child process spawn() method?

NodeJs and Python are two main preferred languages among developers and web designers. But there are couple of areas where NodeJs fall short of python are numerical and scientic computation (AI, Machine learning, deep learning etc.). Whereas python provides lots of libraries to work with scientific computing lot easier.
Luckly, we can utilise the python libraries within our nodejs application by running python in the background and return back the result.
For this we are going to use the child_process standard library of NodeJs to spawn a pyton process in the background, do computation and return back the result to our node program.
We are going to write a simple python script which outputs messages to standard output along the way.
#Import library
import sys, getopt, time
def main(argv):
   argument = ''
   usage = 'usage: myscript.py -f <sometext>'
   # parse incoming arguments
   try:
      opts, args = getopt.getopt(argv,"hf:",["foo="])
   except getopt.GetoptError:
      print(usage)
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print(usage)
         sys.exit()
      elif opt in ("-f", "--foo"):
         argument = arg
   # print output
   print("Start : %s" % time.ctime())
   time.sleep( 2 )
   print('Foo is')
   time.sleep( 2 )
   print(argument)
   print("End : %s" % time.ctime())
if __name__ == "__main__":
main(sys.argv[1:])
>python myscript.py -f "Hello, Python"
Start : Wed Feb 20 07:52:45 2019
Foo is
Hello, Python
End : Wed Feb 20 07:52:49 2019
Will generate same output as above, if we try to run with argument:
>python myscript.py --foo "Hello, Python"
>python myscript.py –h
usage: myscript.py -f <Hello, Python>
Our nodejs script will interact with python script by first calling python script then pass script output to the client and render output in the client.
So let’s create a nodejs script, where we’ll try to create a child process using spawn() method.
const path = require('path')
const {spawn} = require('child_process')
/**
   * Run python myscript, pass in `-u` to not buffer console output
   * @return {ChildProcess}
*/
function runScript(){
   return spawn('python', [
      "-u",
      path.join(__dirname, 'myscript.py'),
     "--foo", "some value for foo",
   ]);
}
const subprocess = runScript()
// print output of script
subprocess.stdout.on('data', (data) => {
   console.log(`data:${data}`);
});
subprocess.stderr.on('data', (data) => {
   console.log(`error:${data}`);
});
subprocess.stderr.on('close', () => {
   console.log("Closed");
});
The above script will give output through .on(‘data’, callback). To prevent python from buffering output use the –f flag otherwise data event we’ll will not get print() statements from program until the end of execution.
>node server.js
data:Start : Wed Feb 20 10:56:11 2019
data:Foo is
data:some value for foo
data:End : Wed Feb 20 10:56:15 2019
Closed
Error Handling in Python using Decorators - GeeksforGeeks

21 Sep, 2021
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. 
Example:
Python3
# defining decorator functiondef decorator_example(func):    print("Decorator called")    # defining inner decorator function    def inner_function():            print("inner function")            func()    return inner_function   # defining outer decorator function@decorator_exampledef out_function():    print("outer function")out_function()
Output:
Decorator called
inner function
outer function
The following example shows how a general error handling code without use of any decorator looks like:
Python3
def mean(a,b):    try:        print((a+b)/2)    except TypeError:        print("wrong data types. enter numeric")  def square(sq):    try:        print(sq*sq)    except TypeError:        print("wrong data types. enter numeric")  def divide(l,b):    try:        print(b/l)    except TypeError:                print("wrong data types. enter numeric")mean(4,5)square(21)divide(8,4)divide("two","one")
Output :
4.5
441
0.5
wrong data types. enter numeric
Even though there is nothing logically wrong with the above code but it lacks clarity. To make the code more clean and efficient decorators are used for error handling. The following example depicts how the above code can be more presentable and understandable by use of decorators:
Python3
def Error_Handler(func):    def Inner_Function(*args, **kwargs):        try:            func(*args, **kwargs)        except TypeError:            print(f"{func.__name__} wrong data types. enter numeric")    return Inner_Function@Error_Handlerdef Mean(a,b):        print((a+b)/2)     @Error_Handlerdef Square(sq):        print(sq*sq) @Error_Handlerdef Divide(l,b):        print(b/l)     Mean(4,5)Square(14)Divide(8,4)Square("three")Divide("two","one")Mean("six","five")
Output :
4.5 
196 
0.5 
Square wrong data types. enter numeric 
Divide wrong data types. enter numeric 
Mean wrong data types. enter numeric  
simmytarika5
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Analysis of Algorithms - GeeksforGeeks

29 Jul, 2021
Let the three pegs be A, B and C. The goal is to move n pegs from A to C.
To move n discs from peg A to peg C:
    move n-1 discs from A to B. This leaves disc n alone on peg A
    move disc n from A to C
    move n?1 discs from B to C so they sit on disc n
  f1(n) = 2^n
  f2(n) = n^(3/2)
  f3(n) = nLogn
  f4(n) = n^(Logn)
  f1(n) = 2^n
  f2(n) = n^(3/2)
  f3(n) = nLogn
  f4(n) = n^(Logn)
n = 32, f1 = 2^32, f4 = 32^5 = 2^25
n = 64, f1 = 2^64, f4 = 64^6 = 2^36
...............
............... 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Python Program for Breadth First Search or BFS for a Graph
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is "network ID" and "host ID" in IP Addresses?
What is Transmission Control Protocol (TCP)?
How to Calculate Number of Host in a Subnet?
Bash Scripting - How to check If File Exists
Python Raise Keyword
Python OpenCV - Canny() Function
IntStream sorted() in Java - GeeksforGeeks

06 Dec, 2018
IntStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
Syntax :
IntStream sorted()

Where, IntStream is a sequence of primitive int-valued 
elements. This is the int primitive specialization of Stream.

Exception : If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
Return Value : IntStream sorted() method returns the new stream.
Example 1 : Using IntStream sorted() to sort the numbers in given IntStream.
// Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(10, 9, 8, 7, 6);          // displaying the stream with sorted elements        // using IntStream.sorted() function        stream.sorted().forEach(System.out::println);    }}
6
7
8
9
10

Example 2 : Using IntStream sorted() to sort the random numbers generated by IntStream generator().
// Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream by generating        // random elements using IntStream.generate()        IntStream stream = IntStream.generate(()                          -> (int)(Math.random() * 10000))                             .limit(5);          // displaying the stream with sorted elements        // using IntStream.sorted() function        stream.sorted().forEach(System.out::println);    }}
501
611
7991
8467
9672

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
How to know/change current directory in Python shell?

You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to.
>>> import os
>>> os.chdir('my_folder')
To know the current working directory or pwd use the os module.
>>> import os
>>> print(os.getcwd())
/home/ayush/qna
How to add Matplotlib Colorbar Ticks?

To add ticks to the colorbar, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x, y and z data points using numpy.
Create x, y and z data points using numpy.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Create ticks using numpy in the range of min and max of z.
Create ticks using numpy in the range of min and max of z.
Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks.
Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

x, y = np.mgrid[-1:1:100j, -1:1:100j]
z = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2))

plt.imshow(z, extent=[-1, 1, -1, 1])

ticks = np.linspace(z.min(), z.max(), 5, endpoint=True)

cb = plt.colorbar(ticks=ticks)

plt.show()
What is the use of type = "h" in base R for plotting a graph?

The type = "h" is a graphing argument in base R which is generally used inside a plot function. It helps to generate the vertical lines in the R environment instead of points. For example, if we want to plot values from 1 to 10 then type = "h" will plot the vertical lines starting from X-axis and the upper end of the lines will represent the actual value.
Live Demo
> plot(1:10,type="h")
Live Demo
> plot(rnorm(10),type="h")
How to check the website status code using PowerShell?

Website status code is meant to be the status of the website as if the website request from the client is successful or not if the website is available or any error on the webpage which is causing the handshake failed with the client.
There are various website status codes. Please refer to the below link for them.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
To retrieve the status using PowerShell, we will first connect the webpage using the Invoke-WebRequest command and then we can use the property StatusCode. For example,
$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req
StatusCode : 200
StatusDescription : OK
Content : <!DOCTYPE html>
         <html lang="en-US">
         <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="profile" href="http://gmpg.org/xfn/11">
         <script>...
We can see the status code in the output. Here 200 code means the connection is successful and no error on the webpage.
To retrieve only the status code,
$req.StatusCode
In the case of page unavailability, it throws the exception and the status code can not be captured, so we need to use a try/catch mechanism for handling the exception and generating the status code.
try{
   $req = Invoke-WebRequest -uri "https://theautomationcode.com/Unknownpage" Write-output    "Status Code -- $($req.StatusCode)"
} catch{
   Write-Output "Status Code --- $($_.Exception.Response.StatusCode.Value__) "
}
Status Code --- 404
Bitwise Operators in C

Bitwise operators are used to perform bit-level operations on two variables. Here is the table of bitwise operators in C language,
Here is an example of bitwise operators in C language,
 Live Demo
#include <stdio.h>
int main() {
   int x = 10;
   int y = 28;
   int i = 0;
   printf("Bitwise AND : %d\n", x&y);
   printf("Bitwise OR : %d\n", x|y);
   printf("Bitwise XOR : %d\n", x^y);
   printf("Bitwise Complement : %d,%d\n", ~x,~-y);
   for(i;i<2;i++)
   printf("Right shift by %d: %d\n", i, x>>i);
   for(i;i<=3;++i)
   printf("Left shift by %d: %d\n", i, y<<i);
   return 0;
}
Bitwise AND : 8
Bitwise OR : 30
Bitwise XOR : 22
Bitwise Complement : -11,27
Right shift by 0: 10
Right shift by 1: 5
Left shift by 2: 112
Left shift by 3: 224
Function Overloading and Overriding in PHP

Function overloading is a feature that permits making creating several methods with a similar name that works differently from one another in the type of the input parameters it accepts as arguments.
Let us now see an example to implement function overloading−
 Live Demo
<?php
   class Shape {
      const PI = 3.142 ;
      function __call($name,$arg){
         if($name == 'area')
            switch(count($arg)){
               case 0 : return 0 ;
               case 1 : return self::PI * $arg[0] ;
               case 2 : return $arg[0] * $arg[1];
            }
      }
   }
   $circle = new Shape();
   echo $circle->area(3);
   $rect = new Shape();
   echo $rect->area(8,6);
?>
This will produce the following output−
9.42648
In function overriding, the parent and child classes have the same function name with and number of arguments
Let us now see an example to implement function overriding−
 Live Demo
<?php
   class Base {
      function display() {
         echo "\nBase class function declared final!";
      }
      function demo() {
         echo "\nBase class function!";
      }
   }
   class Derived extends Base {
      function demo() {
         echo "\nDerived class function!";
      }
   }
   $ob = new Base;
   $ob->demo();
   $ob->display();
   $ob2 = new Derived;
   $ob2->demo();
   $ob2->display();
?>
This will produce the following output−
Base class function!
Base class function declared final!
Derived class function!
Base class function declared final!
Python Pandas - Fill NaN values with the specified value in an Index object

To fill NaN values with the specified value in an Index object, use the index.fillna() method in Pandas. At first, import the required libraries −
import pandas as pd
import numpy as np
Creating Pandas index with some NaN values as well −
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

Display the Pandas index −
print("Pandas Index...\n",index)
Fill the NaN with some specific value −
print("\nIndex object after filling NaN value...\n",index.fillna('Amit'))

Following is the code −
import pandas as pd
import numpy as np

# Creating Pandas index with some NaN values as well
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Fill the NaN with some specific value
print("\nIndex object after filling NaN value...\n",index.fillna('Amit'))
This will produce the following output −
Pandas Index...
Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')

Number of elements in the index...
9

The dtype object...
float64

Index object after filling NaN value...
Index([50.0, 10.0, 70.0, 'Amit', 90.0, 50.0, 'Amit', 'Amit', 30.0], dtype='object')
PHP String Data Type

In PHP, a string data type is a non-numeric sequence of charaters.Any character in the ASCII set can be a part of a string. PHP doesn't support UNICODE.
In PHP, literal representation of string can be done with single quotes, double quotes, with heredoc syntax and nowdoc syntax.
//Literal assignment of string value to variable
$var='Hello World'; //Single quotes
$var3="Hello World"; //Double quotes
To embed single quote character inside single quoted string prefix it with '\'. Similarly to embed backslash in single quoted string prefix it with additional backslash. Other escape sequence characters such as \n etc. do not carry any special representation.
Double quoted string treats following escape sequences with their special meaning as follows:
The Heredoc string starts with <<< symbol followed by any identifier of user's choice. From next line, any multiline sequence of characters that may be having any of the above escape sequences. Last line should have same heredoc identifier ending with semicolon.
//Heredoc assignment of string value to variable
public $var = <<< XYZ
Hello World
Welcome to Tutorialspoint
XYZ;
Nowdoc strings are similar to heredoc strings. Difference is that identifier must be enclosed in single quotes and escape sequences inside nowdoc string are not parsed and appear as it is.
//Nowdoc assignment of string value to variable
public $var = <<< 'XYZ'
Hello World
Welcome to Tutorialspoint
XYZ;
Use of separation symbol "_" is avilable since PHP 7.40
Following example shows single quoted string. The escape sequence \n is not parsed and appears as it is
 Live Demo
<?php
$var = 'Hello World.\n Welcome to Tutorialspoint';
echo $var;
?>
This will produce following result −
Hello World.\n Welcome to Tutorialspoint
This Example double quoted string. The escape sequence \n is parsed and text appears in two lines
 Live Demo
<?php
$var = "Hello World.\n Welcome to Tutorialspoint";
echo $var;
?>
This will produce following result −
Hello World.
Welcome to Tutorialspoint
This example shows how to use Heredoc and Nowdoc syntax for string representation
 Live Demo
<?php
//Heredoc
$var = <<< STR
Hello World
Welcome to Tutorialspoint
STR;
echo $var . "\n";
//Nowdoc
$var = <<< 'STR'
Hello World
Welcome to Tutorialspoint
STR;
echo $var;
?>
This will produce following result −
Hello World
Welcome to Tutorialspoint
Hello World
Welcome to Tutorialspoint
This Example shows values of a variable is substiuted in heredoc string. Nowdoc string doesn't make substitution
 Live Demo
<?php
$name = "Mahesh";
$var = <<< STR
Hello $name
Welcome to Tutorialspoint
STR;
echo $var . "\n";
//Nowdoc
$var = <<<'STR'
Hello $name
Welcome to Tutorialspoint
STR;
echo $var;
?>
This will produce following result −
Hello Mahesh
Welcome to Tutorialspoint
Hello $name
Welcome to Tutorialspoint
Replace 0 with null in MySQL?

You can use NULLIF() from MySQL to replace 0 with NULL. The syntax is as follows −
SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Replace0WithNULLDemo
   -> (
   -> Id int NOT NULL auto_increment,
   -> Name varchar(20),
   -> Marks int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.53 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76);
Query OK, 1 row affected (0.16 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86);
Query OK, 1 row affected (0.20 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0);
Query OK, 1 row affected (0.16 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98);
Query OK, 1 row affected (0.19 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0);
Query OK, 1 row affected (0.17 sec)
Display records from the table using select statement. The query is as follows −
mysql> select *from Replace0WithNULLDemo;
The following is the output −
+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  1 | John  | 76    |
|  2 | Carol | 86    |
|  3 | Sam   | 0     |
|  4 | Mike  | 0     |
|  5 | Larry | 98    |
|  6 | Bob   | 0     |
+----+-------+-------+
6 rows in set (0.00 sec)
Let us now replace 0 with NULL. The query is as follows −
mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo;
The following is the output displaying a new column wherein new have replaced 0 with NULL −
+----+-------+-------+---------------------+
| Id | Name  | Marks | ReplaceZeroWithNULL |
+----+-------+-------+---------------------+
| 1  | John  | 76    | 76                  |
| 2  | Carol | 86    | 86                  |
| 3  | Sam   | 0     | NULL                |
| 4  | Mike  | 0     | NULL                |
| 5  | Larry | 98    | 98                  |
| 6  | Bob   | 0     | NULL                |
+----+-------+-------+---------------------+
6 rows in set (0.00 sec)
Creating 3D Plots in R Programming - persp() Function - GeeksforGeeks

10 Dec, 2021
3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot. The persp() function which is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane. persp() is defines as a generic function. Moreover, it can be used to superimpose additional graphical elements on the 3D plot, by lines() or points(), using the function trans3d().
Syntax: persp(x, y, z)
Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z.
Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t).
R
# To illustrate simple right circular conecone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surfacepersp(x, y, z)
Output:
Here in the above code, function seq() to generate a vector of equally spaced numbers. The outer() function to apply the function cone at every combination of x and y.
Python3
# Adding Titles and Labeling Axes to Plotcone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surface# Adding Titles and Labeling Axes to Plotpersp(x, y, z,main="Perspective Plot of a Cone",zlab = "Height",theta = 30, phi = 15,col = "orange", shade = 0.4)
Output: 
Here in the above code, xlab, ylab, and zlab can be used to label the three axes. Theta and phi are viewing direction.
Python3
# Visualizing a simple DEM model z <- 2 * volcano     # Exaggerate the reliefx <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)  # Don't draw the grid lines : border = NApar(bg = "gray")persp(x, y, z, theta = 135, phi = 30,      col = "brown", scale = FALSE,    ltheta = -120, shade = 0.75,      border = NA, box = FALSE)
Output: 
kumar_satyam
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
SoapUI - Request & Response

Here, we will perform the conversion of the currency from INR to USD.
FromCurrency – INR
ToCurrency – USD
Next, enter these inputs in the place of the question mark which will be sent as a request XML. After placing those values into the corresponding XML tags, click 'Submit request' button to check the response.
Upon submitting a request, the web service request is processed by the web-server and sends back a response as shown in the following screenshot.
By reading the response, it can be concluded that 1 unit of INR = 0.0147 units of USD.
SOAP messages are transported by HTTP protocol. To view the HTTP request, click RAW at SoapUI Request window (left side).
The Request is posted to the web-server. Hence, the POST method of Http is used.
The SOAP Request is transported in the body of the http message, which is shown as follows.
POST http://www.webservicex.com/currencyconvertor.asmx HTTP/1.1 
Accept-Encoding: gzip,deflate 
Content-Type: text/xml;charset = UTF-8 
SOAPAction: "http://www.webserviceX.NET/ConversionRate" 
Content-Length: 353 
Host: www.webservicex.com 
Connection: Keep-Alive 
User-Agent: Apache-HttpClient/4.1.1 (java 1.5) 

Click the 'RAW' Tab in SOAP-UI Response Window to understand how the response is sent via HTTP.
After processing the request, the http response code (200) is shown which means it is a success. The web-server has processed it successfully.
The SOAP response is sent back to the client as part of the body of the HTTP message.
HTTP/1.1 200 OK 
Cache-Control: private, max-age = 0 
Content-Type: text/xml; charset = utf-8 
Content-Encoding: gzip 
Vary: Accept-Encoding 
Server: Microsoft-IIS/7.0 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Sun, 22 Jan 2017 19:39:31 GMT 
Content-Length: 316 

Following HTTP codes are used to send in responses by the Web-server and are very useful for debugging.
1xx:
Informational − This means a request was received and there is a continuing process.
2xx:
Success − The action was successfully received, understood, and accepted.
3xx:
Redirection − This means further action must be taken in order to complete the request.
4xx:
Client Error − This means the request contains a bad syntax or cannot be fulfilled.
5xx:
Server Error − The server failed to fulfil an apparently valid request.
 Print
 Add Notes
 Bookmark this page
Get week of month and year using Java Calendar

For using Calendar class, import the following package.
import java.util.Calendar;
Create a Calendar class object.
Calendar cal = Calendar.getInstance();
Now, get the week of month and year using the following fields.
Calendar.WEEK_OF_MONTH
Calendar.WEEK_OF_YEAR
The following is an example.
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
      // current date and time
      System.out.println(cal.getTime().toString());
      // date information
      System.out.println("\nDate Information..........");
      System.out.println("Year = " + cal.get(Calendar.YEAR));
      System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1));
      System.out.println("Date = " + cal.get(Calendar.DATE));
      // week
      System.out.println("Week of month = " + cal.get(Calendar.WEEK_OF_MONTH));
      System.out.println("Week of year = " + cal.get(Calendar.WEEK_OF_YEAR));
      // time information
      System.out.println("\nTime Information..........");
      System.out.println("Hour (24 hour format) : " + cal.get(Calendar.HOUR_OF_DAY));
      System.out.println("Hour (12 hour format) : " + cal.get(Calendar.HOUR));
      System.out.println("Minute : " + cal.get(Calendar.MINUTE));
      System.out.println("Second : " + cal.get(Calendar.SECOND));
      System.out.println("Millisecond : " + cal.get(Calendar.MILLISECOND));
   }
}
Mon Nov 19 14:28:46 UTC 2018

Date Information..........
Year = 2018
Month = 11
Date = 19
Week of month = 4
Week of year = 47

Time Information..........
Hour (24 hour format) : 14
Hour (12 hour format) : 2
Minute : 28
Second : 46
Millisecond : 464
123 Number Flip in Python

Suppose we have an integer n, where only 1, 2, and 3 these digits are present. We can flip one digit to a 3. Then find the maximum number we can make.
So, if the input is like 11332, then the output will be 31332
To solve this, we will follow these steps −
li := a list by digits of n
li := a list by digits of n
for x in range 0 to size of li - 1, doif li[x] is not '3', thenli[x] := '3'return the number by merging digits from li
for x in range 0 to size of li - 1, do
if li[x] is not '3', thenli[x] := '3'return the number by merging digits from li
if li[x] is not '3', then
li[x] := '3'
li[x] := '3'
return the number by merging digits from li
return the number by merging digits from li
return n
return n
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n):
      li = list(str(n))
      for x in range(len(li)):
         if li[x] != '3':
            li[x] = '3'
            return int(''.join(li))
      return n
ob = Solution()
print(ob.solve(11332))
11332
31332
Average numbers in array in C Programming

There are n number of elements stored in an array and this program calculates the average of those numbers. Using different methods.
Input - 1 2 3 4 5 6 7
Output - 4
Explanation - Sum of elements of array 1+2+3+4+5+6+7=28
No of element in array=7
Average=28/7=4
There are two methods
In this method we will find sum and divide the sum by the total number of elements.
Given array arr[] and size of array n
Input - 1 2 3 4 5 6 7
Output - 4
Explanation - Sum of elements of array 1+2+3+4+5+6+7=28
No of element in array=7
Average=28/7=4
#include<iostream>
using namespace std;
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
   int n=7;
   int sum = 0;
   for (int i=0; i<n; i++) {
      sum += arr[i];
   }
   float average = sum/n;
   cout << average;
   return 0;
}
The idea is to pass index of element as an additional parameter and recursively compute sum. After computing sum, divide the sum by n.
Given array arr[], size of array n and initial index i
Input - 1 2 3 4 5
Output - 3
Explanation - Sum of elements of array 1+2+3+4+5=15
No of element in array=5
Average=15/5=3
#include <iostream>
using namespace std;
int avg(int arr[], int i, int n) {
   if (i == n-1) {
      return arr[i];
   }
   if (i == 0) {
      return ((arr[i] + avg(arr, i+1, n))/n);
   }
   return (arr[i] + avg(arr, i+1, n));
}
int main() {
   int arr[] = {1, 2, 3, 4, 5};
   int n = 5;
   cout << avg(arr,0, n) << endl;
   return 0;
}
Pandas Groupby and Computing Median

13 Jul, 2021
The Pandas in Python is known as the most popular and powerful tool for performing data analysis. It because of the beauty of Pandas functionality and the ability to work on sets and subsets of the large dataset. So in this article, we are going to study how pandas Group By functionality works and saves tons of effort while working on a large dataset. Also, we will solve real-world problems using Pandas Group By and Median functionalities.
The groupby() method in pandas splits the dataset into subsets to make computations easier. Generally, groupby() splits the data, applies the functionalities, and then combine the result for us. Let’s take an example if we have data on alcohol consumption of different countries and we want to perform data analysis continent-wise, this problem can be minimized using groupby() method in pandas. It splits the data continent-wise and calculates median using the median() method.
Syntax :
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)  
Example 1: Find the median of alcohol consumption continent-wise on a given dataset.
Dataset: Drinksbycountry.csv
Python3
# import the packagesimport pandas as pd # read Datasetdata = pd.read_csv("drinksbycountry.csv")data.head() # perform groupby on continent and find median# of total_litres_of_pure_alcoholdata.groupby(["continent"])["total_litres_of_pure_alcohol"].median() # perform groupby on continent and find median# of wine_servingdata.groupby(["continent"])["wine_servings"].median()
Output :
median of total_litres_of_pure_alcohol
median of wine_serving
Example 2: Find the median of the total population group by age on a given dataset.
Dataset: WorldPopulationByAge2020.csv
Python3
# import packagesimport pandas as pd # read Datasetdata = pd.read_csv("WorldPopulationByAge2020.csv")data.head() # perform group by AgeGrp and find mediandata.groupby(["AgeGrp"])["PopTotal"].median()
Output :
Group by Age 
anikakapoor
Python pandas-groupby
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Python Program for Min Cost Path

08 Jun, 2022
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.For example, in the following figure, what is the minimum cost path to (2, 2)?  
The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).  
Python
# Dynamic Programming Python implementation of Min Cost Path# problemR = 3C = 3 def minCost(cost, m, n):     # Instead of following line, we can use int tc[m + 1][n + 1] or    # dynamically allocate memory to save space. The following    # line is used to keep te program simple and make it working    # on all compilers.    tc = [[0 for x in range(C)] for x in range(R)]     tc[0][0] = cost[0][0]     # Initialize first column of total cost(tc) array    for i in range(1, m + 1):        tc[i][0] = tc[i-1][0] + cost[i][0]     # Initialize first row of tc array    for j in range(1, n + 1):        tc[0][j] = tc[0][j-1] + cost[0][j]     # Construct rest of the tc array    for i in range(1, m + 1):        for j in range(1, n + 1):            tc[i][j] = min(tc[i-1][j-1], tc[i-1][j],                            tc[i][j-1]) + cost[i][j]     return tc[m][n] # Driver program to test above functionscost = [[1, 2, 3],        [4, 8, 2],        [1, 5, 3]]print(minCost(cost, 2, 2)) # This code is contributed by Bhavya Jain
8
 
Time Complexity: O(m*n)
Auxiliary Space: O(m*n)
Please refer complete article on Dynamic Programming | Set 6 (Min Cost Path) for more details! 
simmytarika5
chandramauliguptach
Python DSA-exercises
Dynamic Programming
Python Programs
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Count number of binary strings without consecutive 1's
Find if a string is interleaved of two other strings | DP-33
Optimal Substructure Property in Dynamic Programming | DP-2
Maximum sum such that no two elements are adjacent
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