code-rag-bench/online-tutorials huggingface dataset:
How to list all files (only) from a directory using Java?

The ListFiles() method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
The File Filter interface is filter for the path names you can pass this as a parameter to the listFiles() method. This method filters the file names passed on the passed filter.
To get the files in a folder implement a FileFilter which accepts only files and pass it as a parameter to the listFiles() method.
Following is a screen shot of the contents of the ExampleDirectory
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class Demo{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\\ExampleDirectory");
    //Creating filter for directories files
    FileFilter fileFilter = new FileFilter(){
         public boolean accept(File dir) {          
            if (dir.isFile()) {
               return true;
            } else {
               return false;
            }
         }
      };        
      File[] list = directoryPath.listFiles(fileFilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(File fileName : list) {
         System.out.println(fileName);
      }  
   }
}
List of the jpeg files in the specified directory:
D:\ExampleDirectory\demo1.pdf
D:\ExampleDirectory\demo2.pdf
D:\ExampleDirectory\sample1.txt
D:\ExampleDirectory\sample2.txt
D:\ExampleDirectory\sample3.txt
D:\ExampleDirectory\sample_jpeg1.jpg
D:\ExampleDirectory\sample_jpeg2.jpg
D:\ExampleDirectory\test1.docx
D:\ExampleDirectory\test2.docx
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ListOfFiles {
   public static void main(String[] args) throws IOException {
      Stream<Path> path = Files.walk(Paths.get("D:\\ExampleDirectory"));
      path = path.filter(Files::isRegularFile);
      path.forEach(System.out::println);
    }
}
D:\ExampleDirectory\demo1.pdf
D:\ExampleDirectory\demo2.pdf
D:\ExampleDirectory\sample1.txt
D:\ExampleDirectory\sample2.txt
D:\ExampleDirectory\sample3.txt
D:\ExampleDirectory\sample_jpeg1.jpg
D:\ExampleDirectory\sample_jpeg2.jpg
D:\ExampleDirectory\test1.docx
D:\ExampleDirectory\test2.docx
ExpressJS - URL Building

We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them.
Here is an example of a dynamic route −
var express = require('express');
var app = express();

app.get('/:id', function(req, res){
   res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);
To test this go to http://localhost:3000/123. The following response will be displayed.
You can replace '123' in the URL with anything else and the change will reflect in the response. A more complex example of the above is −
var express = require('express');
var app = express();

app.get('/things/:name/:id', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);
To test the above code, go to http://localhost:3000/things/tutorialspoint/12345.
You can use the req.params object to access all the parameters you pass in the url. Note that the above 2 are different paths. They will never overlap. Also if you want to execute code when you get '/things' then you need to define it separately.
You can also use regex to restrict URL parameter matching. Let us assume you need the id to be a 5-digit long number. You can use the following route definition −
var express = require('express');
var app = express();

app.get('/things/:id([0-9]{5})', function(req, res){
   res.send('id: ' + req.params.id);
});

app.listen(3000);
Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a "Cannot GET <your-request-route>" message as response. This message be replaced by a 404 not found page using this simple route −
var express = require('express');
var app = express();

//Other routes here
app.get('*', function(req, res){
   res.send('Sorry, this is an invalid URL.');
});
app.listen(3000);
Important − This should be placed after all your routes, as Express matches routes from start to end of the index.js file, including the external routers you required.
For example, if we define the same routes as above, on requesting with a valid URL, the following output is displayed. −
While for an incorrect URL request, the following output is displayed.

    16 Lectures 
     1 hours 

 Anadi Sharma
 Print
 Add Notes
 Bookmark this page
Initialization, declaration and assignment terms in Java

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form of a variable declaration − data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
int a, b, c;            // Declares three ints, a, b, and c.
int a = 10, b = 10;     // Example of initialization
byte B = 22;            // initializes a byte type variable B.
double pi = 3.14159;    // declares and assigns a value of PI.
char a = 'a';           // the char variable a is initialized with value a
LISP - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. LISP allows numerous operations on data, supported by various functions, macros and other constructs.
The operations allowed on data could be categorized as −
Arithmetic Operations
Comparison Operations
Logical Operations
Bitwise Operations
The following table shows all the arithmetic operators supported by LISP. Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Following table shows all the relational operators supported by LISP that compares between numbers. However unlike relational operators in other languages, LISP comparison operators may take more than two operands and they work on numbers only.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Common LISP provides three logical operators: and, or, and not that operates on Boolean values. Assume A has value nil and B has value 5, then −
Show Examples
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for bitwise and, or, and xor operations are as follows −
Show Examples
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A and B = 0000 1100
A or B = 0011 1101
A xor B = 0011 0001
not A  = 1100 0011
The Bitwise operators supported by LISP are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Explain Binding of a variable in C language.

Storage classes specify the scope, lifetime and binding of variables.
To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.
A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable.
Storage class tells us the following factors −
Where the variable is stored (in memory or cpu register)?
What will be the initial value of variable, if nothing is initialized?
What is the scope of variable (where it can be accessed)?
What is the life of a variable?
Binding finds the corresponding binding occurrence (declaration/definition) for an applied occurrence (usage) of an identifier.
Scope of variables should be known.
What is the block structure?
In which block the identifier is variable?
What will happen if we use same identifier name again?
‘C’ forbids use of same identifier name in the same scope.
Same name can be used in different scopes.
double f,y;
int f( ) //error {
   ---
   ----
   ----
}
double y; //error
double y;
int f( ){
   double f;//legal
   int y; //legal
}
Following is the C program for binding of a variable −
 Live Demo
