code-rag-bench/online-tutorials huggingface dataset:
How to open a file in the same directory as a Python script?

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys.path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.
For example if you have a file called my_file.txt in the same directory as currently executing script, you can open it using:
import os
with open(os.path.join(sys.path[0], "my_file.txt"), "r") as f:
    print(f.read())
This will open the file and read its content given that the file resides in the same directory as the script.
What is the difference between single and double quotes in python?

A string as a sequence of characters not intended to have numeric value. In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably. However, if either single or double quote is a part of the string itself, then the string must be placed in double or single quotes respectively.
For example a text Hello “Python” is to be stored as a string, then one should use
str1='Hello "Python"'
On the other hand, if string should resemble Hello ‘Python’ then it should be declared as follows:
Str2="Hello 'Python'"
Creating Instance Objects in Python

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Now, putting all the concepts together −
 Live Demo
#!/usr/bin/python
class Employee:
   'Common base class for all employees'
   empCount = 0
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   def displayCount(self):
   print "Total Employee %d" % Employee.empCount
   def displayEmployee(self):
      print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
When the above code is executed, it produces the following result −
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
You can add, remove, or modify attributes of classes and objects at any time −
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following functions −
The getattr(obj, name[, default]) − to access the attribute of object.
The hasattr(obj,name) − to check if an attribute exists or not.
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
The delattr(obj, name) − to delete an attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'
Find the sum of array in Python Program

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array we need to compute the sum of the array.
The brute-force approach to traverse the whole array and element at each index to obtain the sum is discussed below at each index to obtain the sum is discussed below
 Live Demo
# sum function
def sum_(arr,n):
   # using built-in function
   return(sum(arr))
# main
arr = [11,22,33,44,55,66]
# length
n = len(arr)
ans = sum_(arr,n)
# display sum
print("Sum of the array is ",ans)
Sum of the array is 231
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned how to print the sum of array
What are symbols in a JavaFX line chart. How to disable them?

