code-rag-bench/online-tutorials huggingface dataset:
Python Classes

Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
To create a class, use the keyword class:
Create a class named MyClass, with a property named x:
Now we can use the class named MyClass to create objects:
Create an object named p1, and print the value of x:
The examples above are classes and objects in their simplest form, and are 
not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() 
function.
All classes have a function called __init__(), which is always executed when 
the class is being initiated.
Use the __init__() function to assign values to object properties, or other 
operations that are necessary to do when the object 
is being created:
Create a class named Person, use the __init__() function to assign values 
for name and age:
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Objects can also contain methods. Methods in objects are functions that 
belong to the object.
Let us create a method in the Person class:
Insert a function that prints a greeting, and execute it on the p1 object:
Note: The self parameter 
  is a reference to the current instance of the class, and is used to access variables that belong to the class.
The self parameter is a reference to the 
current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can 
call it whatever you like, but it has to be the first parameter of any function 
in the class:
Use the words mysillyobject and abc instead of self:
You can modify properties on objects like this:
Set the age of p1 to 40:
You can delete properties on objects by using the 
del keyword:
Delete the age property from the p1 object:
You can delete objects by using the del keyword:
Delete the p1 object:
class definitions cannot be empty, but if 
you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.
Create a class named MyClass:
 MyClass:
  x = 5

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Shell Script to List all Hidden Files in Current Directory - GeeksforGeeks

29 Nov, 2021
Here we are going to see how to write a script to list all hidden files in the current directory, But before starting we will see how to hide the file in the current directory.
In Linux, the files which start with a period (.) sign are the hidden files. We will write a small script to hide the file by providing the name of the file as an input to the console.
Code:
#!/bin/bash
echo "This is to HIDE any file."
echo "Enter the name of the file  in the current directory:"
read file
# a (.) or period sign is used to hide any file in linux
mv $file .$file
echo ".....The has been hide successfully....."
Give rwx permissions
# chmod 777 hide.sh
Make an empty file so that we could hide it and also check if it is created.
# touch file1.txt
# ls
File has been created.
Execute the script and give the file name as input.
# ./hide.sh
The above code has just changed the name of the original file adding a period (.) at the start.
To find the hidden files we will use the ‘find’ command which has many options which can help us to carry out this process.
Code:
#!/bin/bash
dir=$(pwd)
echo -e "We will list all the Hidden file in the current Directory $dir"
# find <path> <pattern> <action>
find . -type f -name ".*" -ls
Give Permissions and run the file.
# chmod 777 listHide.sh
# ./lishtHide.sh
Hence, the hidden files have been listed. We could also see our “.file1.txt” which we made hidden earlier.
rajeev0719singh
kapoorsagar226
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
Named Pipe or FIFO with example C program
Inserting Elements into a List

Mutable Lists can grow dynamically at runtime. The List.add() function appends the specified value to the end of the List and returns a modified List object. The same is illustrated below.
void main() { 
   List l = [1,2,3]; 
   l.add(12); 
   print(l); 
}
It will produce the following output −
[1, 2, 3, 12]

The List.addAll() function accepts multiple values separated by a comma and appends these to the List.
void main() { 
   List l = [1,2,3]; 
   l.addAll([12,13]); 
   print(l); 
}
It will produce the following output −
[1, 2, 3, 12, 13]

The List.addAll() function accepts multiple values separated by a comma and appends these to the List.
void main() { 
   List l = [1,2,3]; 
   l.addAll([12,13]); 
   print(l); 
} 
It will produce the following output −
[1, 2, 3, 12, 13]

Dart also supports adding elements at specific positions in the List. The insert() function accepts a value and inserts it at the specified index. Similarly, the insertAll() function inserts the given list of values, beginning from the index specified. The syntax of the insert and the insertAll functions are as given below −
List.insert(index,value) 
List.insertAll(index, iterable_list_of _values)

The following examples illustrate the use of the insert() and insertAll() functions respectively.
List.insert(index,value)  
List.insertAll([Itearble])

void main() { 
   List l = [1,2,3]; 
   l.insert(0,4); 
   print(l); 
}
It will produce the following output −
[4, 1, 2, 3]