#include<stdio.h>
int i=33;
main() {
   extern int i; {
      int i=22; {
         const volatile unsigned i=11;
         printf("i=%d\n",i);
      }
      printf("i=%d",i);
   }
}
When the above program is executed, it produces the following output −
i=11
i=22
Write program to reverse a String without using reverse() method in Java?

You can reverse a String in several ways, without using the reverse() function.
Using recursion − Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. You can reverse a string using recursive function as shown in the following program.
import java.util.Scanner;
public class StringReverse {
   public static String reverseString(String str){
      if(str.isEmpty()){
         return str;
      }else{
         return reverseString(str.substring(1))+str.charAt(0);
      }
   }
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      String result = StringReverse.reverseString(str);
      System.out.println(result);
   }
}
Enter a String value:
Tutorialspoint
tniopslairotuT
Converting to byte/character array: You can get a byte or, character array using the getBytes() or, toCharArray() methods respectively.
To reverse a given String
convert it into an array.
Reverse the elements of the array.
Create another String using the resultant array.
import java.util.Scanner;
public class StringReverse {
   public static String reverseString(String str){
      //Converting to character array
      char ch[] = str.toCharArray();
      int n = ch.length;
      char result[] = new char[n];
      for(int i = 0; i<ch.length; i++) {
         result[n-1] = ch[i];
         n = n - 1;
      }
      return new String(result);
   }
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      String result = StringReverse.reverseString(str);
      System.out.println(result);
   }
}
Enter a String value:
Tutorialspoint
tniopslairotuT
Accessing Values of Strings in Python

Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
 Live Demo
#!/usr/bin/python
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
MySQLi - Drop Database

You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.
Be careful while deleting any database because you will lose your all the data available in your database.
Here is an example to delete a database(TUTORIALS) created in the previous chapter −
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******

This will give you a warning and it will confirm if you really want to delete this database or not.
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'TUTORIALS' database [y/N] y
Database "TUTORIALS" dropped

PHP uses mysqli query() or mysql_query() function to drop a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli→query($sql,$resultmode)

$sql
Required - SQL query to drop a MySQL database.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to drop a database −
Copy and paste the following example as mysql_example.php −
<html>
   <head><title>Dropping MySQL Database</title></head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');

         if ($mysqli->query("Drop DATABASE TUTORIALS")) {
            printf("Database TUTORIALS dropped successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not drop database: %s<br />", $mysqli->error);
         }
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS dropped successfully.


    14 Lectures 
     1.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to create a boxplot with outliers of larger size in R?

