code-rag-bench/online-tutorials huggingface dataset:
MongoDB Required Constraint using Node.js - GeeksforGeeks

04 Mar, 2021
Mongoose module is one of the most powerful external modules of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database (Refer this Link)
Required Constraint: This constraint does not allow to skip the value of a particular key in the document of MongoDB collection. This constraint same as a not-null constraint in MySQL.
Installing Module: Install the required module using the following command.
npm install mongoose
Project Structure: Our project structure will look like this.
Running Server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
index.js
// Importing mongoose moduleconst mongoose = require("mongoose")  // Database Addressconst url = "mongodb://localhost:27017/GFG"  // Connecting to databasemongoose.connect(url).then((ans) => {  console.log("Connected Successful")}).catch((err) => {  console.log("Error in the Connection")})  // Calling Schema classconst Schema = mongoose.Schema;  // Creating Structure of the collectionconst collection_structure = new Schema({  name: {    type: String,    required: true  },  marks: {    type: Number  }})  // Creating collectionconst collections = mongoose.model("GFG2", collection_structure)  // Inserting one documentcollections.create({  // Inserting value of only one key  marks: 3}).then((ans) => {  console.log(ans);}).catch((err) => {  console.log(err.message);})
Run index.js file using below command:
node index.js
Console output:
NodeJS-Questions
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
IP Addressing - GeeksforGeeks

02 Dec, 2021
	IPA BITWISE-AND Ms == IPBBITWISE-AND Ms

128.8.129.43 BITWISE-AND 255.255.31.0 = 128.8.1.0
128.8.161.55 BITWISE-AND 255.255.31.0 = 128.8.1.0

   List-I               List-II
A. 128.96.171.92     1. Interface 0
B. 128.96.167.151    2. Interface 1
C. 128.96.163.121    3. R2
D. 128.96.165.121    4. R3
                     5. R4
Codes:
     A B C D
(a)  1 3 5 4
(b)  1 4 2 5
(c)  2 3 4 5
(d)  2 3 5 4
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
How to redirect browser window back using JavaScript ?

07 Jun, 2022
In this article, we will redirect the browser window back using JavaScript. There are two approaches used to redirect the browser window back. 
Approach 1: Using history.back() Method: The back() method of the window.history object is used to go back to the previous page in the current session history. In case there is no previous page, this method does not call anything. The onclick event can be specified with this method to go back one page in history. 
Syntax:
history.back()
Example 1: This example uses history.back() method to redirect the browser into previous page. 
javascript
<html> <head>    <script>        function Previous() {            window.history.back()        }    </script></head> <body>     <input type="button"           value="GoBack"           onclick="Previous()"> </body> </html>
Output:
  
Approach 2: Using history.go() Method: The history.go() method of the window.history object is used to load a page from the session history. It can be used to move forward or backward using the value of the delta parameter. A positive delta parameter means that the page would go forward in history. Similarly, a negative delta value would make the page go back to the previous page. This method can be used with ‘-1’ as the delta value to go back one page in history. The onclick event can be specified with the method to go back one page in history. 
Syntax:
history.ho(number\URL)
Example 2: This example uses window.history.go() method to redirect the browser into previous page. 
javascript
<!DOCTYPE html><html> <body>    <button onclick="Previous()">Go Back 1 Page</button>    <script>        function Previous() {            window.history.go(-1);        }    </script></body> </html>
Output:
  
Note: This method will not work if the previous page does not exist in the history list. 
Supported Browsers: 
Google Chrome
Microsoft Edge
Firefox
Apple Safari
Opera
satyamm09
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Output of C++ Program | Set 8

27 Dec, 2016
Predict the output of following C++ programs.
Question 1
#include<iostream>using namespace std;  class Test1{    int x;public:    void show() {  }};  class Test2{    int x;public:    virtual void show() {  }};  int main(void){    cout<<sizeof(Test1)<<endl;    cout<<sizeof(Test2)<<endl;    return 0;}
Output:48There is only one difference between Test1 and Test2. show() is non-virtual in Test1, but virtual in Test2. When we make a function virtual, compiler adds an extra pointer vptr to objects of the class. Compiler does this to achieve run time polymorphism (See chapter 15 of Thinking in C++ book for more details). The extra pointer vptr adds to the size of objects, that is why we get 8 as size of Test2.
Question 2
#include<iostream>using namespace std;class P{public:    virtual void show() = 0;};  class Q : public P {    int x;};  int main(void){    Q q;    return 0;}
Output: Compiler ErrorWe get the error because we can’t create objects of abstract classes. P is an abstract class as it has a pure virtual method. Class Q also becomes abstract because it is derived from P and it doesn’t implement show().
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to kill all instances of a Node.js process via command line ?