void main() { 
   List l = [1,2,3]; 
   l.insertAll(0,[120,130]); 
   print(l); 
}
It will produce the following output −
[120, 130, 1, 2, 3]


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Python | Pandas dataframe.first_valid_index()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.first_valid_index() function returns index for first non-NA/null value in the dataframe. In the case of Pandas Series, the first non-NA/null index is returned. In the case of pandas Dataframe, that index is returned which has even a single non-NA/null value.
Note : If all elements are non-NA/null, returns None. Also returns None for empty DataFrame
Syntax: DataFrame.first_valid_index()Returns : scalar : type of index
Example #1: Use first_valid_index() function to find the first non-NA/null index in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[None, None, 2, 4, 5],                    "B":[5, None, None, 44, 2],                   "C":[None, None, None, 1, 5]})  # Print the dataframedf
Now apply the first_valid_index() function.
# applying first_valid_index() function df.first_valid_index()
Output :
Notice, there is non-Na value in the second column of the first row. so the output is 0, indicating that 0th index contain a non-NA value. Example #2: Use first_valid_index() function to find the first non-NA/null index in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[None, None, 2, 4, 5],                   "B":[None, None, None, 44, 2],                   "C":[None, None, None, 1, 5]})  # applying first_valid_index() function df.first_valid_index()
Output :
As we can see in the dataframe, the first two rows are having only NA values. so, the output is 2 Example #3: Use first_valid_index() function to find the first non-NA/null index in a series.
# importing pandas as pdimport pandas as pd  # Creating the seriesser = pd.Series([None, None, "sam", "alex", "sophia", None])  # Print the seriesser
Now apply the first_valid_index() function.
# applying first_valid_index() function ser.first_valid_index()
Output :Output is 2 because 0th and 1st indexes are having null value.
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 update state to re-render the component in ReactJS ?

22 Oct, 2021
The useState() hook in react allows us to declare a state variable that persists during the re-render cycles. If we want to re-render the component then we can easily do so by calling the setState() function which is obtained by destructuring the array returned as a result of calling the useState() hook. Whenever we update the state using the setState() method it re-renders the current component and its child components.
Syntax:
const [state, setState] = useState(initialState)
When we call the setState function it receives the latest state snapshot. Then we can use it inside the setState() function and return the new value to which we want to update the new state value to. 
Syntax:
setState((latestState) => {
    // code logic
    return newState;
})
 
Project setup
To create the new react project use the following command on command-line
npx create-react-app name_of_project
After running this command a new project will be created and your project structure will look as below.
App.js
import { useState } from 'react';  function App() {  const [counter, setCounter] = useState(0);    const handleIncrease = () => {    setCounter((prev) => prev + 1);  };    const handleDecrease = () => {    setCounter((prev) => prev - 1);  };    console.log('Rendering!!!');    return (    <div>      <button onClick={handleDecrease}>         decrease      </button>      <span> {counter} </span>      <button onClick={handleIncrease}>         increase      </button>    </div>  );}  export default App;
Step to run application: To start your application, use the following command on command-line.
npm start
Output: Open the browser and go to http://localhost:3000, you will see the following output.
Explanation: When we click the increase or decrease button, the handleIncrease or handleDecrease functions is called. Inside of these two functions we update the state using setState() function due to which our App component is rendered again and prints a message on the console.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a floating Layout in HTML?

To create a floating layout in HTML, use the CSS Float. Websites have multiple columns to show content. CSS Float is one of the ways to multi-column layouts.
Floating layout is commonly used for layout of websites. This is done using the CSS Float property.
Here’s the floating layout, which you can easily create −
You can try to run the following code to create the above floating layout in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div.mycontent {
            width: 100%;
            border: 1px solid green;
         }
         header, footer {
            padding: 1em;
            color: green;
            background-color: #FAFAFA;
            text-align: left;
         }
         nav {
            float: left;
            max-width: 150px;
            padding: 1em;
         }
         nav ul {
            list-style-type: none;
            padding: 0;
         }
         article {
            margin-left: 10px;
            border-left: 1px solid gray;
            padding: 1em;
            overflow: hidden;
         }
      </style>
   </head>
   <body>
      <div class="mycontent">
         <header>
            <h1>Tutorialspoint.com</h1>
            <h3>Simply Easy Learning</h3>
        </header>
        <nav>
           <ul>
              <li><a href="/tutorialslibrary.htm">Tutorials Library</a></li>
              <li><a href="/videotutorials/index.htm">Video Tutorials</a></li>
              <li><a href="/codingground.htm">Coding Ground</a></li>
              <li><a href="/tutor_connect/index.php">Tutor Connect</a></li>
              <li><a href="/online_dev_tools.htm">Tools</a></li>
           </ul>
        </nav>
        <article>
           <h1>About Us</h1>
           <p>This is demo content.</p>
           <p>This is demo content.</p>
           <p>This is demo content.</p>
           <p>This is demo content.</p>
        </article>
        <footer>Add the footer content here</footer>
    </div>
   </body>