When we create a boxplot for a column of an R data frame that contains outlying values, the points for those values are smaller in size by default. If we want to increase the size for those outlying points then outlier.size argument can be used inside geom_boxplot function of ggplto2 package.
Consider the below data frame −
 Live Demo
set.seed(1231)
x<-sample(LETTERS[1:4],20,replace=TRUE)
y<-c(rnorm(19,5,1),10)
df<-data.frame(x,y)
df
x y
1 B 5.983562
2 A 4.571819
3 D 6.110019
4 A 4.074785
5 A 6.034136
6 B 5.351433
7 C 4.596340
8 C 3.375895
9 D 4.849060
10 A 4.723585
11 B 5.406556
12 A 6.254387
13 B 6.408786
14 C 5.386244
15 D 4.215608
16 A 4.576638
17 B 5.688985
18 B 3.839879
19 C 5.914120
20 B 10.000000
Loading ggplot2 package and creating boxplots for y values based on categories in x with default size of outliers −
library(ggplot2) ggplot(df,aes(x,y,col=x))+geom_boxplot()
Creating the boxplots with larger size of outlier −
ggplot(df,aes(x,y))+geom_boxplot(outlier.size=5)
Create a Box Plot with SeaBorn – Python Pandas

Box Plot in Seaborn is used to draw a box plot to show distributions with respect to categories. The seaborn.boxplot() is used for this.
Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv
At first, import the required 3 libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame:
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

# plotting box plot with Age and Heigh
sb.boxplot( dataFrame['Age'],dataFrame['Height'] )

# set label for y i.e. Height
plt.ylabel("Height (inches)")

# display
plt.show()
This will produce the following output −
Let us see another example −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame:
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

# plotting box plot with Age
sb.boxplot( dataFrame['Age'] )
plt.show()
This will produce the following output −
Next.js - Api Routes

API Routes is a way to create rest API using Next.js. Next.js maps any file present in /pages/api folder and will be treated as API end point. An example of API function − 
export default (req, res) => {
   ...
}
 Following are some important points to consider.
req − req is an instance of http.IncomingMessage and is used to get data from request.
req − req is an instance of http.IncomingMessage and is used to get data from request.
res − res is an instance of http.ServerResponse and is used to send data as response.
res − res is an instance of http.ServerResponse and is used to send data as response.
Let's create an example to demonstrate the same.
In this example, we are going to create an user.js in pages/api directory.
Let's update the nextjs project used in Global CSS Support chapter.
Create user.js file in pages/api directory as following.
export default (req, res) => {
   res.statusCode = 200
   res.setHeader('Content-Type', 'application/json')
   res.end(JSON.stringify({ name: 'Robert' }))
}
Run the following command to start the server −.
npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
event - build page: /api/user
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

Open localhost:3000/api/user in a browser and you will see the following output.
{"name":"Robert"}

 Print
 Add Notes
 Bookmark this page
sciPy stats.alpha() | Python - GeeksforGeeks

14 Mar, 2019
scipy.stats.alpha() is an alpha continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :q : lower and upper tail probabilityx : quantilesa : shape parameterloc : [optional] location parameter. Default = 0scale : [optional] scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : alpha continuous random variable
Code #1 : Creating alpha continuous random variable
# Python code to demonstrate scipy.alpha()from scipy.stats import alpha  # using alpha() methodnumargs = alpha.numargs[ a ] = [0.6, ] * numargsrv = alpha(a)
Code #2 :
# Python code to demonstrate scipy.alpha()import numpy as npimport matplotlib.pyplot as plt  # getting distribution using linspace()distribution = np.linspace(0, np.minimum(rv.dist.b, 3))plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Deleting a binary tree using the delete keyword - GeeksforGeeks