Inline chart the data values have represented a series of points connected by a line. In JavaFX, you can create a line chart by instantiating the javafx.scene.chart.LineChart class.
By default,
A JavaFX Line chart contains symbols pointing out the values in the series
along the x-axis. Typically, these are small circles.
A JavaFX Line chart contains symbols pointing out the values in the series
along the x-axis. Typically, these are small circles.
The X-Axis on the bottom in the plot.
The X-Axis on the bottom in the plot.
Y-Axis on the left.
Y-Axis on the left.
The LineChart class has a property named createSymbols (boolean), which specifies whether to create symbols for data items in the chart. You can set values to this method using the setCreateSymbols() method.
To remove symbols from a line chart you need to invoke this method by passing the boolean value false as an argument to this method.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class LineChart_Symbols extends Application {
   public void start(Stage stage) {
      //Defining the x an y axes
      CategoryAxis xAxis = new CategoryAxis();
      NumberAxis yAxis = new NumberAxis(200, 600, 100);
      //Setting labels for the axes
      xAxis.setLabel("Model");
      yAxis.setLabel("Price (USD)");
      //Creating a line chart
      LineChart linechart = new LineChart(xAxis, yAxis);
      //Preparing the data points for the line
      XYChart.Series series = new XYChart.Series();
      series.getData().add(new XYChart.Data("OnePlus X", 249));
      series.getData().add(new XYChart.Data("OnePlus One", 299));
      series.getData().add(new XYChart.Data("OnePlus 2", 329));
      series.getData().add(new XYChart.Data("OnePlus 3", 399));
      series.getData().add(new XYChart.Data("OnePlus 3T", 439));
      series.getData().add(new XYChart.Data("OnePlus 5", 479));
      series.getData().add(new XYChart.Data("OnePlus 5T", 499));
      series.getData().add(new XYChart.Data("OnePlus 6", 559));
      //Setting the name to the line (series)
      series.setName("Price of mobiles");
      //Setting the data to Line chart
      linechart.getData().add(series);
      //Removing the symbols of the line chart
      linechart.setCreateSymbols(false);
      //Creating a stack pane to hold the chart
      StackPane pane = new StackPane(linechart);
      pane.setPadding(new Insets(15, 15, 15, 15));
      pane.setStyle("-fx-background-color: BEIGE");
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Line Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
How to download Google Images using Python

Google offers many python packages which minimize the effort to write python code to get data from google services. One such package is google images download. It takes in the key words as parameters and locates the images with those keywords.
In the below example we limit the number of images to 5 and also allow the program to print the urls from where the files were generated.
from google_images_download import google_images_download
#instantiate the class
response = google_images_download.googleimagesdownload()
arguments = {"keywords":"lilly,hills","limit":5,"print_urls":True}
paths = response.download(arguments)
#print complete paths to the downloaded images
print(paths)
Running the above code gives us the following result −
Image URL: https://assets.traveltriangle.com/blog/wp-content/uploads/2017/11/Hill-Stations-Near-Kolkata-cover1-400x267.jpg
Completed Image ====> 4.Hill-Stations-Near-Kolkata-cover1-400x267.jpg
Image URL: https://image.shutterstock.com/image-photo/distant-hills-hilly-steppe-curvy-260nw-1037414248.jpg
Completed Image ====> 5.distant-hills-hilly-steppe-curvy-260nw-1037414248.jpg
({'lilly': ['C:\\python3\\downloads\\lilly\\1.Lilly-Tougas.jpg', 
'C:\\python3\\downloads\\lilly\\2.1200px-Eli_Lilly_and_Company.svg.png', '
C:\\python3\\downloads\\lilly\\3.nikki-lilly-this-morning.jpg', 
'C:\\python3\\downloads\\lilly\\4.lily-plants.jpg', 
'C:\\python3\\downloads\\lilly\\5.dish-lilly-ghalichi.jpg'], 
'hills': ['C:\\python3\\downloads\\hills\\1.220px-Clouds_over_hills.jpg', 
'C:\\python3\\downloads\\hills\\2.Bacin_zari_2015.jpg', 
'C:\\python3\\downloads\\hills\\3.65ad9ac0-0455-4086-a4f4-1245f697d10e.png', 
'C:\\python3\\downloads\\hills\\4.Hill-Stations-Near-Kolkata-cover1-400x267.jpg', 
'C:\\python3\\downloads\\hills\\5.distant-hills-hilly-steppe-curvy-260nw-1037414248.jpg']}, 1)
Object Slicing in C++ - GeeksforGeeks

24 Sep, 2021
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.  
C++
class Base { int x, y; }; class Derived : public Base { int z, w; }; int main(){    Derived d;    Base b = d; // Object Slicing,  z and w of d are sliced off}
Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.  
C++
#include <iostream>using namespace std; class Base{protected:    int i;public:    Base(int a)     { i = a; }    virtual void display()    { cout << "I am Base class object, i = " << i << endl; }}; class Derived : public Base{    int j;public:    Derived(int a, int b) : Base(a) { j = b; }    virtual void display()    { cout << "I am Derived class object, i = "           << i << ", j = " << j << endl;  }}; // Global method, Base class object is passed by valuevoid somefunc (Base obj){    obj.display();} int main(){    Base b(33);    Derived d(45, 54);    somefunc(b);    somefunc(d);  // Object Slicing, the member j of d is sliced off    return 0;}
Output: 
I am Base class object, i = 33
I am Base class object, i = 45
We can avoid above unexpected behavior with the use of pointers or references. Object slicing doesn’t occur when pointers or references to objects are passed as function arguments since a pointer or reference of any type takes same amount of memory. For example, if we change the global method myfunc() in the above program to following, object slicing doesn’t happen.  
C++
// rest of code is similar to abovevoid somefunc (Base &obj){    obj.display();}          // rest of code is similar to above
Output: 
I am Base class object, i = 33
I am Derived class object, i = 45, j = 54
We get the same output if we use pointers and change the program to following.  
C++
// rest of code is similar to abovevoid somefunc (Base *objp){    objp->display();} int main(){    Base *bp = new Base(33) ;    Derived *dp = new Derived(45, 54);    somefunc(bp);    somefunc(dp);  // No Object Slicing    return 0;}
Output: 
I am Base class object, i = 33
I am Derived class object, i = 45, j = 54
Object slicing can be prevented by making the base class function pure virtual there by disallowing object creation. It is not possible to create the object of a class which contains a pure virtual method.This article is contributed by Pravasi Meet. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
sankususharma
cpp-class
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
How to generate short id in Node.js ? - GeeksforGeeks

09 Apr, 2021
In this article we are going to see how to generate a short id in Node.js. There is an NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, custom alphabet. It Can generate any number of ids without duplication.
Setting up of the environment:
Setting up of the NPM package of the project :npm init -y
Setting up of the NPM package of the project :
npm init -y
Installing Dependencies :npm install express shortid
Installing Dependencies :
npm install express shortid
Basic Express server:
index.js
const express = require('express');const app = express();    app.get('/' , (req , res)=>{    res.send("GeeksforGeeks");})  app.listen(4000 , ()=>{    console.log("server is running on port 4000");})
Output:
Example: Importing ‘shortid’ into our project, there are lots of features in shortid module.
Syntax:
const short = require('shortid');
server.js
const express = require('express');const app = express();const short = require('shortid');  app.get('/' , (req , res)=>{    res.send(short()); // generating short id by calling short() function.})  app.listen(4000 , ()=>{    console.log("server is running on port 4000");})
Output:
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
Convert buffer to readable string in JavaScript?

For this, use the concept of toString(‘utf8’). Following is the code −
In the code below, there are detailed explanations about the buffer.
var actualBufferObject = Buffer.from('[John Smith]', 'utf8')
console.log("The actual buffer object=");
console.log(JSON.stringify(actualBufferObject))
console.log("Get back the original object=");
console.log(actualBufferObject.toString('utf8'));
var myObjectValue = '[John Smith]';
console.log("The data you are getting from the buffer is equal to ASCII
code equivalent...")
for (var counter = 0; counter < myObjectValue.length; counter++) {
   console.log("The ascii value of " + myObjectValue[counter] + " is ="
   + (myObjectValue.charCodeAt(counter)));
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo197.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo197.js
The actual buffer object=
{"type":"Buffer","data":[91,74,111,104,110,32,83,109,105,116,104,93]}
Get back the original object=
[John Smith]
The data you are getting from the buffer is equal to ASCII code equivalent...
The ascii value of [ is =91
The ascii value of J is =74
The ascii value of o is =111
The ascii value of h is =104
The ascii value of n is =110
The ascii value of is =32
The ascii value of S is =83
The ascii value of m is =109
The ascii value of i is =105
The ascii value of t is =116
The ascii value of h is =104
The ascii value of ] is =93
Reading JavaScript variables using Selenium WebDriver.

We can read Javascript variables with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method. Also we have to add the statement import org.openqa.selenium.JavascriptExecutor to work with Javascript.
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.title")
Let us obtain the browser title of the below page by reading the value from Javascript variable. The output should be About Careers at Tutorials Point – Tutorialspoint.
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavascriptReadValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // Javascript executor to read value
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // get the browser title with document.title
      String t = (String)j.executeScript("return document.title");
      System.out.print("Current page title: " +t);
      driver.close();
   }
}
SQLAlchemy Core - SQL Expressions

In this chapter, we will briefly focus on the SQL Expressions and their functions.
SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows −
ins = students.insert()
The result of above method is an insert object that can be verified by using str() function. The below code inserts details like student id, name, lastname.
'INSERT INTO students (id, name, lastname) VALUES (:id, :name, :lastname)'
It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below −
>>> ins = users.insert().values(name = 'Karan')
>>> str(ins)
'INSERT INTO users (name) VALUES (:name)'
The SQL echoed on Python console doesn’t show the actual value (‘Karan’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement.
ins.compile().params
{'name': 'Karan'}
Similarly, methods like update(), delete() and select() create UPDATE, DELETE and SELECT expressions respectively. We shall learn about them in later chapters.

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Constructor Overloading in C#

When more than one constructor with the same name is defined in the same class, they are called overloaded, if the parameters are different for each constructor.
Let us see an example to learn how to work with Constructor Overloading in C#.
In the example, we have two subjects and a string declaration for Student Name.
private double SubjectOne;
private double SubjectTwo;
string StudentName;
We are showing result of three students in different subjects. For our example, to show constructor overloading, the name is only displayed for student 3rd.
Student s1 = new Student();
Student s2 = new Student(90);
Student s3 = new Student("Amit",88, 60);
You can try to run the following code to implement constructor overloading in C#.
 Live Demo
using System;
namespace Program {
   class Student {
      private double SubjectOne;
      private double SubjectTwo;
      string StudentName;
      public Student() {
         this.SubjectOne = 80;
      }
      public Student(double SubjectOne) {
         this.SubjectOne = SubjectOne;
      }
      public Student(string StudentName, double SubjectOne, double SubjectTwo) {
         this.SubjectOne = SubjectOne;
         this.SubjectTwo = SubjectTwo;
         this.StudentName = StudentName;
      }
      public double GetSubjectOneMarks() {
         return this.SubjectOne;
      }
      public double GetSubjectTwoMarks() {
         return this.SubjectTwo;
      }
      public string GetStudentName() {
         return this.StudentName;
      }
   }
   class Program {
      static void Main(string[] args) {
         Student s1 = new Student();
         Student s2 = new Student(90);
         Student s3 = new Student("Amit",88, 60);
         Console.WriteLine("One");
         Console.WriteLine("Subject One Marks: {0}", s1.GetSubjectOneMarks());
         Console.WriteLine();
         Console.WriteLine("Second");
         Console.WriteLine("Subject One Marks: {0}", s2.GetSubjectOneMarks());
         Console.WriteLine();
         Console.WriteLine("Third");
         Console.WriteLine("Student name: {0}", s3.GetStudentName());
         Console.WriteLine("Subject One Marks: {0}", s3.GetSubjectOneMarks());
         Console.WriteLine("Subject Two Marks: {0}", s3.GetSubjectTwoMarks());
         Console.ReadKey();
      }
   }
}
One
Subject One Marks: 80

Second
Subject One Marks: 90

Third
Student name: Amit
Subject One Marks: 88
Subject Two Marks: 60
Enqueue and deque in Queue class in C#

Queue collection class is a concept in C# that is included in the System.Collection namespace. The elements are stored in a QUEUE in FIFO. The first element added will be the first to go out like a queue of people outside a movie hall to buy tickets.
It has two methods.
Enqueue() method to add values
Dequeue() method to retrieve values
Add items in the queue.
Queue q = new Queue();
q.Enqueue(“Two”);
q.Enqueue(“One”);
Return items from the queue.
Queue q = new Queue();
q.Enqueue(“Two”);
q.Enqueue(“One”);
// remove elements
while (q.Count > 0)
   Console.WriteLine(q.Dequeue());
What is PL/SQL?

It is a procedural extension language (PL) for the structured query language (SQL) and the Oracle relational database. It provides a built-in, interpreted and OS independent programming environment.
Apart from Oracle it also available Times Ten in-memory database and IBM DB2.
The Syntax of PL/SQL is based on ADA and Pascal programming languages. PL/SQL is tightly integrated with SQL.
PL/SQL offers the following −
Extensive error checking.
Numerous data types.
Variety of programming structures.
PL/SQL supports the following −
Structured programming through functions.
Structured programming through functions.
Procedures and object-oriented programming.
Procedures and object-oriented programming.
Development of web applications and server pages.
Development of web applications and server pages.
It defines the type of block (procedure, function, anonymous) and the way it is called, it declares any variables used in the block, it uses variables and other PL/SQL objects to perform actions and handle any problems that arise during execution of the block.
PL/SQL is not case sensitive. It uses the same data-types as SQL like Boolean, record, table, array and LOB. It allows reference data-types %type and %row type.
/* and */ for multiline.
-- for a single line.
= is used for assignment.
; is used to indicate end of line (instruction).
Given below is an example for the PL/SQL −
DECLARE
   current_bldg_code VARCHAR2(5);
   CURSOR location_cursor IS
      SELECT room, capacity
      FROM location
      WHERE bldg_code = current_bldg_code
      FOR UPDATE of capacity;
   location_row location_cursor%rowtype;
BEGIN
   current_bldg_code := ‘LIB’;
   FOR location_row IN location_cursor LOOP
      UPDATE location
      Set capacity = capacity +1
      WHERE CURRENT OF location_cursor;
   END LOOP;
   COMMIT;
END;
Find all occurrences of a word in array in JavaScript

We are required to write a JavaScript function that takes in an array of literals as the first argument and a string as the second argument. Our function should return the count of the number of times that string (provided by second argument) appears anywhere in the array.
The code for this will be −
const arr = ["word", "a word", "another word"];
const query = "word";
const findAll = (arr, query) => {
   let count = 0;
   count = arr.filter(el => {
      return el.indexOf(query) != -1;
   }).length;
   return count;
};
console.log(findAll(arr, query));
And the output in the console will be −
3
Node.js https.request() Function - GeeksforGeeks

08 Oct, 2021
Node.js provides two core modules for making http requests. The http module can be used to make http requests and the https module can be used to make https requests. One great feature of the request is that it provides a single module that can make both http and https requests.
Feature of https module:
It is easy to get started and easy to use.It is widely used and popular module for making https calls.
It is easy to get started and easy to use.
It is widely used and popular module for making https calls.
Create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
Filename: index.js
const https = require('https');  // Sample URLconst url = 'https://jsonplaceholder.typicode.com/todos/1';  const request = https.request(url, (response) => {    let data = '';    response.on('data', (chunk) => {        data = data + chunk.toString();    });      response.on('end', () => {        const body = JSON.parse(data);        console.log(body);    });})  request.on('error', (error) => {    console.log('An error', error);});  request.end() 
Steps to run the program:
Run index.js file using below command:node index.js
node index.js
So this is how you can use the https.request() function to make https request calls.
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to copy Items to the destination path with the different
credentials in PowerShell?

To copy the items with the different credentials you need to use the credential parameter in the Copy-Item cmdlet.
For example,
Copy-Item C:\temp\* -Destination \\Remoteshare\c$\temp -Credential (Get-
Credential)
Or
$creds = (Get-Credential)
Copy-Item C:\temp\* -Destination \\Remoteshare\c$\temp -Credential $creds
How to capture a screenshot of a particular element in Selenium 4.0?

We can capture screenshots of a particular element in Selenium 4.0 with the help of getScreenshotAs(OutputType.File) method where the OutputType tells about the output type of the screenshot.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
public class ScreenshotsElement{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/tutor_connect/index.php";
      WebElement drpdwn = driver.findElement(By.xpath("//select[@name=’selType’]"));
      // capture screenshot with getScreenshotAs() of the dropdown
      File f = drpdwn.getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(f, new File(“screenshots.png”));
      driver.quit();
   }
}
Angular forms NgForm Directive - GeeksforGeeks

24 May, 2021
In this article, we are going to see what is NgForm in Angular 10 and how to use it. NgForm is used to create a top-level form group Instance, and it binds the form to the given form value.
Syntax:
<form #FormName = "ngForm"> </form>
NgModule: Module used by NgForm is:
FormsModule
Selectors:
[ngForm]
Approach: 
Create the Angular app to be used
In app.module.ts import FormsModule.
In app.component.html make a form and store its value in ngForm variable and show its value in a JSON form.
Serve the angular app using ng serve to see the output.
Example 1:
app.module.ts
import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';      import { AppComponent }   from './app.component';   @NgModule({  bootstrap: [    AppComponent  ],  declarations: [    AppComponent  ],  imports: [    FormsModule,    BrowserModule,    BrowserAnimationsModule,        ]})export class AppModule { }
app.component.html
<form #gfgform = "ngForm">  {{ gfgform.value | json }}  <br>  <br>  Name: <input type="text" name = 'name' ngModel>  Email: <input type="email" name = 'email' ngModel></form>
Output:
Reference: https://angular.io/api/forms/NgForm
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
std::is_trivially_copyable template in C++ with Examples - GeeksforGeeks

12 Jun, 2020
The std::is_trivially_copyable template of C++ STL is present in the <type_traits> header file. The std::is_trivially_copyable template of C++ STL is used to check whether T is trivially copyable type (a type whose storage is contiguous) or not. It return the boolean value true if T is trivially copyable type, otherwise return false.
Header File:
#include<type_traits>

Template Class:
template<class T>
struct is_trivially_copyable;

Syntax:
std::is_trivially_copyable<T>::value

Parameter: The template std::is_trivially_copyable accepts a single parameter T(Trait class) to check whether T is trivially copyable type or not.
Return Value:The template std::is_trivially_copyable returns a boolean variable as shown below:
True: If the type T is a trivially copyable.
False: If the type T is not a trivially copyable.
Below is the program to demonstrate std::is_trivially_copyable template in C++:
Program:
// C++ program to illustrate// std::is_trivially_copyable#include <bits/stdc++.h>#include <type_traits>using namespace std;  // Declare structuresstruct X {    int a;};  struct Y {    Y(const Y&) {}};  struct Z {    virtual void GFG();};  struct A {    ~A() = delete;};  struct B : A {};  // Driver Codeint main(){    cout << boolalpha;      // Check if X is a trivially    // copyable or not    cout << is_trivially_copyable<X>::value         << endl;      // Check if Y is a trivially    // copyable or not    cout << is_trivially_copyable<Y>::value         << endl;      // Check if Z is a trivially    // copyable or not    cout << is_trivially_copyable<Z>::value         << endl;      // Check if A is a trivially    // copyable or not    cout << is_trivially_copyable<A>::value         << endl;      // Check if B is a trivially    // copyable or not    cout << is_trivially_copyable<B>::value         << endl;      return 0;}
true
false
false
true
true

CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Django Project MVT Structure - GeeksforGeeks

16 Aug, 2021
Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. 
MVT Structure has the following three parts – 
Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres). To check more, visit – Django Models 
View: The View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files. To check more, visit – Django Views. 
Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. To check more, visit – Django Templates 
 
A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-  
manage.py- This file is used to interact with your project via the command line(start the server, sync the database... etc). For getting the full list of commands that can be executed by manage.py type this code in the command window- 
$ python manage.py help
 folder ( geeks_site ) – This folder contains all the packages of your project. Initially, it contains four files – 
_init_.py – It is a python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data.
settings.py – As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc.
urls.py – In this file, we store all links of the project and functions to call.
wsgi.py – This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the webserver.
NaveenArora
annianni
ddeevviissaavviittaa
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
AtomicReference set() method in Java with Examples - GeeksforGeeks

27 Dec, 2019
The set() method of a AtomicReference class is used to set the value of this AtomicReference object with memory semantics of reading as if the variable was declared volatile type of variable.
Syntax:
public final void set(V newValue)

Parameters: This method accepts newValue which is the new value to set.
Return value: This method returns nothing.
Below programs illustrate the set() method:Program 1:
// Java program to demonstrate// AtomicReference.set() method  import java.util.concurrent.atomic.AtomicReference;  public class GFG {    public static void main(String[] args)    {          // create an atomic reference object        // which stores Integer.        AtomicReference<Integer> ref            = new AtomicReference<Integer>();          // set some value using set method        ref.set(13243546);          // print value        System.out.println("value 1 = " + ref.get());    }}
value 1 = 13243546

Program 2:
// Java program to demonstrate// AtomicReference.set() method  import java.util.concurrent.atomic.AtomicReference;  public class GFG {    public static void main(String[] args)    {          // create an atomic reference object        // which stores String.        AtomicReference<String> ref            = new AtomicReference<String>();          // set some value        ref.set("WELCOME TO GEEKS FOR GEEKS");          // print value        System.out.println("V  = " + ref.get());    }}
V  = WELCOME TO GEEKS FOR GEEKS

References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#set(V)
Java-Functions
Java-util-concurrent-atomic package
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
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
mpstat Command in Linux with Examples - GeeksforGeeks

26 Aug, 2020
mpstat is a command that is used to report processor related statistics. It accurately displays the statistics of the CPU usage of the system. It displays information about CPU utilization and performance. It initializes the first processor with CPU 0, the second one with CPU 1, and so on.
In Red Hat based Linux
sudo yum install sysstat
In ubuntu based Linux
 sudo apt install sysstat
1. To display processor and CPU statistics.
mpstat
This will display all the processor and CPU stats.
2. To display processor number of all CPUs.
mpstat -P ALL
This command will display the processor numbers of all the CPUs working.
3. To get all the information which the tool may collect.
mpstat -A
This will display each and every detail of CPU usage.
4. To display CPU utilization by a specific processor.
mpstat -P 0
This will display the CPU utilization by the 0th processor.
5. To display CPU usage with a time interval.
mpstat 1 5
This command will print 5 reports with 1 second time interval.
6. To display mpstat version
mpstat -V
This will display the version of the mpstat command installed in your system.
7. To display mpstat help
mpstat -h
This command will display mpstat help section
christopher2
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp 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
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Lex program to recognize valid arithmetic expression and identify the identifiers and operators - GeeksforGeeks

03 Dec, 2019
Problem: Write a Lex program to recognize valid arithmetic expression and identify the identifiers and operators.
Explanation:Flex (Fast lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Examples:
Input: a+b*c
Output: valid expression
        the operators are :
        + 
        * 
        the identifiers  are :
        a 
        b 
        c

Input: a+b-
Output: invalid expression
 
Input: (a*b)
Output: valid expression
        the operators are :
        * 
        the identifiers are :
        a 
        b 

Input: (a+b-
Output: invalid expression 
Implementation:
/* Lex program to recognize valid arithmetic expression        and identify the identifiers and operators */%{ #include <stdio.h> #include <string.h>     int operators_count = 0, operands_count = 0, valid = 1, top = -1, l = 0, j = 0;     char operands[10][10], operators[10][10], stack[100]; %} %%"(" {     top++;     stack[top] = '('; } "{" {    top++;     stack[top] = '{'; } "[" {     top++;     stack[top] = '['; } ")" {     if (stack[top] != '(') {         valid = 0;         }     else if(operands_count>0 && (operands_count-operators_count)!=1){        valid=0;    }    else{        top--;        operands_count=1;        operators_count=0;    } } "}" {     if (stack[top] != '{') {         valid = 0;         }     else if(operands_count>0 && (operands_count-operators_count)!=1){        valid=0;    }    else{        top--;        operands_count=1;        operators_count=0;    } } "]" {     if (stack[top] != '[') {         valid = 0;     }     else if(operands_count>0 && (operands_count-operators_count)!=1){        valid=0;    }    else{        top--;        operands_count=1;        operators_count=0;    }           } "+"|"-"|"*"|"/" {     operators_count++;     strcpy(operators[l], yytext);     l++; } [0-9]+|[a-zA-Z][a-zA-Z0-9_]* {     operands_count++;     strcpy(operands[j], yytext);     j++; } %%     int yywrap() {     return 1; } int main() {     int k;     printf("Enter the arithmetic expression: ");     yylex();       if (valid == 1 && top == -1) {         printf("\nValid Expression\n");     }     else        printf("\nInvalid Expression\n");       return 0;} 
Output:
ajay_singhroha
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Symbol Table in Compiler
Code Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Intermediate Code Generation in Compiler Design
Introduction of Compiler Design
Types of Parsers in Compiler Design
Syntax Directed Translation in Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
C | Pointer Basics | Question 2 - GeeksforGeeks

04 Feb, 2013
Output of following program?
# include <stdio.h>void fun(int *ptr){    *ptr = 30;}  int main(){  int y = 20;  fun(&y);  printf("%d", y);    return 0;}
(A) 20(B) 30(C) Compiler Error(D) Runtime ErrorAnswer: (B)Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&y)’, address of y is passed so that y can be modified using its address.
C-Pointers
Pointers
C Language
C Quiz
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
Output of C programs | Set 64 (Pointers)
C | Arrays | Question 7
Java Examples - Create eventlistener in Applet

How to create an event listener in Applet?
Following example demonstrates how to create a basic Applet having buttons to add & subtract two nos. Methods used here are addActionListener() to listen to an event(click on a button) & Button() construxtor to create a button.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventListeners extends Applet implements ActionListener {
   TextArea txtArea;
   String Add, Subtract;
   int i = 10, j = 20, sum = 0, Sub = 0;
   
   public void init() {
      txtArea = new TextArea(10,20);
      txtArea.setEditable(false);
      add(txtArea,"center");
      Button b = new Button("Add");
      Button c = new Button("Subtract");
      b.addActionListener(this);
      c.addActionListener(this);
      add(b);
      add(c);
   }
   public void actionPerformed(ActionEvent e) {
      sum = i + j;
      txtArea.setText("");
      txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");
      Button source = (Button)e.getSource();
      
      if(source.getLabel() == "Add") {
         txtArea.append("Sum : " + sum + "\n");
      }
      if(i > j) { 
         Sub = i - j;
      } else {
         Sub = j - i;
      }
      if(source.getLabel() == "Subtract") {
         txtArea.append("Sub : " + Sub + "\n");
      }
   }
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser. 

 Print
 Add Notes
 Bookmark this page
Add some emphasis to a paragraph with Bootstrap

The lead class in Bootstrap is used to add emphasis to a paragraph.
You can try to run the following code to implement the lead class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap lead class</title>
      <meta name = "viewport" content="width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h2>Heading Two</h2>
      <p class = "lead"> This is an example paragraph demonstrating the use of lead body copy.
      </p>
   </body>
</html>
Scala Char isDigit() method with example - GeeksforGeeks

29 Oct, 2019
The isDigit() method is utilized to check if the stated character is digit or not.
Method Definition: def isDigit: Boolean
Return Type: It returns true if the stated character is digit else it returns false.
Example: 1#
// Scala program of isDigit()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isDigit method        val result = '9'.isDigit                  // Displays output        println(result)          }} 
true

Example: 2#
// Scala program of isDigit()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isDigit method        val result = 'g'.isDigit                  // Displays output        println(result)          }} 
false

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Lists
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Scala Singleton and Companion Objects
Operators in Scala
Scala Constructors
How to install Scala on Windows?
Hello World in Scala
Scala | Option
Find rows that have the same value on a column in MySQL?

First, we will create a table and insert some values into the table. Let us create a table.
mysql> create table RowValueDemo
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert records using the insert command. We have added duplicate values as well for our example.
mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.14 sec)

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.14 sec)

mysql> insert into RowValueDemo values('Carol');
Query OK, 1 row affected (0.11 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.24 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.18 sec)
Displaying all records with the help of select statement.
mysql> select *from RowValueDemo;
Here is the output.
+-------+
| Name  |
+-------+
| John  |
| Bob   |
| Carol |
| John  |
| John  |
| John  |
| Bob   |
| Bob   |
+-------+
8 rows in set (0.00 sec)

Now, we ill get only the rows that have same value for column using the following query −
mysql> select * from RowValueDemo where Name in (
   ->  select Name from RowValueDemo
   ->  group by Name having count(*) > 1
   -> );
The following is the output.
+------+
| Name |
+------+
| John |
| Bob  |
| John |
| John |
| John |
| Bob  |
| Bob  |
+------+
7 rows in set (0.06 sec)