code-rag-bench/online-tutorials huggingface dataset:
Print Postorder traversal from given Inorder and Preorder traversals

Given with inorder and preorder of a tree program must find the postroder traversal and print the same
Input:
Inorder traversal in[] = {4, 2, 5, 1, 3, 6}
Preorder traversal pre[] = {1, 2, 4, 5, 3, 6}
Output:
Postorder traversal post[] = {4, 5, 2, 6, 3, 1}
START
Step 1 -> declare function as find_value(int p, int in_order[], int n)
   Loop For i=0 and i<n and ++i
      IF in_order[i]==p
         Return i
      End IF
   End
Step 2 -> declare function as postorder(int pre_order[], int in_order[], int n)
   Declare int variable as root = find_value(pre_order[0], in_order, n)
   IF root!=0
      Call postorder(pre_order+1, in_order, root)
   End
   IF root !=n-1
      Call postorder(pre_order+root+1, in_order+root+1,n-root-1)
   End
   Print pre_order[0]
End
Step 3 -> goto main()
   Declare int pre_order[] = {1, 2, 4, 5, 3, 6}
   Declare int in_order[] = {4, 2, 5, 1, 3, 6}
   Declare int size = sizeof(pre_order)/sizeof(pre_order[0])
   Call postorder(pre_order, in_order, size)
STOP
#include <stdio.h>
int find_value(int p, int in_order[], int n) {
   for (int i = 0; i < n; ++i) {
      if (in_order[i] == p) {
         return i;
      }
   }
   return -1;
}
int postorder(int pre_order[], int in_order[], int n) {
   int root = find_value(pre_order[0], in_order, n);
   if(root !=0 )
      postorder(pre_order+1, in_order, root);
   if (root != n-1)
      postorder(pre_order+root+1, in_order+root+1, n-root-1);
   printf("%d ", pre_order[0]);
}
int main(int argc, char const *argv[]) {
   int pre_order[] = {1, 2, 4, 5, 3, 6};
   int in_order[] = {4, 2, 5, 1, 3, 6};
   int size = sizeof(pre_order)/sizeof(pre_order[0]);
   postorder(pre_order, in_order, size);
   return 0;
}
if we run the above program then it will generate the following output
4 5 2 6 3 1
new and delete operators in C++ - GeeksQuiz

29 Jul, 2020
int **arr = new int *[10]; 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Alter Multiple Columns at Once in SQL Server?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Python Program to Implement Shell Sort

When it is required to implement shell sort, a function is defined, and this takes a list and the length of the list as arguments. This list is sorted up to a specific number of elements, wherein the number of elements is the largest value. This is done until the number of elements has the smallest value.
This is done for all sub-lists in the list, and all these sub-lists are sorted.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
Below is a demonstration of the same −
Live Demo
def shell_sort(my_list, list_len):
   interval = list_len // 2
   while interval > 0:
      for i in range(interval, list_len):
         temp = my_list[i]
         j = i
         while j >= interval and my_list[j - interval] > temp:
            my_list[j] = my_list[j - interval]
            j -= interval
         my_list[j] = temp
      interval //= 2

my_list = [ 45, 31, 62, 12, 89, 5, 9, 8]
list_len = len(my_list)
print ("The list before sorting is :")
print(my_list)
shell_sort(my_list, list_len)
print ("\nThe list after performing shell sorting is :")
print(my_list)
The list before sorting is :
[45, 31, 62, 12, 89, 5, 9, 8]

The list after performing shell sorting is :
[5, 8, 9, 12, 31, 45, 62, 89]
A method named 'shell_sort' is defined, that takes the list, and the length of the list as arguments.
The 'interval' variable is defined by using the '//' bitwise operator.
It performs floor division.
It rounds down the value to the nearest whole number.
The list is iterated over, and a temporary variable is created.
The 'interval' variable is compared with every index of the list, and every element in the list is compared to the temporary variable.
The 'interval' variable is again used to perform floor division.
The list is defined, and is displayed on the console.
The method is called by passing this list, and its length.
The output is displayed on the console.
How to enable Session in C# ASP.NET Core?