</html>
Greatest digit of a number in JavaScript

We are required to write a JavaScript recursive function that takes in a number and returns the greatest digit in the number.
For example: If the number is 45654356
Then the return value should be 6
The code for this will be −
const num = 45654356;
const greatestDigit = (num = 0, greatest = 0) => {
   if(num){
      const max = Math.max(num % 10, greatest);
      return greatestDigit(Math.floor(num / 10), max);
   };
   return greatest;
};
console.log(greatestDigit(num));
The output in the console will be −
6
How to get all the values of a column in a worksheet in Selenium with python?

We can get all the values of a column in a worksheet in Selenium. Excel is
a spreadsheet which is saved with the .xlsx extension. An excel workbook has
multiple sheets and each sheet consists of rows and columns.
Out of all the worksheets, while we are accessing a particular sheet that is called as
an active sheet. Each cell inside a sheet has a unique address which is a combination
of row and column numbers.
The column number starts from alphabetic character A and row number starts from
the number 1. A cell can contain numerous types of values and they are the main
component of a worksheet.
To work with excel in Selenium with python, we need to take help of OpenPyXL
library. This library is responsible for reading and writing operations on Excel,
having the extensions like xlsx, xlsm, xltm, xltx.
To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel.
To get the values from a particular column, first of all we need to load the entire
workbook by specifying the path where it is located. This is achieved with
load_workbook() method. Next we need to identify the sheet with the help of the
sheet name.
And also we need to identify the column address for which we want to retrieve all
the values. Then we need to iterate through all the cells in that specific column and
get the values with the help of value method.
wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx")
# to identify the sheet with name
sh = wrkbk["Sheet1"]
Coding Implementation to get all the values from a particular column.
import openpyxl
# load excel with its path
wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx"
sh = wrkbk["Sheet1"]
# to iterate through cells in Column A and print value in console
for c in sheet['A']:
   print(c.value)
GATE | GATE-CS-2009 | Question 12 - GeeksforGeeks

28 Jun, 2021
Which of the following statement(s)is / are correct regarding Bellman-Ford shortest path algorithm?
P: Always finds a negative weighted cycle, if one exist s.
Q: Finds whether any negative weighted cycle is reachable 
   from the source. 
(A) P Only(B) Q Only(C) Both P and Q(D) Neither P nor QAnswer: (B)Explanation: Bellman-Ford shortest path algorithm is a single source shortest path algorithm. So it can only find cycles which are reachable from a given source, not any negative weight cycle. Consider a disconnected where a negative weight cycle is not reachable from the source at all.
If there is a negative weight cycle, then it will appear in shortest path as the negative weight cycle will always form a shorter path when iterated through the cycle again and again.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
C# Exceptions (Try..Catch)

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, 
or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).
The try statement allows you to define a block of code to be 
tested for errors while it is being executed.
The catch statement allows you to define a block of code to 
be executed, if an error occurs in the try block.
The try and catch keywords 
come in pairs:
try 
{
  //  Block of code to try
}
catch (Exception e)
{
  //  Block of code to handle errors
}
Consider the following example, where we create an array of three integers:
This will generate an error, because myNumbers[10] does not exist.
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]); // error!
The error message will be something like this:
If an error occurs, we can use try...catch 
to catch the error and execute some code to handle it.
In the following example, we use the variable inside the catch block (e) together with the built-in Message property, which outputs a message that describes the exception:
try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}
The output will be:
You can also output your own error message:
try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}
The output will be:
The finally statement lets you execute code, after try...catch, regardless of the result:
try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}
finally
{
  Console.WriteLine("The 'try catch' is finished.");
}

The output will be:
The throw statement allows you to create a custom error.
The throw statement is used together with an exception class. There are many exception classes available in C#: ArithmeticException, 
FileNotFoundException, 
IndexOutOfRangeException, TimeOutException, etc:
static void checkAge(int age)
{
  if (age < 18)
  {
    throw new ArithmeticException("Access denied - You must be at least 18 years old.");
  }
  else
  {
    Console.WriteLine("Access granted - You are old enough!");
  }
}

static void Main(string[] args)
{
  checkAge(15);
}
The error message displayed in the program will be:
If age was 20, you would not get an exception:
checkAge(20);
The output will be:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Difference between Turbo C++ and Dev C++ - GeeksforGeeks