26 Jul, 2018
A recursive and a non-recursive program to delete an entire binary tree has already been discussed in the previous posts. In this post, deleting the entire binary tree using the delete keyword in C++ is discussed.
Declare a destructor function in the ‘BinaryTreeNode’ class which has been defined to create a tree node. Using ‘delete’ keyword on an object of a class deletes the entire binary tree., it’s destructor is called within the destructor. Use the ‘delete’ keyword for the children; so the destructors for the children will be called one by one, and the process will go on recursively until the entire binary tree is deleted. Consider the tree shown below, as soon as the destructor is called for the root i.e., ‘1’, it will call the destructors for ‘2’ and ‘3’, and 2 will then call the same for its left and right child with data ‘4’ and ‘5’ respectively. Eventually, the tree will be deleted in the order: 4->5->2->3->1 (Post-order)
Below is the C++ implementation of the above approach:
// C++ program to delete the entire binary// tree using the delete keyword#include <iostream>using namespace std;  class BinaryTreeNode {      // Making data members public to    // avoid the usage of getter and setter functionspublic:    int data;    BinaryTreeNode* left;    BinaryTreeNode* right;      // Constructor function to    // assign data to the node    BinaryTreeNode(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }      // Destructor function to delete the tree    ~BinaryTreeNode()    {        // using keyword to delete the tree        delete left;        delete right;          // printing the node which has been deleted        cout << "Deleting " << this->data << endl;    }};  // Driver Codeint main(){    // Creating the nodes dynamically    BinaryTreeNode* root = new BinaryTreeNode(1);    BinaryTreeNode* node1 = new BinaryTreeNode(2);    BinaryTreeNode* node2 = new BinaryTreeNode(3);    BinaryTreeNode* node3 = new BinaryTreeNode(4);    BinaryTreeNode* node4 = new BinaryTreeNode(5);      // Creating the binary tree    root->left = node1;    root->right = node2;    node1->left = node3;    node1->right = node4;      // Calls the destructor function which actually deletes the tree entirely    delete root;      return 0;}
Deleting 4
Deleting 5
Deleting 2
Deleting 3
Deleting 1

Binary Tree
C++-Constructors
C++-Destructors
Delete Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Top 50 Tree Coding Problems for Interviews
Find the node with minimum value in a Binary Search Tree
Print Binary Tree in 2-Dimensions
Real-time application of Data Structures
Find maximum (or minimum) in Binary Tree
Iterative Postorder Traversal | Set 2 (Using One Stack)
Difference between Min Heap and Max Heap
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Python | Combining values from dictionary of list - GeeksforGeeks

06 Mar, 2019
Given a dictionary of list values, the task is to combine every key-value pair in every combination.
Input :{“Name” : [“Paras”, “Chunky”],“Site” : [“Geeksforgeeks”, “Cyware”, “Google”] }
Output:[{‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Paras’}, {‘Site’: ‘Cyware’, ‘Name’: ‘Paras’},{‘Site’: ‘Google’, ‘Name’: ‘Paras’}, {‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Chunky’},{‘Site’: ‘Cyware’, ‘Name’: ‘Chunky’}, {‘Site’: ‘Google’, ‘Name’: ‘Chunky’}]
Method #1: Using itertools and sorting
# Python code to combine every key value# pair in every combinations  # List initializationInput = {"Bool" : ["True", "False"],"Data" : ["Int", "Float", "Long Long"],}  # Importingimport itertools as it  # Sorting inputsorted_Input = sorted(Input)  # Using product after sortingOutput = [dict(zip(sorted_Input, prod))           for prod in it.product(*(Input[sorted_Input]          for sorted_Input in sorted_Input))]  # Printing outputprint(Output)
[{‘Bool’: ‘True’, ‘Data’: ‘Int’}, {‘Bool’: ‘True’, ‘Data’: ‘Float’}, {‘Bool’: ‘True’, ‘Data’: ‘Long Long’}, {‘Bool’: ‘False’, ‘Data’: ‘Int’}, {‘Bool’: ‘False’, ‘Data’: ‘Float’}, {‘Bool’: ‘False’, ‘Data’: ‘Long Long’}]
 Method #2: Using Zip