09 Apr, 2021
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside the browser. It is widely used in developing APIs and microservices from small to large companies.
Why we need to kill all the instances?
Sometimes there may be some issue with the NodeJS like the server is listening to some other port or there may be some services which you want to run, but it shows an error like service is already running or process is already running. At that time you need to kill all the instances of the NodeJS server at that time. This method will help you to kill all the instances in NodeJS.
Command/CMD: Killings all instances of a NodeJS process via command line.
killall node
Example: Open the folder where we want to start the server.
Start the server and get the list of the same.
npx http-server
Running process: We can see this web-server is running on the NodeJS on the first URL.
Now let’s use the terminate command on the command prompt to see the results.
Here is a success message that the process is terminated.
Let’s open the web-server again. Now we can see at the same URL the process is not running now as the above command has killed all the nodes instances.
So here is an error on the same local address. By using the above command in CMD we can terminate or kill all instance of NodeJS process running.
Node.js-process-module
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Language | Set 8

27 Mar, 2017
Following questions have been asked in GATE CS 2011 exam.1) What does the following fragment of C-program print?
char c[] = "GATE2011";char *p =c;printf("%s", p + p[3] - p[1]) ;
(A) GATE2011(B) E2011(C) 2011(D) 011
Answer: (C)See comments for explanation.
char c[] = "GATE2011";  // p now has the base address string "GATE2011"char *p =c;  // p[3] is 'E' and p[1] is 'A'.  // p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4// So the expression  p + p[3] - p[1] becomes p + 4 which is // base address of string "2011"printf("%s", p + p[3] - p[1]) ; 
2) Consider the following recursive C function that takes two arguments
unsigned int foo(unsigned int n, unsigned int r) {  if (n  > 0) return (n%r +  foo (n/r, r ));  else return 0;}
What is the return value of the function foo when it is called as foo(513, 2)?(A) 9(B) 8(C) 5(D) 2
Answer: (D)foo(513, 2) will return 1 + foo(256, 2). All subsequent recursive calls (including foo(256, 2)) will return 0 + foo(n/2, 2) except the last call foo(1, 2) . The last call foo(1, 2) returns 1. So, the value returned by foo(513, 2) is 1 + 0 + 0.... + 0 + 1.The function foo(n, 2) basically returns sum of bits (or count of set bits) in the number n.
3) What is the return value of the function foo when it is called as foo(345, 10) ?(A) 345(B) 12(C) 5(D) 3
Answer: (B)The call foo(345, 10) returns sum of decimal digits (because r is 10) in the number n. Sum of digits for 345 is 3 + 4 + 5 = 12.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2011
GATE-CS-C-Language
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the typecode for enum in C#?

23 Jul, 2019
Enum.GetTypeCode Method is used to get the type code of the underlying type of this enumeration member.
Syntax:
public TypeCode GetTypeCode ();
Returns: This method returns type code of the underlying type of this instance.
Exception: This method will give InvalidOperationException if the enumeration type is unknown.
Example:
// C# program to illustrate the// Enum.GetTypeCode() Methodusing System;  class GFG {          enum Color {Blue, Black };      // Main Method    public static void Main(String[] args)    {        Color c1 = Color.Blue;        Console.Write("TypeCode of Enum Constant " + c1 + " : ");          // Using the GetTypeCode() Method        Console.WriteLine(c1.GetTypeCode());          Color c2 = Color.Black;        Console.Write("TypeCode of Enum Constant " + c2 + " : ");          // Using the GetTypeCode Method        Console.WriteLine(c2.GetTypeCode());    }}
TypeCode of Enum Constant Blue : Int32
TypeCode of Enum Constant Black : Int32

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.enum.gettypecode?view=netframework-4.8sfdsfsdf
CSharp-Enum-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert date record to the same table with different date formats with MySQL?