24 Aug, 2020
1. Turbo C++ (TC) :It is a compiling software used for C and CPP Language. The initial release was in May 1990 but the first stable version released in September 2008. It takes more memory and time to load as compared to Dev C++. Turbo C++ is the compiler from which most of us start our coding life in school/college.
2. Dev C++ :Dev C++ is also used for C and CPP Language. The first stable release was in April 2015. It is fast as compared to Turbo C++. Dev C++ is very much similar to Online Compilers which we used in Coding Competitions.
Let us see the difference between the two using a program. To understand this you must have basic knowledge of C++.
Code in Turbo C++ :
#include <conio.h>#include <iostream.h>void main(){   clrscr();   cout << "Hello Geeks!" ;    getch(); }
Note –This program is written as per standards of Turbo C++ software only. This may not run in online compilers or Dev C++.
Code in Dev C++ :
#include <iostream>using namespace std;int main(){   cout << "Hello Geeks" ;    return 0; } 
Difference between Turbo C++ and Dev C++ :
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Filled area chart using plotly in Python

28 Jun, 2021
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. 
Filled area plot is the easy-to-use, high-level articulation to plotly which completes a variety of types of data and produces easy-to-style figures. Each filled area harmonizes with one value of the column given by the line_group parameter. Filled area charts are most commonly used to show trends, rather than convey specific values. Two popular variations of Area Graphs are: grouped and Stacked Area Graphs.
Syntax: plotly.express.area(data_frame=None, x=None, y=None, line_group=None, color=None, hover_name=None, hover_data=None, custom_data=None, text=None, facet_row=None, facet_col=None, facet_col_wrap=0, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, orientation=None, groupnorm=None, log_x=False, log_y=False, range_x=None, range_y=None, line_shape=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame:  This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame.
x, y: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x and y axis in cartesian coordinates.
color: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.
Example 1:
Python3
import plotly.express as px df = px.data.iris() fig = px.area(df, x="sepal_width", y="sepal_length",            color="species",            hover_data=['petal_width'],) fig.show()
  
Output:
 
 
Example 2:
 
Python3
import plotly.express as pximport numpy as np # creating random data through randomint# function of numpy.randomnp.random.seed(42)   random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) fig = px.area(x = random_x, y = random_y)fig.show()
  
Output:
 
 
Example 3:
 
Python3
import plotly.express as px  df = px.data.tips()   fig = px.area(df, x ='total_bill', y = 'day')fig.show()
  
Output:
 
 
Example 4:
 
Python3
import plotly.express as px  df = px.data.tips()    fig = px.area(df, x ='time', y = 'day',              color="total_bill")fig.show()
  
Output:
 
 
sooda367
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create boxplot using mean and standard deviation in R?

The main statistical parameters that are used to create a boxplot are mean and standard deviation but in general, the boxplot is created with the whole data instead of these values. If we don’t have whole data but mean and standard deviation are available then the boxplot can be created by finding all the limits of a boxplot using mean as a measure of central tendency.
Consider the below data frame:
Live Demo
> df<-data.frame(mean=c(24,25,27,24),sd=c(1.1,2.1,1.5,1.8),Category=as.factor(c("A","B","C","D")))
> df
mean sd Category
1 24 1.1 A
2 25 2.1 B
3 27 1.5 C
4 24 1.8 D
Loading ggplot2 package and creating the boxplot of each category in df:
> library(ggplot2)
> ggplot(df,aes(x=Category))+geom_boxplot(aes(lower=mean-sd,upper=mean+sd,middle=mean,ymin=mean-3*sd,ymax=mean+3*sd),stat="identity")
Scala List length() method with example

13 Aug, 2019
The length() method is utilized to find the length of the list.
Method Definition: def length: Int
Return Type: It returns the length of the list stated.
Example: 1#
// Scala program of length()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(3, 4, 5, 7, 8)                  // Applying length method        val result = m1.length                  // Displays output        println(result)          }} 
5

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

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example
Operators in Scala
Scala Constructors
Enumeration in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
Scala String replace() method with example
Python program to Compute a Polynomial Equation

21 Jun, 2022
The following article contains programs to compute a polynomial equation given that the coefficients of the polynomial are stored in a List.
Examples:
# Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
Input: poly[] = {2, -6, 2, -1}, x = 3
Output: 5

# Evaluate value of 2x3 + 3x + 1 for x = 2
Input: poly[] = {2, 0, 3, 1}, x = 2
Output: 23

# Evaluate value of 2x + 5 for x = 5
Input: poly[] = {2, 5}, x = 5
Output: 15
The equation will be of type:
We will be provided with the value of variable and we have to compute the value of the polynomial at that point. To do so we have two approaches.
Naive Method: Using for loop to compute the value.
Optimised Method: Using Horner’s Method for computing the value.
Naive method:
In this approach, the following methodology will be followed. This is the most naive approach to do such questions.
First coefficient cn will be multiplied with xn
Then coefficient cn-1 will be multiplied with xn-1
The results produced in the above two steps will be added
This will go on till all the coefficient are covered.
Example:
Python3
# 2x3 - 6x2 + 2x - 1 for x = 3poly = [2, -6, 2, -1]x = 3n = len(poly) # Declaring the resultresult = 0 # Running a for loop to traverse through the listfor i in range(n):     # Declaring the variable Sum    Sum = poly[i]     # Running a for loop to multiply x (n-i-1)    # times to the current coefficient    for j in range(n - i - 1):        Sum = Sum * x     # Adding the sum to the result    result = result + Sum # Printing the resultprint(result)
Output:
5
Time Complexity: O(n2)
Optimized method:
Horner’s method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider the example of 2x3 – 6x2 + 2x – 1. The polynomial can be evaluated as ((2x – 6)x + 2)x – 1. The idea is to initialize result as the coefficient of xn which is 2 in this case, repeatedly multiply the result with x and add the next coefficient to result. Finally, return the result. 
Python3
# + poly[1]x(n-2) + .. + poly[n-1]def horner(poly, n, x):     # Initialize result    result = poly[0]     # Evaluate value of polynomial    # using Horner's method    for i in range(1, n):         result = result*x + poly[i]     return result # Driver program to# test above function.  # Let us evaluate value of# 2x3 - 6x2 + 2x - 1 for x = 3poly = [2, -6, 2, -1]x = 3n = len(poly) print("Value of polynomial is:", horner(poly, n, x))
Output:
Value of polynomial is: 5
Time Complexity: O(n)
mitalibhola94
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create links between files in the Linux?

Before creating links, we need to understand what is link and how many types of link in the Linux system.
Links are shortcuts to access a file. It is a connection between file name and actual data in the system. We can say that a link is a pointer to a file.
There are two types of links in the Linux system.
Hard Links
Soft Links or Symbolic links
The hard link points to the index node of a file, the data of which is stored on the system and the size of link is equal to actual file size.
The soft links are just shortcuts of actual files in the Linux system. It does not contain the contents of the actual file.
The ln command is used to create links between files in the Linux system. By default, the ln command creates a hard link of the file for creating symbolic links, we use -s or --symbolic option with the ln command.
The general syntax of the ln command is as follows.
$ ln [OPTION]... [-T] TARGET LINK_NAME
$ ln [OPTION]... TARGET
$ ln [OPTION]... -t TARGET... DIRECTORY
$ ln [OPTION]... -t DIRECTORY TARGET...
Brief description of options available in the ln command.
To create a hard link of the file, we use the command specified by file name and link name as shown in below.
$ ln file.txt link.txt
The created link will be a hard link because by default, using the ln command the hard link will be created and the size of the link is equal to the actual size of the file.
To create symbolic link or soft link of a file, we use -s or --symbolic option with the ln command in the Linux system as shown in below.
$ ln --symbolic file.txt link.txt
The color of the symbolic link is different from the actual file or hard link, and also the contents of the file are only in the actual file the symbolic link is just pointing to the file.
Conditional upsert (multiple insert) when updating document in MongoDB?

For multiple write operations, use bulkWrite() in MongoDB. Let us create a collection with documents −
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 21 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f428bbc41e36cc3cae83")
}
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 23 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f429bbc41e36cc3cae84")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 22 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f42abbc41e36cc3cae85")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 21 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75f42abbc41e36cc3cae86")
}
Display all documents from a collection with the help of find() method
> db.demo428.find();
This will produce the following output −
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }
Following is the query for conditional upsert (insert) when updating document in MongoDB −
> db.demo428.bulkWrite(
...    [
...       { "updateOne": {
...          "filter": { "Name": "David", "Age": 22 },
...          "update": { "$set": { "Info": {Name:"John"} } }
...       }},
...       { "insertOne": {
...          "document": { "Name": "Carol", "Age": 22, "Info": {Name:"John"}}
...       }}
...    ],
...    { "ordered": false }
... )
{
   "acknowledged" : true,
   "deletedCount" : 0,
   "insertedCount" : 1,
   "matchedCount" : 1,
   "upsertedCount" : 0,
   "insertedIds" : {
      "1" : ObjectId("5e75f448bbc41e36cc3cae87")
   },
   "upsertedIds" : {
   }
}
Display all documents from a collection with the help of find() method −
> db.demo428.find();
This will produce the following output −
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22, "Info" : { "Name" : "John" } }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e75f448bbc41e36cc3cae87"), "Name" : "Carol", "Age" : 22, "Info" : { "Name" : "John" } }
How to share secondary Y-axis between subplots in Matplotlib?