# Python code to combine every key value# pair in every combinations  # Importingimport itertools  # Input InitializationInput = {"Bool" : ["True", "False"],"Data" : ["Int", "Float", "Long Long"],}  # using zip and product without sortingOutput = [[{key: value} for (key, value) in zip(Input, values)]               for values in itertools.product(*Input.values())]                  # Printing outputprint(Output)
[[{‘Data’: ‘Int’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Int’}, {‘Bool’: ‘False’}], [{‘Data’: ‘Float’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Float’}, {‘Bool’: ‘False’}], [{‘Data’: ‘Long Long’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Long Long’}, {‘Bool’: ‘False’}]]
Python dictionary-programs
Python
Python Programs
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python program to convert hex string to decimal - GeeksforGeeks

20 May, 2019
In Python, element conversion has been a very useful utility as it offers it in a much simpler way that other languages. This makes Python a robust language and hence knowledge of interconversions is always a plus for a programmer. This article discusses the hexadecimal string to a decimal number. Let’s discuss certain ways in which this can be performed.
Method #1 : Using int()
This function can be used to perform this particular task, adding an argument (16) this function can convert hexadecimal string number to base sixteen and convert it into integer at the same time.
# Python3 code to demonstrate# converting hexadecimal string to decimal# Using int()  # initializing string test_string = 'A'  # printing original string print("The original string : " + str(test_string))  # using int()# converting hexadecimal string to decimalres = int(test_string, 16)  # print resultprint("The decimal number of hexadecimal string : " + str(res))
The original string : A
The decimal number of hexadecimal string : 10

 
Method #2 : Using ast.literal_eval()
We can perform this particular function by using literal evaluation function that predicts the base and converts the number string to its decimal number format.
# Python3 code to demonstrate# converting hexadecimal string to decimal# Using ast.literal_eval()from ast import literal_eval  # initializing string test_string = '0xA'  # printing original string print("The original string : " + str(test_string))  # using ast.literal_eval()# converting hexadecimal string to decimalres = literal_eval(test_string)  # print resultprint("The decimal number of hexadecimal string : " + str(res))
The original string : A
The decimal number of hexadecimal string : 10

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Quickly check if two STL vectors contain same elements or not - GeeksforGeeks

16 Jul, 2021
Unlike normal C/C++ arrays, we don’t need to do element by element comparison to find if two given vectors contain same elements or not.In case of vectors, the operator “==” is overloaded to find the result quickly. Below is an example to demonstrate same. 
C++14
// C++ implementation to check whether elements// in vector is equal or not#include<bits/stdc++.h>using namespace std; // Check if all elements is equal or notint main(){  // Comparing equal vectors  vector<int> v1{3, 1, 2, 3};  vector<int> v2{3, 1, 2, 3};  (v1 == v2)?  cout << "Equal\n" : cout << "Not Equal\n";     // Comparing non-equal vectors  vector<int> v3{1, 2, 3, 4};  (v1 == v3)?  cout << "Equal\n" : cout << "Not Equal\n";     // comparing with empty  vector<int> v4;  (v1 == v4)?  cout << "Equal\n" : cout << "Not Equal\n";   // comparing two empty  vector<int> v5;  (v5 == v4)?  cout << "Equal\n" : cout << "Not Equal\n";    return 0;}
Output: 
Equal
Not Equal
Not Equal
Equal
This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
arunn19013
STL
C++
STL
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++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
Random nextDouble() method in Java with Examples - GeeksforGeeks

07 Jan, 2019
The nextDouble() method of Random class returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator’s sequence.
Syntax:
public double nextDouble()  

Parameters: The function does not accepts any parameter.
Return Value: This method returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator’s sequence.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
Program 1:
// program to demonstrate the// function java.util.Random.nextDouble()  import java.util.*;public class GFG {    public static void main(String[] args)    {          // create random object        Random r = new Random();          // check next double value  and print it        System.out.println("Next double value is = "                           + r.nextDouble());    }}
Next double value is = 0.10210556893379474