Session is a feature in ASP.NET Core that enables us to save/store the user data.
Session stores the data in the dictionary on the Server and SessionId is used as a key.
The SessionId is stored on the client at cookie. The SessionId cookie is sent with
every request.
The SessionId cookie is per browser and it cannot be shared between the browsers.
There is no timeout specified for SessionId cookie and they are deleted when the
Browser session ends.
At the Server end, session is retained for a limited time. The default session timeout at
the Server is 20 minutes but it is configurable.
Microsoft.AspNetCore.Session package provides middleware to manage the sessions in ASP.NET Core. To use session in our Application, we need to add this package as a dependency in project.json file.
The next step is to configure session in Startup class.
We need to call "AddSession" method in ConfigureServices method of startup class.
The "AddSession" method has one overload method, which accepts various session
options such as Idle Timeout, Cookie Name and Cookie Domain etc.
If we do not pass the session options, the system will take the default options
public class Startup {
   public void Configure(IApplicationBuilder app){
      app.UseSession();
      app.UseMvc();
      app.Run(context => {
         return context.Response.WriteAsync("Hello World!");
      });
   }
   public void ConfigureServices(IServiceCollection services){
      services.AddMvc();
      services.AddSession(options => {
         options.IdleTimeout = TimeSpan.FromMinutes(60);
      });
   }
}
How to access the session
public class HomeController : Controller{
   [Route("home/index")]
   public IActionResult Index(){
      HttpContext.Session.SetString("product","laptop");
      return View();
   }
   [Route("home/GetSessionData")]
   public IActionResult GetSessionData(){
      ViewBag.data = HttpContext.Session.GetString("product");;
      return View();
   }
}
How to delete columns in PySpark dataframe ?

17 Jun, 2021
In this article, we are going to delete columns in Pyspark dataframe. To do this we will be using the drop() function. This function can be used to remove values from the dataframe.
Syntax: dataframe.drop(‘column name’)
Python code to create student dataframe with three columns:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  data data =[["1","sravan","vignan"],       ["2","ojaswi","vvit"],       ["3","rohith","vvit"],       ["4","sridevi","vignan"],       ["1","sravan","vignan"],        ["5","gnanesh","iit"]]  # specify column namescolumns=['student ID','student NAME','college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns)  print("Actual data in dataframe")  # show dataframedataframe.show()
Output:
Actual data in dataframe
+----------+------------+-------+
|student ID|student NAME|college|
+----------+------------+-------+
|         1|      sravan| vignan|
|         2|      ojaswi|   vvit|
|         3|      rohith|   vvit|
|         4|     sridevi| vignan|
|         1|      sravan| vignan|
|         5|     gnanesh|    iit|
+----------+------------+-------+
Example 1: Python program to delete a single column.
Here we are going to delete ‘student ID’ from the dataframe, for this we will use drop().
Python3
# delete single columndataframe=dataframe.drop('student ID')dataframe.show()
Output:
+------------+-------+
|student NAME|college|
+------------+-------+
|      sravan| vignan|
|      ojaswi|   vvit|
|      rohith|   vvit|
|     sridevi| vignan|
|      sravan| vignan|
|     gnanesh|    iit|
+------------+-------+
Example 2: Delete multiple columns
Here we will delete multiple columns in a dataframe just passing multiple columns inside the drop() function.
Python3
# delete two columnsdataframe=dataframe.drop(*('student NAME',                           'student ID'))dataframe.show()
Output:
+-------+
|college|
+-------+
| vignan|
|   vvit|
|   vvit|
| vignan|
| vignan|
|    iit|
+-------+
Example 3: Delete all columns
Here we will delete all the columns in dataframe.
Python3
# delete two columnsdataframe=dataframe.drop(*('student NAME',                           'student ID',                           'college'))dataframe.show()
Output:
++
||
++
||
||
||
||
||
||
++
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
Node.js __dirname Variable

08 Apr, 2021
The __dirname string gives the directory path of the current module, this is also similar to that of path.dirname() of the filename.
Return Value : It returns the directory path of the current module.
Example 1: Let’s create a file main.js
main.js
import path from 'path';const __dirname = path.resolve();console.log(__dirname)
Output: Now run node main.js.
Example 2: Replicating __dirname with path.dirname().
Javascript
import path from 'path';const __dirname = path.resolve();const __filename = path.resolve();console.log(path.dirname(__filename));
Output: Now run node main.js.
Reference:https://nodejs.org/docs/latest/api/globals.html#globals_dirname
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Hover Text and Formatting in Python-Plotly

06 Jul, 2022
Prerequisites: Python Plotly
In this article, we will explore how to Hover Text and Formatting in Python.
It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears.
 The default setting is layout.hovermode=’closest’, wherein a single hover label appears for the point directly underneath the cursor.