To share secondary Y-axis between subplots in matplotlib, we can take the following steps −
Create x for data points.
Create x for data points.
Add a subplot to the current figure, with nrows=2, ncols=1, at index=1 (ax0)
Add a subplot to the current figure, with nrows=2, ncols=1, at index=1 (ax0)
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax1).
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax1).
Add a subplot to the current figure, with nrows=2, ncols=1 at index=2 (ax2)
Add a subplot to the current figure, with nrows=2, ncols=1 at index=2 (ax2)
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax3).
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax3).
Using get_shared_y_axes() method, return a reference to the shared axes Grouper object for Yaxis.
Using get_shared_y_axes() method, return a reference to the shared axes Grouper object for Yaxis.
Create curves c1, c2, c3 and c4 with different colors, x and y data points.
Create curves c1, c2, c3 and c4 with different colors, x and y data points.
To move the legend box to the upper left of the figure, use the legend method with bbox_to_anchor.
To move the legend box to the upper left of the figure, use the legend method with bbox_to_anchor.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
ax0 = plt.subplot(211)
ax1 = ax0.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis.
ax2 = plt.subplot(212)
ax3 = ax2.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis.
ax1.get_shared_y_axes().join(ax1, ax3)
c1, = ax0.plot(x, np.sin(x), c='red')
c2, = ax1.plot(x, np.cos(x), c='blue')
c3, = ax2.plot(x, np.tan(x), c='green')
c4, = ax3.plot(x, np.exp(x), c='yellow')
plt.legend([c1, c2, c3, c4], ["y=sin(x)", "y=cos(x)", "y=tan(x)", "y=exp(x)"],
loc = "upper left", bbox_to_anchor=(.070, 2.25))
plt.show()
Output of python program | Set 2 - GeeksforGeeks