For this, you can use the INSERT INTO SELECT statement. To format the date, use the DATE_FORMAT() function. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> DateOfJoining datetime,
   -> JoiningDate text
   -> );
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(DateOfJoining) values('2019-10-26 13:52:10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(DateOfJoining) values('2018-12-31 15:20:40');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement−
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+-------------+
| DateOfJoining       | JoiningDate |
+---------------------+-------------+
| 2019-10-26 13:52:10 | NULL        |
| 2018-12-31 15:20:40 | NULL        |
+---------------------+-------------+
2 rows in set (0.00 sec)
Here is the query to insert date record to the same table with different date formats −
mysql> insert into DemoTable(JoiningDate) select date_format(DateOfJoining , '%W %e, %b %Y @ %r') from DemoTable;
Query OK, 2 rows affected (0.13 sec)
Records: 2 Duplicates: 0 Warnings: 0
Let us check the table records once again−
mysql> select *from DemoTable;
This will produce the following output−
+---------------------+-------------------------------------+
| DateOfJoining       | JoiningDate                         |
+---------------------+-------------------------------------+
| 2019-10-26 13:52:10 | NULL                                |
| 2018-12-31 15:20:40 | NULL                                |
| NULL                | Saturday 26, Oct 2019 @ 01:52:10 PM |
| NULL                | Monday 31, Dec 2018 @ 03:20:40 PM |
+---------------------+-------------------------------------+
4 rows in set (0.00 sec)
scipy stats.skewtest() function | Python

11 Feb, 2019
scipy.stats.skewtest(array, axis=0) function test whether the skew is different from the normal distribution. This function tests the null hypothesis that the skewness of the population that the sample was drawn from is the same as that of a corresponding normal distribution.
Its formula –
Parameters :array : Input array or object having the elements.axis : Axis along which the skewness test is to be computed. By default axis = 0.
Returns : Z-score (Statistics value) and P-value for the hypothesis test on data set.
Code #1:
# Performing skewtestfrom scipy.stats import skewtestimport numpy as np import pylab as p   x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2  )  p.plot(x1, y1, '*')    print( '\nSkewness test for given data :\n', skewtest(y1))
Output :


Skewness test for given data :
 SkewtestResult(statistic=11.874007880556805, pvalue=1.6153913086650964e-32)

 Code #2:
# Performing skewtestfrom scipy.stats import skewtestimport numpy as np import pylab as p   x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2  )  p.plot(x1, y1, '.')    print( '\nSkewness for data :\n', skewtest(y1))
Output :


Skewness for data :
 SkewtestResult(statistic=16.957642860709516, pvalue=1.689888374767126e-64)

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
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Iterate over a list in Python
Calculating the sum of all columns of a 2D NumPy array

02 Sep, 2020
Let us see how to calculate the sum of all the columns of a 2 dimensional NumPy array.
Example :
Input : 
[[1, 2, 3, 4, 5],
 [5, 6, 7, 8, 9],
 [2, 1, 5, 7, 8],
 [2, 9, 3, 1, 0]]
         
Output :  [10, 18, 18, 20, 22]

Input : 
[[5, 4, 1, 7],
 [0, 9, 3, 5], 
 [3, 2, 8, 6]]

Output : [8, 15, 12, 18]

Approach 1 : We will be using the sum() method. We will pass parameter axis = 0 to get the sum columns wise.
# importing numpyimport numpy as np  # initialize the 2-d arrayarr = np.array([[1, 2, 3, 4, 5],                [5, 6, 7, 8, 9],                [2, 1, 5, 7, 8],                [2, 9, 3, 1, 0]])  # calculating column wise sumsum_2d = arr.sum(axis = 0)  # displaying the sumprint("Column wise sum is :\n", sum_2d)
Output :
Column wise sum is :
 [10 18 18 20 22]

Approach 2 : We can also use the numpy.einsum() method, with parameter 'ij->j'.
# importing numpyimport numpy as np  # initialize the 2-d arrayarr = np.array([[1, 2, 3, 4, 5],                [5, 6, 7, 8, 9],                [2, 1, 5, 7, 8],                [2, 9, 3, 1, 0]])  # calculating column wise sumsum_2d = np.einsum('ij->j', arr)  # displaying the sumprint("Column wise sum is :\n", sum_2d)
Output :
Column wise sum is :
 [10 18 18 20 22]

Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Finding difference of greatest and the smallest digit in a number - JavaScript

We are required to write a JavaScript function that takes in a number and returns the difference between the greatest and the smallest digit present in it.
For example: If the number is 5464676, then the smallest digit here is 4 and the greatest is 7
Hence, our output should be 3
Let’s write the code for this function −
const num = 44353456;
const difference = (num, min = Infinity, max = -Infinity) => {
   if(num){
      const digit = num % 10;
      return difference(Math.floor(num / 10), Math.min(digit, min),
      Math.max(digit, max));
   };
   return max - min;
};
console.log(difference(num));
The output in the console: −
3
Tryit Editor v3.7

Tryit: HTML bold text
Underscore.js | _.isString() Function - GeeksforGeeks

27 Apr, 2020
The _.isString() function is used to check whether the given object element is string or not.
Syntax:
_.isString( object )
Parameters: This function accepts single parameter as mentioned above and described below:
object: It contains the value of object that need to be check whether it is an string or not.
Return Value: It returns a Boolean value True if given object element is string, False otherwise.
Example 1:
<!DOCTYPE html><html>  <head>    <script type="text/javascript"             src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          var info = {            Company: 'GeeksforGeeks',            Address: 'Noida',            Contact: '+91 9876543210'        };        console.log(_.isString(info));          var str = 'GeeksforGeeks';        console.log(_.isString(str));    </script></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <script type="text/javascript"             src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          console.log(_.isString(true));        console.log(_.isString(10));        console.log(_.isString('GeeksforGeeks'));        console.log(_.isString("20"));    </script></body>  </html>
Output:
JavaScript - Underscore.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
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
How to insert spaces/tabs in text using HTML/CSS?
How to edit a comboBox in JavaFX?

A combo box is similar to a choice box it holds multiple items and, allows you to select one of them. It can be formed by adding scrolling to a drop-down list. You can create a combo box by instantiating the javafx.scene.control.ComboBox class.
The ComboBox class has a method known as editable (boolean), which specifies whether the current Combobox allows user input. You can set the value to this property using the setEditable() method.
Therefore, to edit a JavaFX ComboBox invoke the setEditable() method on it by passing the boolean value true as a parameter.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
public class ComboBoxEditable extends Application {
   @Override
   public void start(Stage stage) {
      //Setting the label
      Label label = new Label("Select Desired Course:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a combo box
      ComboBox<String> combo = new ComboBox<String>();
      //Getting the observable list of the combo box
      ObservableList<String> list = combo.getItems();
      //Adding items to the combo box
      list.add("Java");
      list.add("C++");
      list.add("Python");
      list.add("Big Data");
      list.add("Machine Learning");
     //Setting the combo box editable
      combo.setEditable(true);
      HBox hbox = new HBox(15);
      //Setting the space between the nodes of a HBox pane
      hbox.setPadding(new Insets(75, 150, 50, 60));
      hbox.getChildren().addAll(label, combo);
      //Creating a scene object
      Scene scene = new Scene(new Group(hbox), 595, 280, Color.BEIGE);
      stage.setTitle("Combo Box");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
SQL - Having Clause

The HAVING Clause enables you to specify conditions that filter which group results appear in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause.
The following code block shows the position of the HAVING Clause in a query.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used. The following code block has the syntax of the SELECT statement including the HAVING clause −
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

Consider the CUSTOMERS table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would display a record for a similar age count that would be more than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
This would produce the following result −
+----+--------+-----+---------+---------+
| ID | NAME   | AGE | ADDRESS | SALARY  |
+----+--------+-----+---------+---------+
|  2 | Khilan |  25 | Delhi   | 1500.00 |
+----+--------+-----+---------+---------+


    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Bootstrap Pagination

If you have a web site with lots of pages, you may wish to add some sort of pagination to each page.
A basic pagination in Bootstrap looks like this:
1
2
3
4
5
To create a basic pagination, add the .pagination class to an <ul> element:
The active state shows what is the current page:
1
2
3
4
5
Add class .active to let the user know which page he/she is on:
A disabled link cannot be clicked:
1
2
3
4
5
Add class .disabled if a link for some reason is disabled:
Pagination blocks can also be sized to a larger size or a smaller size:
1
2
3
4
5
1
2
3
4
5
Add class .pagination-lg for larger blocks or .pagination-sm for smaller blocks:
Another form for pagination, is breadcrumbs:

Home
Private
Pictures
Vacation

Home
Private
Pictures
Vacation
The .breadcrumb class indicates the current page's location within a 
navigational hierarchy:
Add the correct class name to transform the list below into a pagination menu.
<ul class="">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
</ul>

Start the Exercise
For a complete reference of all navigation classes, go to our complete
Bootstrap Navigation Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to preview an image before and after upload in HTML and JavaScript?

To preview an image before and after upload, you need to try the following code − HTML
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id = "form1" runat = "server">
   <input type ='file' id = "demo" />
   <img id = "myid" src = "#" alt = "new image" />
</form>
The following is the jQuery −
function display(input) {
   if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(event) {
         $('#myid').attr('src', event.target.result);
      }
      reader.readAsDataURL(input.files[0]);
   }
}

$("#demo").change(function() {
   display(this);
});
How can we implement a moving text using a JLabel in Java?

A JLabel is a subclass of JComponent class and an object of JLabel provides text instructions or information on a GUI. A JLabel can display a single line of read-only text, an image or both text and an
image. A JLabel can explicitly generate a PropertyChangeListener interface. We can also implement a moving text in a JLabel by using a Timer class, it can set a timer with speed(in milliseconds) and this as an argument.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MovingTextLabel extends JFrame implements ActionListener {
   private JLabel label;
   public MovingTextLabel() {
      setTitle("MovingTextLabel");
      label= new JLabel(" Welcome to Tutorials Point ");
      label.setFont(new Font("Arial", 0, 25));
      add(label, BorderLayout.CENTER);
      Timer t = new Timer(400, this); // set a timer
      t.start();
      setSize(400, 300);
      setVisible(true);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void actionPerformed(ActionEvent e) {
      String oldText = label.getText();
      String newText= oldText.substring(1)+ oldText.substring(0,1);
      label.setText(newText);
   }
   public static void main (String[] args) {
      new MovingTextLabel();
   }
}
Python program to convert decimal to binary number - GeeksforGeeks

29 May, 2021
Given a decimal number as input, the task is to write a Python program to convert the given decimal number into an equivalent binary number.Examples : 
Input : 7                                                         
Output :111

Input :10
Output :1010
Method #1: Recursive solution
DecimalToBinary(num):
        if num >= 1:
            DecimalToBinary(num // 2)
           print num % 2 
Below is the implementation of the above recursive solution: 
Python3
# Function to convert decimal number# to binary using recursiondef DecimalToBinary(num):         if num >= 1:        DecimalToBinary(num // 2)    print(num % 2, end = '') # Driver Codeif __name__ == '__main__':         # decimal value    dec_val = 24         # Calling function    DecimalToBinary(dec_val)
011000
Method #2: Decimal to binary using in-built function 
Python3
# Python program to convert decimal to binary   # Function to convert Decimal number# to Binary numberdef decimalToBinary(n):    return bin(n).replace("0b", "")   # Driver codeif __name__ == '__main__':    print(decimalToBinary(8))    print(decimalToBinary(18))    print(decimalToBinary(7))
1000
10010
111
Method #3:Without in-built function
Python3
# Python program to convert decimal to binary   # Function to convert Decimal number# to Binary numberdef decimalToBinary(n):    return "{0:b}".format(int(n))   # Driver codeif __name__ == '__main__':    print(decimalToBinary(8))    print(decimalToBinary(18))    print(decimalToBinary(7))
Output
1000
10010
111
nidhi_biet
prashantrajpoot1931
vipinyadav15799
robot16gfx
base-conversion
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Minimum Cost For Tickets in C++

Suppose there is a country, that is popular for train travel, we have planned some train travelling one year in advance. We have an array, that is holding the days of the year that we will travel. Each day is an integer from 1 to 365. Train tickets are sold in three different ways −
A 1-day pass is sold for costs[0] dollars;
A 1-day pass is sold for costs[0] dollars;
A 1-day pass is sold for costs[0] dollars;
A 1-day pass is sold for costs[0] dollars;
A 30-day pass is sold for costs[2] dollars.
A 30-day pass is sold for costs[2] dollars.
Here the passes allow that many days of consecutive travel. For example, if we get one 7-day pass on day 2, then we can travel for 7 days: day consecutively (2, 3, 4, 5, 6, 7, and 8). We have to find the minimum number of dollars we need to travel every day in the given list of days. So if the input is like [1,4,6,7,8,20] and costs are [2,7,15], then the output will be 11.
On day 1, we have bought 1 day pass for costs[0] = 2,thatiscoveringday1,onday3,wehavebought7daypass,socost[1]=7, that is covering days 3 to 9, and on day 20, again bought a pass for 1 day, so cost[0] = 2,thatiscoveringday20.Sointotal11 are spent.
To solve this, we will follow these steps −
create one array called dp, of size 366
create one array called dp, of size 366
j := 0
j := 0
for i in range 1 to 366dp[i] := cost[0] + dp[i - 1]if i – 7 >= 0, then dp[i] := minimum of dp[i - 7] + cost[1] and dp[i]if i – 30 >= 0, then dp[i] := minimum of dp[i - 30] + cost[2] and dp[i]if j < size of the days array and days[j] = i, then increase j by 1, otherwise dp[i] := minimum of dp[i], dp[i – 1]
for i in range 1 to 366
dp[i] := cost[0] + dp[i - 1]
dp[i] := cost[0] + dp[i - 1]
if i – 7 >= 0, then dp[i] := minimum of dp[i - 7] + cost[1] and dp[i]
if i – 7 >= 0, then dp[i] := minimum of dp[i - 7] + cost[1] and dp[i]
if i – 30 >= 0, then dp[i] := minimum of dp[i - 30] + cost[2] and dp[i]
if i – 30 >= 0, then dp[i] := minimum of dp[i - 30] + cost[2] and dp[i]
if j < size of the days array and days[j] = i, then increase j by 1, otherwise dp[i] := minimum of dp[i], dp[i – 1]
if j < size of the days array and days[j] = i, then increase j by 1, otherwise dp[i] := minimum of dp[i], dp[i – 1]
return dp[365]
return dp[365]
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int mincostTickets(vector<int>& days, vector<int>& costs) {
      vector <int> dp(366);
      int j = 0;
      for(int i = 1; i < 366; i++){
         dp[i] = costs[0] + dp[i - 1];
         if(i - 7 >= 0){
            dp[i] = min(dp[i - 7] + costs[1], dp[i]);
         }
         if(i - 30 >= 0){
            dp[i] = min(dp[i - 30] + costs[2], dp[i]);
         }
         if(j < days.size() && days[j] == i){
            j++;
         }else
            dp[i] = min(dp[i], dp[i - 1]);
      }
      return dp[365];
   }
};
main(){
   vector<int> v = {1,4,6,7,8,20};
   vector<int> v1 = {2,7,15};
   Solution ob;
   cout << (ob.mincostTickets(v, v1));
}
[1,4,6,7,8,20]
[2,7,15]
11
Java Program to get Operating System name and version

Use the System.getProperty() method in Java to get the Operating System name and version.
It’s syntax is −
String getProperty(String key)
Above, the key is the name of the system property. Since, we want the OS name and version, therefore we will add the key as −
Operating System name - os.name
Operating System version - os.version
The following is an example −
 Live Demo
public class Demo {
   public static void main(String []args){
      System.out.println("OS Name: " + System.getProperty("os.name"));
      System.out.println("OS Version: " + System.getProperty("os.version"));
   }
}
OS Name: Linux
OS Version: 3.10.0-862.9.1.el7.x86_64
How to use an ArrayList in lambda expression in Java?


The lambda expression is an inline code that can implement a functional interface without creating an anonymous class. An ArrayList can be used to store a dynamically sized collection of elements.
In the below program, We have removed the elements of an ArrayList whose age is less than or equal to 20 using the removeIf() method. This method introduced in Java 8 version to remove all elements from a collection that satisfy a condition.
public boolean removeIf(Predicate filter)

The parameter filter is a Predicate. If the given predicate satisfies the condition, the element can be removed. This method returns the boolean value true if elements are removed, false otherwise.
import java.util.*;

public class LambdaWithArrayListTest {
   public static void main(String args[]) {
      ArrayList<Student> studentList = new ArrayList<Student>();
      studentList.add(new Student("Raja", 30));
      studentList.add(new Student("Adithya", 25));
      studentList.add(new Student("Jai", 20));
      studentList.removeIf(student -> (student.age <= 20)); // Lambda Expression
      System.out.println("The final list is: ");
      for(Student student : studentList) {
         System.out.println(student.name);
      }
   }
   private static class Student {
      private String name;
      private int age;
      public Student(String name, int age) {
         this.name = name;
         this.age = age;
      }
   }
}
The final list is:
Raja
Adithya
Sorting arrays by two criteria in JavaScript

Let the following be the array to be sorted by date and isImportant. All the objects with
isImportant property true rank higher than any any of the object with isImportant false and both
the groups sorted according to the date property.
Following is our array −
const array = [{
   id: 545,
   date: 591020824000,
   isImportant: false,
},
{
   id: 322,
   date: 591080224000,
   isImportant: false,
},
{
   id: 543,
   bdate: 591080424000,
   isImportant: true,
},
{
   id: 423,
   date: 591080225525,
   isImportant: false,
},
{
   id: 135,
   date: 591020225525,
   isImportant: true,
},
];
After that, we can use the array sort method like this to achieve the desired results on the above
array −
array.sort((a, b) => {
   if(a.isImportant && !b.isImportant){
      return -1;
   }else if(!a.isImportant && b.isImportant){
      return 1;
   }else{
      return b.date-a.date;
   }
});
The sort() callback function usually receives two arguments, say a and b, which are nothing but
two elements of the array on which sort() was called and the callback function runs for each
possible pair of elements of the array.
Returning -1 (any negative value) from the callback means we rank the first element higher than
second.
Returning 1 (any positive value) from the callback means we rank the second element higher
than first.
Returning 0 makes no changes. We check if any of the a or b has isImportant property set to
false, if yes then we rank that one lower. Otherwise, we rank them according to their date
property.
Let us now see the complete example −
const array = [{
   id: 545,
   date: 591020824000,
   isImportant: false,
},
{
   id: 322,
   date: 591080224000,
   isImportant: false,
},
{
   id: 543,
   bdate: 591080424000,
   isImportant: true,
},
{
   id: 423,
   date: 591080225525,
   isImportant: false,
},
{
   id: 135,
   date: 591020225525,
   isImportant: true,
},
];
array.sort((a, b) => {
   if(a.isImportant && !b.isImportant){
      return -1;
   }else if(!a.isImportant && b.isImportant){
      return 1;
   }else{
      return b.date-a.date;
   }
});
console.log(array);
The output of the code in the console will be −
[
   { id: 3, date: 591080424000, isImportant: true },{ id: 5, date: 591020225525, isImportant: true },
   { id: 4, date: 591080225525, isImportant: false },{ id: 2, date: 591080224000, isImportant: false },
   { id: 1, date: 591020824000, isImportant: false }
]
How to Add Axes to a Figure in Matplotlib with Python? - GeeksforGeeks

02 Dec, 2020

Matplotlib is a library in Python used to create figures and provide tools for customizing it. It allows plotting different types of data, geometrical figures. In this article, we will see how to add axes to a figure in matplotlib.
We can add axes to a figure in matplotlib by passing a list argument in the add_axes() method.
Syntax: matplotlib.pyplot.figure.add_axes(rect)
Parameters:
rect: This parameter is the dimensions [xmin, ymin, dx, dy] of the new axes. It takes the below elements as arguments in the list:
xmin: Horizontal coordinate of the lower left corner.
ymin: Vertical coordinate of the lower left corner.
dx: Width of the subplot.
dy: Height of the subplot.
Returns: This method return the axes class depends on the projection used. 
Example 1:
Python3
 

 
 










# Importing library 
import matplotlib 
  
# Create figure() objects 
# This acts as a container 
# for the different plots 
fig = matplotlib.pyplot.figure() 
  
# Creating axis 
# add_axes([xmin,ymin,dx,dy]) 
axes = fig.add_axes([0.5, 1, 0.5, 1]) 
  
# Depict illustration 
fig.show() 






Output:
Example 2:
Python3
 

 
 










# Importing library 
import matplotlib 
  
# Create figure() objects 
# This acts as a container  
# for the different plots 
fig=matplotlib.pyplot.figure()  
  
# Creating two axes 
# add_axes([xmin,ymin,dx,dy]) 
axes=fig.add_axes([0,0,2,2])  
axes1=fig.add_axes([0,1,2,2]) 
  
# Depict illustration 
fig.show()






Output:
Example 3:
Python3
 

 
 










# Import libraries 
import matplotlib 
import numpy 
  
# Create figure() objects 
# This acts as a container 
# for the different plots 
fig = matplotlib.pyplot.figure() 
  
# Generate line graph 
x = numpy.arange(0, 1.414*2, 0.05) 
y1 = numpy.sin(x) 
y2 = numpy.cos(x) 
  
# Creating two axes 
# add_axes([xmin,ymin,dx,dy]) 
axes1 = fig.add_axes([0, 0, 1, 1]) 
axes1.plot(x, y1) 
axes2 = fig.add_axes([0, 1, 1, 1]) 
axes2.plot(x, y2) 
  
# Show plot 
plt.show() 






Output:

Python-matplotlib


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
GATE | GATE CS 2011 | Question 43 - GeeksforGeeks

30 Sep, 2021
An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following.1 Valid bit1 Modified bitAs many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?(A) 4864 bits(B) 6144 bits(C) 6656 bits(D) 5376 bitsAnswer: (D)Explanation:
   Cache size = 8 KB
   Block size = 32 bytes
   Number of cache lines = Cache size / Block size = (8 × 1024 bytes)/32 = 256

   

   total bits required to store meta-data of 1 line = 1 + 1 + 19 = 21 bits
   total memory required = 21 × 256 = 5376 bits
YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersQuestions on cache mapping Part-2 with Ashish Verma GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0010:49 / 44:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7GRJAHkvi5g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
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-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
C program to count characters, lines and number of words in a file

A file is a physical storage location on disk and a directory is a logical path which is used to organise the files. A file exists within a directory.
The three operations that we can perform on file are as follows −
Open a file.
Process file (read, write, modify).
Save and close file.
Consider an example given below −
Open a file in write mode.
Enter statements in the file.
The input file is as follows −
Hi welcome to my world
This is C programming tutorial
From tutorials Point
The output is as follows −
Number of characters = 72Total words = 13Total lines = 3
Number of characters = 72
Total words = 13
Following is the C program to count characters, lines and number of words in a file −
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main(){
   FILE * file;
   char path[100];
   char ch;
   int characters, words, lines;
   file=fopen("counting.txt","w");
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,file);
   }
   fclose(file);
   printf("Enter source file path: ");
   scanf("%s", path);
   file = fopen(path, "r");
   if (file == NULL){
      printf("\nUnable to open file.\n");
      exit(EXIT_FAILURE);
   }
   characters = words = lines = 0;
   while ((ch = fgetc(file)) != EOF){
      characters++;
   if (ch == '\n' || ch == '\0')
      lines++;
   if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
      words++;
   }
   if (characters > 0){
      words++;
      lines++;
   }
   printf("\n");
   printf("Total characters = %d\n", characters);
   printf("Total words = %d\n", words);
   printf("Total lines = %d\n", lines);
   fclose(file);
   return 0;
}
When the above program is executed, it produces the following result −
enter the text.press cntrl Z:
Hi welcome to Tutorials Point
C programming Articles
Best tutorial In the world
Try to have look on it
All The Best
^Z
Enter source file path: counting.txt

Total characters = 116
Total words = 23
Total lines = 6
How to append an element after an element using jQuery?

To append an element after an element using jQuery, use the insertAfter() method.
You can try to run the following code to learn how to append an element after an element using jQuery:
Live Demo
<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $("#source").insertAfter(this);
            });
         });
      </script>
       
      <style>
         .div {
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" id = "source"></div>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
Emirp numbers in C++

Emirp number is a special type of number that is a prime number whose digits when reversed create another prime number (this prime number is different from the original one).
Some prime numbers that are not emirp are palindromic prime and single digit prime numbers. 
Some Emirp Numbers are 13, 17, 37, 733.
Here, we are given a number n, and we need to print all emirp numbers less than or equal to n.
Let’s take an example to understand the problem,
Input: n = 40
Output: 13, 17, 31, 37
To find all emirp numbers less than the given number, we need to find all prime numbers less than n and then check if number formed by reversing its digits is a prime number than its a emirp number, print it.
For finding the prime number till n and then rechecking its reverse digits, the best method is using sieve of Eratosthenes.
Live Demo
#include <bits/stdc++.h>
using namespace std;

int reverseDigits(int x) {

   int digitRev = 0;
   while (x > 0)
   {
      digitRev = (digitRev*10) + x%10;
      x = x/10;
   }
   return digitRev;
}

void findAllEmirpNumber(int n) {

   bool primeNo[10001];
   memset(primeNo, true, sizeof(primeNo));

   for (int p=2; p*p<=10001; p++)
   {
      if (primeNo[p] == true)
      {
         for (int i=p*2; i<=10001; i += p)
            primeNo[i] = false;
      }
   }
   for (int p=2; p<=n; p++)
   {
      if (primeNo[p])
      {
         int revNo = reverseDigits(p);
         if (p != revNo && primeNo[revNo]) {
         cout<<p<<"\t";
         if(revNo <= n)
          cout<<revNo<<"\t";
         primeNo[revNo] = false;
         }
      }
   }
}

int main()
{
   int n = 40;
   cout<<"All Emirp numbers less than or equal to "<<n<<" are\n";
   findAllEmirpNumber(n);
   return 0;
}
All Emirp numbers less than or equal to 40 are 13 31 17 37
ADT-array Representation in Data Structure

ADT indicates for Abstract Data Type.
Arrays are defined as ADT’s because they are capable of holding contiguous elements in the same order. And they permit
access for the specific element via index or position.
They are abstract because they can be String, int or Person
int[] arrA = new int[1];
String[] arrB = new String[1];
Person[] arrC = new Person[3]; // where Person is treated as a defined class
Fast, random access of items or elements.
Very memory efficient, very little memory is needed other than that needed to store the contents.
Slow insertion and deletion of elements
Array size must be known when the array is created and is fixed (static)
An Array-Based Implementation of the ADT List
Public class ListArrayBased implementsListInterface {
   private static final int MAX_LIST1 = 50;
   private Object items1[];
   // an array of list items
   privateint numItems1;
   // number of items in list
   publicListArrayBased() {
      items1 = new Object[MAX_LIST1];
      numItems1 = 0;
   } // end default constructor
}