Program 2:
// program to demonstrate the// function java.util.Random.nextDouble()  import java.util.*;public class GFG {    public static void main(String[] args)    {          // create random object        Random r = new Random();          // check next double value  and print it        System.out.println("Next double value is = "                           + r.nextDouble());    }}
Next double value is = 0.26964189606000966

Java-Functions
Java-Random
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream 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
Multithreading in Java
Collections in Java
What are RuntimeErrors  in Python?

A syntax error happens when Python can't understand what you are saying. A run-time error happens when Python understands what you are saying, but runs into trouble when following your instructions. This is called a run-time error because it occurs after the program starts running.
A program or code may be syntactically correct and may not throw any syntax error. This code may still show error after it starts running.
The given code can be corrected as follows
a = input('Enter a number:')
b = input('Enter a number:')
c = a*b
print c
The output we get is as follows
"C:/Users/TutorialsPoint1/~.py"
Enter a number:7
Enter a number:8
56
Calculate Pi with Python - GeeksforGeeks

19 May, 2021
Pi is an irrational number having non-recurring decimal values. We commonly know Pi=3.14 or Pi=22/7, but it is just an approximation for our ease. There are two methods to calculate the value of pi in python:
Method 1: Using Leibniz’s formula
The formula is –
This series is never-ending, the more the terms this series contains, the closer the value of X converges to Pi value.
Approach:
Initialize k=1 // this variable will be used as the denominator of leibniz’s formula, it will be incremented by 2
Initialize sum=0 // sum will add all the elements of the series
Run a for loop from 0 to 1000000 //at this value, we get the most accurate value of Pi
Inside for loop, check if i%2==0 then do sum=sum+4/k
Else, do sum=sum-4/k
Increment k by 2, go to step 3
Below is the implementation:
Python3
# Initialize denominatork = 1 # Initialize sums = 0 for i in range(1000000):     # even index elements are positive    if i % 2 == 0:        s + = 4/k    else:         # odd index elements are negative        s -= 4/k     # denominator is odd    k += 2     print(s)
Output:
3.1415916535897743
Method 2: Using acos() methods.
Approach:
The value of Π is calculated using acos() function which returns a numeric value between [-Π, Π].Since using acos(0.0) will return the value for 2*Π. Therefore to get the value of Π:
The value of Π is calculated using acos() function which returns a numeric value between [-Π, Π].
Since using acos(0.0) will return the value for 2*Π. Therefore to get the value of Π:
 pi = round(2*acos(0.0));
Below is the implementation:
Python3
# Python3 program to calculate the# value of pi up to 3 decimal placesfrom math import acos # Function that prints the# value of pi upto N# decimal placesdef printValueOfPi():     # Find value of pi upto 3 places    # using acos() function    pi = round(2 * acos(0.0), 3)     # Print value of pi upto    # N decimal places    print(pi)  # Driver Codeif __name__ == "__main__":     # Function that prints    # the value of pi    printValueOfPi()
Output:
3.142
Method 3: Using NumPy
In this method, we will use numpy.pi methods to calculate the pi value.
Python3
import numpy print( numpy.pi )
 
 
Output:
 
3.141592653589793
 
Method 4: Using math module
 
Python has an inbuilt library named math we can simply import math and print the value of pi.
 
Python3
import math print( math.pi )
Output:
3.141592653589793
arorakashish0911
Technical Scripter 2020
Mathematical
Python
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Fabric.js | Rect width Property - GeeksforGeeks