09 Mar, 2022
Difficulty level : IntermediatePredict the output of following Python Programs. Program 1:  
Python3
class Acc:    def __init__(self, id):        self.id = id        id = 555 acc = Acc(111)print (acc.id)
Output:
111
Explanation: Instantiation of the class “Acc” automatically calls the method __init__ and passes the object as the self parameter. 111 is assigned to data attribute of the object called id. The value “555” is not retained in the object as it is not assigned to a data attribute of the class/object. So, the output of the program is “111”  Program 2:  
Python3
for i in  range(2):    print (i) for i in range(4,6):    print (i)
Output:  
0
1
4
5
Explanation: If only single argument is passed to the range method, Python considers this argument as the end of the range and the default start value of range is 0. So, it will print all the numbers starting from 0 and before the supplied argument. For the second for loop the starting value is explicitly supplied as 4 and ending is 5.  Program 3:  
Python3
values = [1, 2, 3, 4]numbers = set(values) def checknums(num):    if num in numbers:        return True    else:        return False for i in  filter(checknums, values):    print (i)
Output:  
1
2
3
4
Explanation: The function “filter” will return all items from list values which return True when passed to the function “checknums”. “checknums” will check if the value is in the set. Since all the numbers in the set come from the values list, all of the original values in the list will return True. Program 4:  
Python3
counter = {} def addToCounter(country):    if country in  counter:        counter[country] += 1    else:        counter[country] = 1 addToCounter('China')addToCounter('Japan')addToCounter('china') print (len(counter))
Output:  
3
Explanation: The task of “len” function is to return number of keys in a dictionary. Here 3 keys are added to the dictionary “country” using the “addToCounter” function. Please note carefully – The keys to a dictionary are case sensitive. Try yourself: What happens If same key is passed twice??This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jeakansh
amartyaghoshgfg
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java programs | Set 13 (Collections)
Output of Java Program | Set 3
Different ways to copy a string in C/C++
Output of C++ programs | Set 34 (File Handling)
Output of Java program | Set 28
Runtime Errors
Output of Java program | Set 5
Output of Java Programs | Set 12
Output of Java Program | Set 20 (Inheritance)
Output of Java Program | Set 7
Best way to change the date format in MySQL SELECT?