Python3
import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines") fig.show()
Output:
If layout.hovermode=’x’ , a single hover label appears per trace, for points at the same x value as the cursor.
Python3
import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines", hovertemplate=None)fig.update_layout(hovermode="x unified") fig.show()
Output:
If layout.hovermode=’y’ , a single hover label appears per trace, for points at the same y value as the cursor.
Python3
import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country")fig.update_traces(mode="markers+lines", hovertemplate=None)fig.update_layout(hovermode="y unified") fig.show()
Output:
GDP: %{x} <br>Life Expectancy: %{y}
Here, GDP and Expectancy is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information.
Python3
import plotly.express as px df_2007 = px.data.gapminder().query("year==2007") fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp",                 log_x=True, color='continent') fig.update_traces(hovertemplate='GDP: %{x} <br>Life Expectancy: %{y}') fig.show()
Output:
%{label}: <br>Popularity: %{percent} </br> %{text}
Here, Label, Percent, and Text is used as naming convention about the data whereas %{ <variable>} which allows to revel a large amount of data about complex information.
Python3
import plotly.graph_objects as go fig = go.Figure(go.Pie(    name = "",    values = [2, 5, 3, 2.5],    labels = ["R", "Python", "Java Script", "Matlab"],    text = ["R", "Python", "JS", "Matlab"],    hovertemplate = "%{label}: <br>Popularity: %{percent} </br> %{text}")) fig.show()
Output:
vinayedula
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
javap tool in Java with Examples

10 May, 2019
javap tool
The javap tool is used to get the information of any class or interface. The javap command (also known as the Java Disassembler) disassembles one or more class files. Its output depends on the options used (“-c” or “-verbose” for byte code and byte code along with innards info, respectively). If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it.Syntax:
javap [option] [classname]

When no options are used:Syntax:
javap class_name

Output:When Options are used:
The description and implementation of options are given below:Note: Some options prints very long output which can’t be shown completely. Please try in your System to view the complete output of options used.
-help or –help or -? :This option prints a help message for the javap command.Syntax:javap -help
Output:
javap -help

Output:
-version :This option prints Version information of java.Syntax:javap -version
Output:
javap -version

Output:
-v or -verbose :This option Prints additional information like stack size, number of locals and arguments for methods.Syntax:javap -v class_name
Output:
javap -v class_name

Output:
-l :This option prints line number and local variable tables.Syntax:javap -l class_name
Output:
javap -l class_name

Output:
-public :This option prints only public classes and members.Syntax:javap -public class_name
Output:
javap -public class_name

Output:
-protected :This option prints protected/public classes and members.Syntax:javap -protected class_name
Output:
javap -protected class_name

Output:
-package :This option prints package/protected/public classes and members (default).Syntax:javap -package class_name
Output:
javap -package class_name

Output:
-c :This option prints Disassembled code.Syntax:javap -c class_name
Output:
javap -c class_name

Output:
-s :This option prints internal type signatures.Syntax:javap -s class_name
Output:
javap -s class_name

Output:
-sysinfo :This option prints system info (path, size, date, MD5 hash) of class being processed.Syntax:javap -sysinfo class_name
Output:
javap -sysinfo class_name

Output:
-constants :This option prints final constants of class.Syntax:javap -constants class_name
Output:
javap -constants class_name

Output:
References: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html
java-advanced
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
How to use ngfor to make a dropdown in Angular from an array ?

12 Mar, 2021
In this post, we will see how we can display the array elements in the drop-down menu using AngularJS. Sometimes we need to display dynamically fetched data and this is where features ngFor come into the scene. We can iterate over the array, apply conditions and display the data easily.
Using ngFor: NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. 
Syntax:
<tag-name  *ngFor="let item of array">{{iter}}</tag-name>
<tag-name  *ngFor="let key of object">{{key}}</tag-name>
Prerequisites: NPM must be preinstalled.
Install angular :
npm install -g @angular/cli
Create a new Angular project:
ng new <project-name>
cd <project-name> 
Check the installation by running the project. You should see the angular landing page on http://localhost:4200/
ng serve -o
1. Create a new component:
ng g c dropdown
2. It will create a new directory with 4 new files. Open dropdown.component.ts and paste the following code:
dropdown.component.ts:
Javascript
import { Component } from '@angular/core';  @Component({  selector: 'app-dropdown',  templateUrl: './dropdown.component.html',  styleUrls: ['./dropdown.component.css']})export class DropdownComponent {  players = [    "Sachin Tendulkar",    "Ricky Ponting",    "Virat Kohli",    "Kumar Sangakkara",    "Jacques Kallis",    "Hashim Amla    ",    "Mahela Jayawardene    ",    "Brian Lara",    "Rahul Dravid",    "AB de Villiers"  ]  selected = "----"    update(e){    this.selected = e.target.value  }}
In above code, we have defined players array that contains the data that we will display in the drop down menu. Additionally we have a selected variable that we will use to display the selected element. The method update() takes an event and sets selected to its value.
3. Now add the following code into dropdown.component.html:
dropdown.component.html:
HTML
<h3>Choose Your Favorite Cricket Player</h3><select #cricket (change)="update($event)">    <option value="default">----</option>    <option *ngFor="let player of players" [value]="player">        {{player}}    </option></select>  <p>You selected {{selected}}</p>
We have created a drop-down menu that will use the players array. The options are populated using ngFor. The selected variable is used to display the selected option.
4. Finally add this component into app.component.html:
app.component.html:
HTML
<app-dropdown></app-dropdown>
5. Now run the project and open http://localhost:4200/ to see the results:
ng serve -o
AngularJS-Questions
HTML-Questions
Picked
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set a Minimum Field Width in Java