13 May, 2022
In this article, we are going to see how to set the width of a canvas rectangle using FabricJS. The canvas means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, fill color, stroke width or size. 
To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and set the width of the canvas rectangle using width property and render the Rect on the Canvas as given in the example below. Syntax:
fabric.Rect({
    width: number,
    height: number
}); 
Parameters: This function accepts two parameters as mentioned above and described below:
width: It specifies the horizontal length.
height: It specifies the vertical length.
Example: This example uses FabricJS to set width of the canvas rectangle. 
html
<!DOCTYPE html><html> <head>    <title>        Fabric.js | Rect width Property    </title>     <!-- FabricJS CDN -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head> <body>    <div style="text-align: center;width: 600px;">        <h1 style="color: green;">            GeeksforGeeks        </h1>        <b>            Fabric.js | Rect width Property        </b>    </div>     <div style="text-align: center;">    <canvas id="canvas" width="600" height="200"            style="border:1px solid #000000;">    </canvas>    </div>     <script>        // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");         // Initiate a Rect instance        var rect = new fabric.Rect({            width: 400,            height: 100        });         // Render the rectangle in canvas        canvas.add(rect);    </script></body> </html>                  
Output:
 
blalverma92
Fabric.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
HTML | <td> bgcolor Attribute - GeeksforGeeks

17 Mar, 2022
The HTML <td> bgcolor attribute is used to specify the background color of a table cell. It is not supported by HTML 5.
Syntax:
<td bgcolor= "color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the text color by using the color name. For example “red”.
hex_number: It sets the text color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)”.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML <td> bgcolor Attribute</title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML bgcolor align Attribute</h2>      <table width="500" border="1">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>          <tr>            <td bgcolor="green">BITTU</td>            <td bgcolor="red">22</td>            <td bgcolor="yellow">CSE</td>        </tr>          <tr>            <td bgcolor="yellow">RAKESH</td>            <td bgcolor="green">25</td>            <td bgcolor="red">EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <td> bgcolor attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
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 ?
Difference between var, let and const keywords in JavaScript
Node.js console.error() Function - GeeksforGeeks

14 Oct, 2021
The console.error() function from console class of Node.js is used to display an error messages on the console. It prints to stderr with newline.Syntax: 
console.error([data][, ...args])
Parameter: This function can contains multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution values.Return Value: The function returns an error message.Below programs demonstrates the working of console.error() function:Program 1: 
javascript
// Store number to variablenum = 20  // Check conditionif (num < 100) {    console.log("Enter number greater then 100");}else {    console.error("correct choice");}        
Output: 
Enter number greater then 100
Program 2: 
javascript
// Store number to variablex = 20;y = 50;  // Check conditionif (x > y) {    console.error('%d is greater then %d', x, y);}else {    console.error('%d is less then or equal to %d', x, y);}
Output: 
20 is less then or equal to 50
simmytarika5
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
Resize an iframe based on the content - GeeksforGeeks

10 Jun, 2019
The iframe HTML element is often used to insert contents from another source. Contents which needs resizing is done indirectly using a div tag. The trick is to initiate with a div tag and enclose within an iframe tag. Now provide iframe with CSS.Note: To open the source site to resize its contents, the source site must be listed in the same directory.
Example 1: Below is the implementation of HTML code to resize contents using Internal CSS:-
<html>  <head>    <style>        body {            background-color: LIGHTGREY;        }                  #target {            width: 300px;            height: 200px;            overflow-y: auto;            overflow-x: auto;            resize: both;            position: relative;            z-index: 2;        }                  iframe {            width: 100%;            height: 100%;            border: none;        }    </style>  </head>  <body>    <div id="target">        <iframe src="/tryit.php"></iframe>    </div></body>  </html>
Output:
Here we have used an internal style sheet to fix the dimension of displaying area as width and height in pixels under target. CSS overflow property controls the contents that are too big to fit into an area.
Example 2: Below is the implementation of HTML code to resize contents, using Javascript:-We will use JavaScript contentWindow property that will iFrame automatically adjust its height according to the contents, no scrollbars will appear.
We select iframe within script tag:var iframe = document.getElementById(“myIframe”);
We Adjust iframe height onload event by:iframe.onload = function(){}
<html>  <head>    <style>        div {            width: 50%;        }    </style></head>  <body>    <iframe src="/tryit.php" id="target">    </iframe>    <script>        var div = document.getElementById("target");        div.onload = function() {            div.style.height =              div.contentWindow.document.body.scrollHeight + 'px';        }    </script></body>  </html>
Output:
JavaScript-Misc
Picked
CSS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Aptitude | GATE CS 1998 | Question 10 - GeeksforGeeks