The best way to change the date format in MySQL SELECT is as follows
SELECT DATE_FORMAT(yourColumnName, "%d/%m/%Y %H:%i") AS anyAliasName FROM yourTableName WHERE yourCondition;
To understand the above concept, let us create a table. The query to create a table is as follows
mysql> create table bestDateFormatDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > ArrivalDateTime datetime
   - > );
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into bestDateFormatDemo(ArrivalDateTime) values(now());
Query OK, 1 row affected (0.11 sec)
mysql> insert into bestDateFormatDemo(ArrivalDateTime) values(date_add(now(),interval -2
year));
Query OK, 1 row affected (0.33 sec)
mysql> insert into bestDateFormatDemo(ArrivalDateTime) values('2014-01-31 13:45:56');
Query OK, 1 row affected (0.15 sec)
mysql> insert into bestDateFormatDemo(ArrivalDateTime) values('2016-02-11 12:40:30');
Query OK, 1 row affected (0.17 sec)
mysql> insert into bestDateFormatDemo(ArrivalDateTime) values('2018-12-31 12:59:59');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from bestDateFormatDemo;
The following is the output
+----+---------------------+
| Id | ArrivalDateTime     |
+----+---------------------+
|  1 | 2019-02-22 22:50:10 |
|  2 | 2017-02-22 22:50:28 |
|  3 | 2014-01-31 13:45:56 |
|  4 | 2016-02-11 12:40:30 |
|  5 | 2018-12-31 12:59:59 |
+----+---------------------+
5 rows in set (0.00 sec)
Here is the query to change the date format in MySQL select statement
mysql> SELECT DATE_FORMAT(ArrivalDateTime, "%d/%m/%Y %H:%i")AS
changeDateFormat FROM bestDateFormatDemo WHERE Id IN(1,2,3,4,5);
The following is the output
+------------------+
| changeDateFormat |
+------------------+
| 22/02/2019 22:50 |
| 22/02/2017 22:50 |
| 31/01/2014 13:45 |
| 11/02/2016 12:40 |
| 31/12/2018 12:59 |
+------------------+
5 rows in set (0.28 sec)
If you want the hour in 12-hour format, use ‘h’ instead of ‘H’.
The query is as follows
mysql> SELECT DATE_FORMAT(ArrivalDateTime, "%d/%m/%Y %h:%i")AS
changeDateFormat FROM bestDateFormatDemo WHERE Id IN(1,2,3,4,5);
The following is the output
+------------------+
| changeDateFormat |
+------------------+
| 22/02/2019 10:50 |
| 22/02/2017 10:50 |
| 31/01/2014 01:45 |
| 11/02/2016 12:40 |
| 31/12/2018 12:59 |
+------------------+
5 rows in set (0.00 sec)
C program to change the file name using rename() function

The rename function changes a file or directory from oldname to newname. This operation is just like a move operation. Hence, we can also use this rename function to move a file.
This function is present in stdio.h library header files.
The syntax of rename function is as follows −
int rename(const char * oldname, const char * newname);
It accepts two parameters. One is oldname and another is newname.
It accepts two parameters. One is oldname and another is newname.
These two parameters are pointer to constant character, which define old and new name of file.
These two parameters are pointer to constant character, which define old and new name of file.
If file renamed is successful, then it returns zero otherwise, it returns a non-zero integer.
If file renamed is successful, then it returns zero otherwise, it returns a non-zero integer.
During the rename operation if that newname file is already present, then it replaces that already existing file with this new file.
During the rename operation if that newname file is already present, then it replaces that already existing file with this new file.
Refer an algorithm given below for changing the file name by using rename() function.
Step 1 − Declare variables
Step 2 − Enter old file path
Step 3 − Enter new file path
Step 4 − check rename(old, new) == 0
If yes print file renamed successfully
Else
Unable to rename.
Following is the C program to change the file name by using rename() function −
 Live Demo
#include <stdio.h>
int main(){
   char old[100], new[100];
   printf("Enter old file path: ");
   scanf("%s", old);
   printf("Enter new file path: ");
   scanf("%s", new);
   if (rename(old, new) == 0){
      printf("File renamed successfully.\n");
   }
   else{
      printf("Unable to rename files\n");
   }
   return 0;
}
When the above program is executed, it produces the following result −
Run 1:
Enter old file path: test.exe
Enter new file path: test1.exe
File renamed successfully.

Run 2:
Enter old file path: priya.c
Enter new file path: bhanu.c
Unable to rename files
Sort an Array of string using Selection sort in C++