The minimum field width specifier is what you include between % and the format conversion code.
To include a 0 before the field width specifier, pad with 0's. An integer between the % sign and the format conversion code acts as a minimum field width specifier.
Let us see an example −
 Live Demo
import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      System.out.println(f.format("%08d", 697));
      f = new Formatter();
      System.out.println(f.format("%10d", 9878));
      f = new Formatter();
      System.out.println(f.format("%06d", 697));
   }
}
00000697
     9878
000697
Collapsible Pane in Tkinter Python

Tkinter is the GUI building library of python. In this article we will see how we can create a collapsible pane. They are usefult when we have some large amount of data to be displayed over a GUI canvas but we do not want to be displayed always. It is made collapsible so that it can be displayed as and when needed.
The below program creates the collapsible pane where we see the result both after expanding and contracting the arrow. The code comments indicate the approach we take at each step.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import *
class cpane(ttk.Frame):
   def __init__(self, MainWindow, expanded_text, collapsed_text):
      ttk.Frame.__init__(self, MainWindow)
      # The class variable
      self.MainWindow = MainWindow
      self._expanded_text = expanded_text
      self._collapsed_text = collapsed_text
      # Weight=1 to grow it's size as needed
      self.columnconfigure(1, weight=1)
      self._variable = tk.IntVar()
      # Creating Checkbutton
      self._button = ttk.Checkbutton(self, variable=self._variable,
      command=self._activate, style="TButton")
      self._button.grid(row=0, column=0)
      # Create a Horizontal line
      self._separator = ttk.Separator(self, orient="horizontal")
      self._separator.grid(row=0, column=1, sticky="we")
      self.frame = ttk.Frame(self)
      # Activate the class
      self._activate()
   def _activate(self):
      if not self._variable.get():
         # Remove this widget when button pressed.
         self.frame.grid_forget()
         # Show collapsed text
         self._button.configure(text=self._collapsed_text)
      elif self._variable.get():
         # Increase the frame area as needed
         self.frame.grid(row=1, column=0, columnspan=2)
         self._button.configure(text=self._expanded_text)
   def toggle(self):
      self._variable.set(not self._variable.get())
      self._activate()
# Creating root window or MainWindow
root = Tk()
root.geometry('300x300')
# Creating Object of Collapsible Pane Container
cpane_obj = cpane(root, 'Close Me', 'Open Me!')
cpane_obj.grid(row=0, column=0)
# Buttons to # appear in collapsible pane
b = Button(cpane_obj.frame, text=" Frame Expanded").grid(
   row=1, column=2, pady=20)
b = Checkbutton(cpane_obj.frame, text="Hi There ! How are you doing?").grid(
   row=3, column=4, pady=20)
mainloop()
Running the above code gives us the following result −
Defining Dependencies in Makefile

It is very common that a final binary will be dependent on various source code and source header files. Dependencies are important because they let the make Known about the source for any target. Consider the following example −
hello: main.o factorial.o hello.o
   $(CC) main.o factorial.o hello.o -o hello
Here, we tell the make that hello is dependent on main.o, factorial.o, and hello.o files. Hence, whenever there is a change in any of these object files, make will take action.
At the same time, we need to tell the make how to prepare .o files. Hence we need to define those dependencies also as follows −
main.o: main.cpp functions.h
   $(CC) -c main.cpp

factorial.o: factorial.cpp functions.h
   $(CC) -c factorial.cpp

hello.o: hello.cpp functions.h
   $(CC) -c hello.cpp
 Print
 Add Notes
 Bookmark this page
C++ ios Library - Function Scientific