08 Jun, 2020
Which of the following sets can be recognized by a Deterministic Finite-state Automaton?(A) The number 1, 2, 4, 8......,2^n,.......... written in binary.(B) The number 1, 2, 4,....., 2^n,.......... written in unary.(C) The set of binary strings in which the number of zeros is the same as the number of ones.(D) The set {1, 101, 11011, 1110111,.......}Answer: (A)Explanation: If there is a infinite language and for that language if their is no any pattern exist then we can surely say that given language is not regular, but if pattern is exist for that language then it may or may not be regular language and for ensuring a given language is regular, if we are able to draw DFA for that language then surely it will be regular otherwise not regular,
Therefore option (A) is regular language as it can written in binary i.e.,
L = {1, 10, 100, 1000, 10000, ...} 
Regular expression is (10*), since, for this expression we can draw DFA.
So, option (A) is correct.Quiz of this Question
vivekkumarmth0077
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to find out which processes are using swap space in Linux?

Swap space is common in Linux, and it usually is used when the amount of the physical memory(RAM) is full. The idea behind the swap space is that if the operating system needs more memory resources and the RAM doesn’t have any space left, then the pages that are inactive will be moved to the swap space.
It should also be noted that while swap space definitely helps out the RAM on a short basis, they should not be considered a replacement for more RAM.
Now we know a bit about swap spaces, let’s talk about how we can detect which processes are using swap space in Linux.
There are many ways to know about the processes that are making use of swap space, the most basic approach is to use the top command and then press f,, scroll down to where it says SWAP press space followed by typing q.
Though it is recommended to either make use of shell script or use Linux utilities like smem.
SMEM on linux is a command-line utility that is used to provide diverse reports on memory usage on a lInux system.
In order to install smem on your local machine, follow the commands shown below −
For Ubuntu/Fedora −
sudo apt-get install smem
For CentOS −
yum install smem
smem [options]
When we run the command shown below, we will get different processes with their PIDs, Usernames, Commands and their swap memory usage.
smem
PID      User     Command               Swap    USS     PSS    RSS
46740  xxxxxxxx /usr/bin/php-cgi       2904      0       2      4
3623   root     ssh-agent-1             572      4       4      4
53398  xxxxxxx  /usr/bin/php-cgi       2748      4       4      8
53396  immukul  /usr/bin/go-cgi        2788      4       4      8
7855   root     rpc.rquotad             124      4       6    116
7380   root     ssh-agent-1             6e4      4       3    112
34802  root     ssh-agent-1             576      4       8      9
We can clearly notice that the process mentioned in the above output are making use of the swap space.
Another approach to get the processes that are using the swap space is to write a shell script.
Consider the script shown below which will print if any process of the directory that you provide is using a swap space.
SUM=0
OVERALL=0
for DIR in `find /usr/local/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"`
do
   PID=`echo $DIR | cut -d / -f 3`
   PROGNAME=`ps -p $PID -o comm --no-headers`
   for SWAP in `grep VmSwap $DIR/status 2 > /dev/null | awk '{ print $2 }'`
   do
      let SUM=$SUM + $SWAP
   done
   if (( $SUM > 0 )); then
      echo "PID=$PID swapped $SUM KB ($PROGNAME)"
   fi
   let OVERALL=$OVERALL + $SUM
   SUM=0
done
echo "Overall swap used on machine : $OVERALL KB"
Overall swap used on machine : 26067 KB
VBScript Trim Function

The Trim Function removes both the Leading and Trailing blank spaces of the given input string.
Trim(String)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("After Trim : " & Trim(var) & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
After trim : Microsoft VBScript


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page