The Selection Sort algorithm sorts an exhibit by more than once finding the base component from the unsorted part and putting it toward the start. In each emphasis of determination sort, the base component from the unsorted subarray is picked and moved to the arranged subarray.
 Live Demo
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_LEN 50
void selectionSort(char arr[][50], int n){
   int i, j, mIndex;
   // Move boundary of unsorted subarray one by one
   char minStr[50];
   for (i = 0; i < n-1; i++){
      // Determine minimum element in unsorted array
      int mIndex = i;
      strcpy(minStr, arr[i]);
      for (j = i + 1; j < n; j++){
         // check whether the min is greater than arr[j]
         if (strcmp(minStr, arr[j]) > 0){
            // Make arr[j] as minStr and update min_idx
            strcpy(minStr, arr[j]);
            mIndex = j;
         }
      }
      // Swap the minimum with the first element
      if (mIndex != i){
         char temp[50];
         strcpy(temp, arr[i]); //swap item[pos] and item[i]
         strcpy(arr[i], arr[mIndex]);
         strcpy(arr[mIndex], temp);
      }
   }
}
int main(){
   char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"};
   int n = sizeof(arr)/sizeof(arr[0]);
   int i;
   cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n";
   selectionSort(arr, n);
   cout << "\nSelection Sorted is::\n";
   for (i = 0; i < n; i++)
      cout << i << ": " << arr[i] << endl;
   return 0;
}
This above C++ program initially chooses the smallest component in the exhibit and swaps it with the principal component in the cluster. Next, it swaps the second littlest component in the
cluster with the subsequent component, etc. In this manner for each pass, the smallest component in the exhibit is chosen and put in its legitimate situation until the whole cluster is arranged. Finally, the section sort method sorts the given string in ascending order as follows;
Given string is:: Tom, Boyaka, Matt, Luke
Selection Sorted::
Boyaka
Luke
Matt
Tom
How to find the index of values in an R data frame column if they occur once?

To find the index of values in an R data frame column if they occur once, we can follow the below steps −
First of all, create a data frame.
First of all, create a data frame.
Then, use which function along with duplicated function and single square brackets for subsetting to find the index of values in a column if they occur once.
Then, use which function along with duplicated function and single square brackets for subsetting to find the index of values in a column if they occur once.
Let’s create a data frame as shown below −
x<-sample(1:10,25,replace=TRUE)
df1<-data.frame(x)
df1
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
    x
1   5
2   3
3  10
4   1
5   9
6   8
7   8
8   7
9   4
10  6
11  1
12  6
13  5
14  5
15  7
16  5
17  1
18  2
19  1
20  3
21  7
22  7
23  9
24 10
25  1
Find the index of values in a column if they occur once
Using which function along with duplicated function and single square brackets for subsetting to find the index of values in column x of data frame df1 if they occur once −
x<-sample(1:10,25,replace=TRUE)
df1<-data.frame(x)
which(!(df1$x %in% df1$x[duplicated(df1$x)]))
[1] 9 18

Let’s create a data frame as shown below −
y<-round(rnorm(25),1)
df2<-data.frame(y)
df2
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
     y
1   2.1
2  -1.0
3  -1.6
4   1.5
5   0.5
6   1.4
7   0.2
8   0.6
9   0.2
10  0.6
11  0.4
12  0.2
13  0.4
14  1.6
15  1.4
16 -1.6
17 -1.1
18  0.4
19  1.0
20  0.3
21  0.4
22 -0.7
23 -0.9
24 -1.6
25 -0.4
Find the index of values in a column if they occur once
Using which function along with duplicated function and single square brackets for subsetting to find the index of values in column y of data frame df2 if they occur once −
y<-round(rnorm(25),1)
df2<-data.frame(y)
which(!(df2$y %in% df2$y[duplicated(df2$y)]))
[1] 1 2 4 5 14 17 19 20 22 23 25
Java Examples - Add Text to Image

How to add text to an image using Java.
Following is the program to add text to an image using Java.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class AddingTextToImage {
   public static void main(String args[]) {

      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      //Reading the Image from the file and storing it in to a Matrix object
      String file = "C:/opencv/logo.jpg";
      Mat matrix = Imgcodecs.imread(file);

      //Adding Text
      Imgproc.putText(matrix,        //Matrix obj of the image
         "Tutorialspoint",           //Text to be added
         new Point(100, 390),        //point
         Core.FONT_HERSHEY_SIMPLEX , //front face
         1,                          //front scale
         new Scalar(0, 0, 0),        //Scalar object for color
         5);                         //Thickness

      Imgcodecs.imwrite("C:/opencv/addingTextOP.jpg", matrix);
      System.out.println("Image Processed");
   }
} 
 Print
 Add Notes
 Bookmark this page