It is used to sets the floatfield format flag for the str stream to scientific. When floatfield is set to scientific, floating-point values are written using scientific notation: the value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter e followed by an optional sign and three exponential digits.
The floatfield format flag is both a selective and a toggle flag: it can take one or more of the following values as shown below −
The floatfield format flag is both a selective and a toggle flag: it can take any of the following values, or none as shown below −
write floating-point values in hexadecimal format.
The value of this is the same as (fixed|scientific)
Following is the declaration for std::scientific function.
ios_base& scientific (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::scientific function.
#include <iostream>

int main () {
   double a = 3.1415926534;
   double b = 2006.0;
   double c = 1.0e-10;

   std::cout.precision(5);

   std::cout << "default:\n";
   std::cout << a << '\n' << b << '\n' << c << '\n';

   std::cout << '\n';

   std::cout << "fixed:\n" << std::fixed;
   std::cout << a << '\n' << b << '\n' << c << '\n';

   std::cout << '\n';

   std::cout << "scientific:\n" << std::scientific;
   std::cout << a << '\n' << b << '\n' << c << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
default:
3.1416
2006
1e-010

fixed:
3.14159
2006.00000
0.00000

scientific:
3.14159e+000
2.00600e+003
1.00000e-010

 Print
 Add Notes
 Bookmark this page
C++ Program for Derivative of a Polynomial

Given a string containing the polynomial term, the task is to evaluate the derivative of that polynomial.
What is a Polynomial?
Polynomial comes from two words: - “Poly” which means “many” and “nomial” means “terms”, which comprises many terms. Polynomial expression is an expression containing variables, coefficients and exponents, which only involves operations such as, addition, multiplication and subtraction of variable(s).
Example of polynomial
x2+x+1
Derivative of the polynomial p(x) = mx^n  will be −
m * n * x^(n-1)
Input: str = "2x^3 +1x^1 + 3x^2"
   val = 2
Output: 37
Explanation: 6x^2 + 1x^0 + 6x^1
   Putting x = 2
   6*4 + 1 + 6*2 = 24 + 1 + 12 = 37

Input: str = “1x^3”
   val = 2
Output: 12
Explanation: 1 * 3 *x^2
   Putting x = 2
   3 * 4 = 12
Approach we will be using to solve the above problem −
Take the input  as a string and a value of x
Now traverse the string and check for the digits, and variables.
Keep adding and traversing the string till we find ‘+’.
Then m * n * x^(n-1).
Return the result.
Start
Step 1-> In function long long term(string polyterm, long long val)
   Declare and initialize coeffStr = "”
   Declare i
   Loop For i = 0 and polyterm[i] != 'x' and i++
      Call coeffStr.push_back(polyterm[i])
      Set coeff = atol(coeffStr.c_str()
      Declare and initialize powStr = ""
      Loop For i = i + 2 and i != polyterm.size() and i++ powStr.push_back(polyterm[i])
         Set power = atol(powStr.c_str());
   Return coeff * power * pow(val, power - 1)
Step 2-> In function long long value(string& str, int val)
   Set ans = 0
   Call istringstream is(str)
   Declare string polyterm
   Loop While is >> polyterm
      If polyterm == "+” then,
         Continue
      Else
         Set ans = (ans + term(polyterm, val))
   Return ans
Step 3-> In function int main()
   Declare and initialize str = "2x^3 + 1x^1 + 3x^2"
   Declare and initialize val = 2
   Print the value received by value(str, val)
Stop
 Live Demo
#include
using namespace std;
long long term(string polyterm, long long val) {
   //to find the coefficient
   string coeffStr = "";
   int i;
   for (i = 0; polyterm[i] != 'x'; i++)
      coeffStr.push_back(polyterm[i]);
   long long coeff = atol(coeffStr.c_str());
   // to get the power value
   string powStr = "";
   for (i = i + 2; i != polyterm.size(); i++)
      powStr.push_back(polyterm[i]);
   long long power = atol(powStr.c_str());
   // For ax^n, we return a(n-1)x^(n-1)
   return coeff * power * pow(val, power - 1);
}
long long value(string& str, int val) {
   long long ans = 0;
   // using istringstream to get input in tokens
   istringstream is(str);
   string polyterm;
   while (is >> polyterm) {
      // check if the token is equal to '+' then
      // continue with the string
      if (polyterm == "+")
         continue;
         // Otherwise find the derivative of that
         // particular term
      else
         ans = (ans + term(polyterm, val));
   }
   return ans;
}
// main function
int main() {
   string str = "2x^3 + 1x^1 + 3x^2";
   int val = 2;
   cout << value(str, val);
   return 0;
}
37
HTML | DOM getBoundingClientRect() Method - GeeksforGeeks

25 Jul, 2019
HTML DOM getBoundingClientRect() Method returns the relative positioning to the viewport.It returns eight properties: left, top, right, bottom, x, y, width, height.Scrolling will change the position value.
Syntax:
var rect = div.getBoundingClientRect();
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML | DOM getBoundingClientRect() Method    </title>    <script>        function myFunction() {            var div = document.getElementById("myDiv");            var rectangle = div.getBoundingClientRect();            x = rectangle.left;            y = rectangle.top;            w = rectangle.width;            h = rectangle.height;              alert("Left:" + x + ", Top:" + y +                ", Width:" + w + ", Height:" + h);        }    </script></head>  <body>    <button onclick="myFunction()">        GET POSITION    </button>    <div style="height:300px;                 width:400px;                overflow:auto;">          <div id="myDiv" style="width:350px;                               height:250px;                                background-color:lightgreen;                               border:2px SOLID green;">              Use scrollbar to change the position.        </div>        <div style="width:1500px;                    height:1500px; ">        </div>    </div>    <br>  </body>  </html>
Output:Before Click:
After Click:
Supported Browsers:
Chrome 1.0
Internet Explorer 9.0
FireFox 3.0
Opera 9.5
Safari 4.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
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 | Pandas Series.dt.time - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.time attribute return a numpy array of python datetime.time objects.
Syntax: Series.dt.time
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# return the timeresult = sr.dt.time  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object. Example #2 : Use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                       periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# return the timeresult = sr.dt.time  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP 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()
Batch Script - Deleting Folders

For deleting folders, Batch Script provides the DEL command.
DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names

Following are the description of the options which can be presented to the DEL command.
Names
Specifies a list of one or more files or directories. Wildcards may be used to delete multiple files. If a directory is specified, all files within the directory will be deleted
/P
Prompts for confirmation before deleting each file.
/F
Force deletes read-only files.
/S
Deletes specified files from all subdirectories.
/Q
Quiet mode, do not ask if ok to delete on global wildcard.
/A
Selects files to delete based on attributes.
attributes
R - Read-only files, S - System files, H - Hidden files, A - Files ready for archiving - Prefix meaning not
Let’s look at some examples of how the DEL command can be used for folders.
del Example

The above command will delete the folder called Example in the current working directory.
del C:\Example

The above command will delete the folder called Example in C drive.
Del Example1 , Example2

The above command will delete the folder called Example1 and Example2 in the current working directory.
 Print
 Add Notes
 Bookmark this page
What are Rest parameters in JavaScript?

ES6 brought rest parameter to ease the work of developers. For arguments objects, rest parameters are indicated by three dots ... and precedes a parameter.With this, set indefinite number of arguments as an array, which areArray instances.
Let’s see the following code snippet:
<html>
   <body>
      <script>
         function addition(...numbers) {
            var res = 0;
            numbers.forEach(function (number) {
               res += number;
            });
            return res;
         }
         document.write(addition(3));
         document.write(addition(5,6,7,8,9));
      </script>
   </body>
</html>
Powershell - Create XML File

New-Item cmdlet is used to create a xml file and Set-Content cmdlet to put content into it.
In this example, we're creating a new xml file named test.xml
Type the following command in PowerShell ISE Console
New-Item D:\temp\test\test.xml -ItemType File
You can see the test.xml created in D:\temp\test directory.
In this example, we're adding content to test.xml.
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.xml '<title>Welcome to TutorialsPoint</title>'
In this example, we're reading content of test.xml.
Get-Content D:\temp\test\test.xml

You can see following output in PowerShell console.
<title>Welcome to TutorialsPoint</title>


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
How to create dismissible alerts in Bootstrap ? - GeeksforGeeks

04 Oct, 2021
Alerts are a very important component in the Bootstrap library. They are used to display any message to the users like a form being submitted, OTP is sent or incorrect input entered in the form. In other words, alerts are used to provide feedback messages to the user based on their interaction with the website.
In this article, we will learn how to create a dismissible alert using the bootstrap library. Dismissible alerts make our website like a modern website where we can dismiss the alert after reading it. We will need to load the alert plugin by including the compiled Bootstrap JavaScript on our HTML page.
We can add the close button and use the .alert-dismissible class, which adds extra padding to the right of the alert and positions the close button. On the close button, we use the data-bs-dismiss=”alert” attribute, which triggers the JavaScript functionality. The <button> element is recommended here for proper behavior across all devices. We can use the .fade and .show classes to animate alerts when they are dismissed.
Syntax:
<div class="alert alert-warning alert-dismissible" role="alert">
    <strong>Alert!</strong>This is a dismissable alert
    <button type="button" class="btn-close" 
      data-bs-dismiss="alert"
      aria-label="Close">
    </button>
</div>
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <!-- Bootstrap CSS -->    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css"           rel="stylesheet">          <!-- Bootstrap JS -->    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js">    </script>  </head>  <body class="container">    <h1>Dismissible Alert</h1>    <div class="alert alert-warning                 alert-dismissible                 fade show" role="alert">        <strong>Alert!</strong>          This is a dismissable          alert that can be dismissed after        clicking on the close button.        <button type="button" class="btn-close"                   data-bs-dismiss="alert"                   aria-label="Close">        </button>    </div>    <p>This is some page text.</p>  </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to keep gap between columns using Bootstrap?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to create Ordered dictionaries in Python?

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, It is defined in collections module of Python library. OrderDict remembers the order of addition of key-value pairs in a dictionary
>>> from collections import OrderedDict
>>> od=OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
>>> t=od.popitem()
>>> t
('orange', 2)
How to select rows of a data frame that are not in other data frame in R?

Instead of finding the common rows, sometimes we need to find the uncommon rows between two data frames. It is mostly used when we expect that a large number of rows are uncommon instead of few ones. We can do this by using the negation operator which is represented by exclamation sign with subset function.
Consider the below data frames −
 Live Demo
> x1<-sample(1:10,20,replace=TRUE)
> y1<-sample(1:10,20,replace=TRUE)
> df1<-data.frame(x1,y1)
> df1
 x1 y1
1 10 6
2 5 9
3 10 10
4 4 10
5 1 6
6 1 4
7 9 3
8 5 10
9 10 3
10 8 2
11 6 10
12 6 3
13 9 3
14 3 6
15 6 9
16 9 1
17 7 9
18 3 8
19 2 5
20 4 9
 Live Demo
> x2<-sample(1:10,20,replace=TRUE)
> y2<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(x2,y2)
> df2
 x2 y2
1 6 10
2 3 6
3 9 6
4 9 10
5 10 10
6 3 2
7 3 3
8 2 9
9 7 5
10 1 1
11 10 10
12 1 6
13 3 4
14 4 2
15 6 3
16 1 7
17 2 2
18 4 6
19 4 1
20 1 8
Now suppose we want to take a subset of df2 variable y2 that are not in y1 of df1, then it can be done as follows −
> subset(df2,!(y2%in%df1$y1))
x2 y2
16 1 7
<0 rows> (or 0-length row.names)
Similarly, taking a subset of df2 variable y2 that are not in x1 of df1, then it can be done as follows −
> subset(df2,!(y2%in%df1$x1))
[1] x2 y2
<0 rows> (or 0-length row.names)
Let’s have a look at one more example −
 Live Demo
> x1<-rep(1:10,2)
> df1<-data.frame(x1)
> df1
 x1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 1
12 2
13 3
14 4
15 5
16 6
17 7
18 8
19 9
20 10
 Live Demo
> x2<-rep(1:5,4)
> df2<-data.frame(x2)
> df2
 x2
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5
11 1
12 2
13 3
14 4
15 5
16 1
17 2
18 3
19 4
20 5
> subset(df1,!(x1%in%df2$x2))
 x1
6 6
7 7
8 8
9 9
10 10
16 6
17 7
18 8
19 9
20 10
ftp - Unix, Linux Command

ftp - Internet file transfer program
ftp [-pinegvd] [host]

pftp [-inegvd] [host]
Example-1:
To see help of all available commands in ftp
$ ftp
ftp> help
output:
$ ftpftp> helpCommands may be abbreviated.  Commands are:!               dir                 mdelete        qc               site$              disconnect      mdir              sendport     sizeaccount     exit                mget            put             statusappend     form               mkdir           pwd            structascii         get                 mls              quit             systembell          glob                mode           quote          suniquebinary       hash               modtime      recv             tenexbye           help               mput           reget            tickcase          idle                newer          rstatus          tracecd             image            nmap           rhelp            typecdup          ipany             nlist             rename        userchmod       ipv4               ntrans          reset            umaskclose         ipv6               open            restart          verbosecr              lcd                 prompt         rmdir            ?delete       ls                   passive        runiquedebug       macdef           proxy           send
Example-2:
To Changing FTP Mode to binary or ascii
ftp> ascii
output:
200 Type set to A.

Example-3:
To Download a file using ftp:
ftp> get README  
output:200 PORT command successful.  150 ASCII data connection for README (128.138.242.10,3134) (2881 bytes).  226 ASCII Transfer complete.  local: README remote: README  2939 bytes received in 0.066 seconds (43 Kbytes/s)
Example-4:
Example-5:
To Changing the remote and local directory:
ftp> pwd
257 "/myftpserver" is current directory.
ftp> cd dir1
250 CWD command successful. "/myftpserver/dir1" is current directory.
ftp> pwd
257 "/myftpserver/dir1" is current directory.
Example-6:
Listing the contents of remote directory from FTP
ftp> ls
output:
200 PORT command successful.150 ASCII data connection for /bin/ls (128.138.242.10,3133) (0 bytes).ElementsofAVS.ps.Z
. . .execsumm_tr.ps.ZviShortRef.ps.Z226 ASCII Transfer complete.418 bytes received in 0.043 seconds (9.5 Kbytes/s)
Example-7:
ftp> mput Makefile
output:
200 PORT command successful.150 Opening ASCII mode data connection for Makefile.226 Transfer complete.local: Makefile remote: Makefile1020 bytes sent in 0.0062 seconds (1.6e+02 Kbytes/s)
Example-8:
To Close a FTP connection:
ftp> close
output:
221 Goodbye.

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
MomentJS - Now

This will display the current date.
var now = moment();
To get the current date, we have to use the following code −
now._d
 Print
 Add Notes
 Bookmark this page
Program to find the minimum cost to arrange the numbers in ascending or descending order in Python

Suppose we have a list of numbers called nums, we have to find the minimum cost to sort the
list in any order (Ascending or Descending). Here the cost is the sum of differences between any
element's old and new value.
So, if the input is like [2, 5, 4], then the output will be 2.
To solve this, we will follow these steps −
temp:= copy the array nums
sort the list temp
c1:= 0, c2:= 0
n:= size of nums
for i in range 0 to n, doif nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|
if nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|
c1 := c1 + |nums[i]-temp[i]|
if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|
c2 := c2 + |nums[i]-temp[n-i-1]|
return minimum of c1 and c2
Let us see the following implementation to get better understanding −
class Solution:
   def solve(self, nums):
      temp=nums.copy()
      temp.sort()
      c1=0
      c2=0
      n=len(nums)
      for i in range(n):
         if nums[i]!=temp[i]:
            c1+=abs(nums[i]-temp[i])
         if nums[i]!=temp[n-1-i]:
            c2+=abs(nums[i]-temp[n-i-1])
      return min(c1,c2)
ob = Solution()
print(ob.solve([2, 5, 4]))
[2, 5, 4]
2
Flask form submission without Page Reload - GeeksforGeeks

17 Jun, 2021
There are many modules or frameworks which allows to build your webpage using python like bottle, django, flask etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you the versatility to program with.
Problem:
If we do post request then the whole page will reload. So this article revolves around how to send the form data to flask backend without reloading the page. For submitting form without reloading  page we use jquery and ajax. So before using flask we have to install that
Ubuntu
pip3 install flask
Create new directory for your project. Inside that create new file and name it as app.py
app.py
Python3
from flask import Flask,render_template,request app = Flask(__name__)  @app.route("/",methods=["POST","GET"])def home():    if request.method == "POST":        todo = request.form.get("todo")        print(todo)    return render_template('home.html')  if __name__ == '__main__':    app.run(debug=True)    
Then create new directory and name it as templates
Inside that create new file and name it as home.html
home.html
HTML
<!DOCTYPE html><html><head>    <title>GFG</title></head><body>  <form method="post" id="todo-form">        <input type="text" name="todo" id="todo">        <button type="submit">submit</button>    </form>         <!--Jquery Cdn -->  <script src="https://code.jquery.com/jquery-3.5.1.js"          integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="          crossorigin="anonymous"></script>   <script type="text/javascript">    $(document).on('submit','#todo-form',function(e)                   {      console.log('hello');      e.preventDefault();      $.ajax({        type:'POST',        url:'/',        data:{          todo:$("#todo").val()        },        success:function()        {          alert('saved');        }      })    });  </script> </body></html>
  
e.preventDefault() :-  This function doesn’t reload the page
type: GET or POST request
url : url that we have specify in our flask app
data : Form data that we want to pass
Succes: function() :- This function run after successfully submitting the values and when there are no error occur while submitting the data.
 
OUTPUT :-
 
 
 
On the cmd or terminal it will print the value we have submitted using form.
 
ruhelaa48
Python Flask
Python Framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()