code-rag-bench/online-tutorials huggingface dataset:
How to calculate local time in Node.js? - GeeksforGeeks

07 Oct, 2021
A JavaScript file is given and the task at hand is to calculate the local time. The local time is determined by the system in question where we execute our file. Node.js will be used as a runtime. 
There are two approaches to this problem that are discussed below:
Approach 1: The first approach is to use the built-in methods provided by JavaScript. First, create a new Date object using new Date() method and then use the same object to get the date part using toDateString() and the time part using toTimeString() methods.
Filename: index.js
Javascript
// Creating a Date objectconst dateObj = new Date();  // Printing the date and time partsconsole.log(`Date: ${dateObj.toDateString()}`);console.log(`Time: ${dateObj.toTimeString()}`);
Run the index.js file using the following command:
node index.js
Date: Wed Nov 11 2020
Time: 18:39:31 GMT+0530 (India Standard Time)
Approach 2: The next approach is based on using a third-party library named luxon. Luxon is a wrapper for JavaScript dates and times. First, we need to install luxon as a dependency in the project. To do so, run the following command from the root directory of the project.
npm install luxon

The above command will install luxon as a dependency and it will be available for use in the JavaScript file.
Filename: index.js
Javascript
const{ DateTime } = require('luxon');  // Creating a date time objectlet date = DateTime.local();  // Printing the date and time partsconsole.log(`Date: ${date.toLocaleString(DateTime.DATE_FULL)}`);console.log(`Time: ${date.toLocaleString(DateTime.TIME_24_WITH_LONG_OFFSET)}`);
Run the index.js file using the following command:
node index.js
Output:
Date: November 11, 2020
Time: 18:57:20 India Standard Time
JavaScript-Misc
Node.js-Methods
Picked
Technical Scripter 2020
JavaScript
Node.js
Technical Scripter
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
JavaScript | Sort() method - GeeksforGeeks

14 Feb, 2019
The array.sort() is an inbuilt method in JavaScript which is used to sort the array. An array can be of any type i.e. string, numbers, characters etc.Syntax:
array.sort()

Here array is the set of values which is going to be sorted.Parameters: It does not accept any parameters.Return values: It does not return anything.Examples:
Input:  var arr = ["Manish", "Rishabh", "Nitika", "Harshita"];
Output: Harshita, Manish, Nitika, Rishabh

Input: var arr = [1, 4, 3, 2];
Output: 1, 2, 3, 4

<html>  <body>    <p>Click on the Sort button to sort the array</p>      <!-- button for click event -->    <!-- onclick event is generated when the button is clicked -->    <p id="demo"></p>      <script>          <!-- array of names -->        var names = [" Manish", " Rishabh", " Nitika", " Harshita"];        document.getElementById("demo").innerHTML = names;          <!-- sortAlphabet function that sort above array alphabetically -->        function sortAlphabet() {            names.sort();            document.getElementById("demo").innerHTML = names;        }    </script>       <button onclick="sortAlphabet()"> Sort </button></body>  </html>
Output:Before clicking the “sort” button-After clicking the “sort” button-Code #2: To sort an array of integers:
<html>   <body>    <p>Click on the Sort button to sort the array</p>       <!-- button for click event -->    <!-- onclick event is generated when the button is clicked-->    <p id="demo"></p>      <script>         <!-- array numbers -->       var numbers = [7, 1, 6, 9, 2];       document.getElementById("demo").innerHTML = numbers;      <!-- sortNumber function that sort the array -->    function sortNumber() {        numbers.sort();        document.getElementById("demo").innerHTML = numbers;        }    </script>       <button onclick="sortNumber()"> Sort </button></body>   </html>
Output:Before clicking the “sort” button-After clicking the “sort” button-
javascript-array
javascript-functions
JavaScript
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to Use the JavaScript Fetch API to Get Data?
How to read a local text file using JavaScript?
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Node.js | fs.writeFileSync() Method
Difference between TypeScript and JavaScript
What can cause the "cannot find symbol" error in Java?

The “cannot find symbol” error occurs mainly when we try to reference a variable that is not declared in the program which we are compiling, it means that the compiler doesn’t know the variable we are referring to.
Using a variable that is not declared or outside the code.
Using wrong cases (“tutorials” and “Tutorials" are different) or making spelling mistakes.
The packaged class has not been referenced correctly using an import declaration.
Using improper identifier values like letters, numbers, underscore and dollar sign. The hello-class is different from helloclass.
public class CannotFindSymbolTest {
   public static void main(String[] args) {
      int n1 = 10;
      int n2 = 20;
      sum = n1 + n2;
      System.out.println(sum);
   }
}
CannotFindSymbolTest.java:5: error: cannot find symbol
sum = n1 + n2;
^
symbol: variable sum
location: class CannotFindSymbolTest
CannotFindSymbolTest.java:7: error: cannot find symbol
System.out.println(sum);
^
symbol: variable sum
location: class CannotFindSymbolTest
In the above program, "Cannot find symbol" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.
How to change the color of selected text using CSS ?

15 Apr, 2020
The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.
Below example implements the above approach:
Example:
<!DOCTYPE html><html lang="en">  <head>    <title>        How to change the color of        selected text using CSS?    </title>          <style>        .geeks h1 {            color: green;        }                  h1::selection {            background: green;            color: yellow;        }                  p::selection {            background: green;            color: yellow;        }    </style></head>  <body>    <div class="geeks">        <h1>GeeksforGeeks</h1>                  <p>            A Computer Science portal for            geeks. It contains well written,            well thought and well explained            computer science and programming            articles, quizzes and many more.        </p>    </div></body>  </html>
Output:
CSS-Misc
CSS-Selectors
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between break and continue statement in C

27 Mar, 2021
In this article, we will discuss the difference between the break and continue statements in C. They are the same type of statements which is used to alter the flow of a program still they have some difference between them.
break statement: This statement terminates the smallest enclosing loop (i.e., while, do-while, for loop, or switch statement). Below is the program to illustrate the same:
C
// C program to illustrate the// break statement#include <stdio.h>  // Driver Codeint main(){      int i = 0, j = 0;      // Iterate a loop over the    // range [0, 5]    for (int i = 0; i < 5; i++) {          printf("i = %d, j = ", i);          // Iterate a loop over the        // range [0, 5]        for (int j = 0; j < 5; j++) {              // Break Statement            if (j == 2)                break;              printf("%d ", j);        }          printf("\n");    }      return 0;}
i = 0, j = 0 1 
i = 1, j = 0 1 
i = 2, j = 0 1 
i = 3, j = 0 1 
i = 4, j = 0 1

Explanation: In the above program the inner for loop always ends when the value of the variable j becomes 2.
continue statement: This statement skips the rest of the loop statement and starts the next iteration of the loop to take place. Below is the program to illustrate the same:
C
// C program to illustrate the// continue statement#include <stdio.h>  // Driver Codeint main(){      int i = 0, j = 0;      // Iterate a loop over the    // range [0, 5]    for (int i = 0; i < 5; i++) {          printf("i = %d, j = ", i);          // Iterate a loop over the        // range [0, 5]        for (int j = 0; j < 5; j++) {              // Continue Statement            if (j == 2)                continue;              printf("%d ", j);        }          printf("\n");    }      return 0;}
i = 0, j = 0 1 3 4 
i = 1, j = 0 1 3 4 
i = 2, j = 0 1 3 4 
i = 3, j = 0 1 3 4 
i = 4, j = 0 1 3 4

Explanation: In the above program the inner for loop always skip the iteration when the value of the variable j becomes 2.
Tabular Difference Between the break and continue statement:
C Language
C Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search and update array based on key JavaScript

We have two arrays like these −
let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
{"EMAIL":"test2@stc.com","POSITION":"GMH"},
{"EMAIL":"test3@stc.com","POSITION":"RGM"},
{"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]
We are required to write a function that adds the property level to each object of arr2, picking it
up from the object from arr1 that have the same value for property "POSITION"
Let's write the code for this function −
let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSI
TION":"GMH"}]
   let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
   {"EMAIL":"test2@stc.com","POSITION":"GMH"},
   {"EMAIL":"test3@stc.com","POSITION":"RGM"},
   {"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]
const formatArray = (first, second) => {
   second.forEach((el, index) => {
      const ind = first.findIndex(item => item["POSITION"] ===
      el["POSITION"]);
      if(ind !== -1){
         second[index]["LEVEL"] = first[ind]["LEVEL"];
      };
   });
};
formatArray(arr1, arr2);
console.log(arr2);
The output in the console will be −
[
   { EMAIL: 'test1@stc.com', POSITION: 'GM', LEVEL: 5 },
   { EMAIL: 'test2@stc.com', POSITION: 'GMH', LEVEL: 5 },
   { EMAIL: 'test3@stc.com', POSITION: 'RGM', LEVEL: 4 },
   { EMAIL: 'test3@CSR.COM.AU', POSITION: 'GM', LEVEL: 5 }
]
Java Program to increase the row height in a JTable

To increase the row height, use the setRowHeight() method for a table in Java. Row height is the height of the row in pixels.
Let’s say the following is our table −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Set the rows and columns and increase the row height by first getting the current height and incrementing it. We are incrementing by 20 pixels here −
table.setRowHeight(table.getRowHeight() + 20);
The following is an example to increase the row height −
package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Difficulty Level");
      tableModel.insertRow(0, new Object[] { "CSS", "Easy" });
      tableModel.insertRow(0, new Object[] { "HTML5", "Easy"});
      tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"});
      // adding a new row
      tableModel.insertRow(tableModel.getRowCount(), new Object[] {"ExpressJS", "Intermediate" });
      // appending a new row
      tableModel.addRow(new Object[] { "WordPress", "Easy" });
      // set row height
      table.setRowHeight(table.getRowHeight() + 20);
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}
The output is as follows. Here we have set the row height to 20 −
Now, let us change the row height to 5 and spot the difference −
Twitter US Airline Sentiment Analysis | by Sohail Hosseini | Towards Data Science

The objective here is to analyze how travelers mentioned their feelings on Twitter in February 2015. It would be fascinating for airlines to use this free data to provide better service to their customers. This Dataset can be downloaded from here.
How can we analyze it?
I have uploaded the data saved in the local directory in Python:
tweets = pd.read_csv('Tweets.csv')
Let’s look at features included in dataset:
tweets.head()
What we are looking for here is the column named “airline_sentiment” and how we can predict it based on travelers’ tweets. This is called Sentiment Analysis.
To have better pictures of observations and features, we can run the following command, and it will provide us with each feature’s character.
tweets.info()
Let’s visualize the number of expressed feelings as negative, neutral, and positive.
plt.figure(figsize=(3,5))sns.countplot(tweets['airline_sentiment'], order =tweets.airline_sentiment.value_counts().index,palette= 'plasma')plt.show()
Majorities are negative, and it would be great/free feedback to airlines to provide appropriate responses. We can also show sentiments for each airline.
g = sns.FacetGrid(tweets, col=”airline”, col_wrap=3, height=5, aspect =0.7) g = g.map(sns.countplot, “airline_sentiment”,order =tweets.airline_sentiment.value_counts().index, palette=’plasma’) plt.show()
To do sentiment analysis, we need to import a few libraries. Since this is a classification problem, I use LGBMClassifier.
from lightgbm import LGBMClassifier
We need to convert these tweets (texts) to a matrix of token counts.
from sklearn.feature_extraction.text import CountVectorizer
The next step is to normalize the count matrix using tf-idf representation.
from sklearn.feature_extraction.text import TfidfTransformer
I used the pipeline function to do all steps together.
twitter_sentiment = Pipeline([('CVec', CountVectorizer(CountVectorizer(stop_words='english'))),                     ('Tfidf', TfidfTransformer()),                      ('norm', Normalizer()),                    ('tSVD', TruncatedSVD(n_components=100)),                     ('lgb', LGBMClassifier(n_jobs=-1))])
In the end, CROSS_VALIDATE is used with ROC_AUC metrics.
%%time cv_pred = cross_validate(twitter_sentiment, tweets[‘text’], tweets[‘airline_sentiment’], cv=5, scoring=(‘roc_auc_ovr’))
The results we have measured using ROC_AUS are as follows.
The complete code can be accessed through this link.
Bitwise right shift operators in C#

Bitwise operator works on bits and performs bit by bit operation. In Bitwise right shift operator the value of the left operand is moved right by the number of bits specified by the right operand.
In the below code, we have the value −
60 i.e. 0011 1100
On the right shift %minus;
c = a >> 2;
It converts into 15 after right shift twice −
15 i.e. 0000 1111
You can try to run the following code to implement Bitwise right shift operator in C# −
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class toBinary {
      static void Main(string[] args) {
         int a = 60;    /* 60 = 0011 1100 */
         int b = 0;
         c = a >> 2;    /* 15 = 0000 1111 */
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}
MongoDB query to update all documents matching specific IDs

Use the updateMany() function to update all documents that match the filter criteria. Let us create a collection with documents −
> db.demo476.insertOne({_id:1,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo476.insertOne({_id:2,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo476.insertOne({_id:3,"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo476.insertOne({_id:4,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Chris" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Bob" }
{ "_id" : 4, "Name" : "Carol" }
Following is the query to update all documents matching specific IDs −
> db.demo476.updateMany({_id:{$in:[1,3]}},{$set:{Name:"Robert"}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Robert" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "Carol" }
Display message when hovering over something with mouse cursor in Tkinter Python

Let us suppose we want to create an application where we want to add some description on tkinter widgets such that it displays tooltip text while hovering on the button widget. It can be achieved by adding a tooltip or popup.
Tooltips are useful in applications where User Interaction is required. We can define the tooltip by instantiating the constructor of Balloon(win). After that, we can bind the button with the tooltip message that applies on the widget.
#Import the tkinter library
from tkinter import *
from tkinter.tix import *

#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("400x200")

#Create a tooltip
tip= Balloon(win)

#Create a Button widget
my_button=Button(win, text= "Python", font=('Helvetica bold', 20))
my_button.pack(pady=20)

#Bind the tooltip with button
tip.bind_widget(my_button,balloonmsg="Python is an interpreted, high-level
and general-purpose programming language")

win.mainloop()
Running the above code will display a window with a button. Now, hover on the Button “Python” and it will display a tooltip text.
Display all records except one in MySQL

You can use IN() to display all records except one in MySQL. Let us first create a table −
mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable values(10,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(110,'Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,'David');
Query OK, 1 row affected (0.20 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 10   | Chris     |
| 110  | Robert    |
| 90   | David     |
+------+-----------+
4 rows in set (0.00 sec)
Here is the query to display all records except one in MySQL −
mysql> select *from DemoTable where Id IN(110,90,100);
This will produce the following output −
+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 110  | Robert    |
| 90   | David     |
+------+-----------+
3 rows in set (0.00 sec)
How to select Python Tuple/Dictionary Values for a given Index?

Items in tuple are indexed. Slice operator allows item of certain index to be accessed
>>> T1=(12, "Ravi", "B.Com FY", 78.50)
>>> print (T1[2])
B.Com FY
Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value.
>>> D1={"Rollno":12, "class":"B.com FY", "precentage":78.50}
>>> print (D1['class'])
B.com FY
>>> print (D1.get('class'))
B.com FY
How to check if a JavaScript function is defined?

To check if a JavaScript function is defined or not, checks it with “undefined”.
You can try to run the following example to check for a function is defined or not in JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <script>
         function display() {
            alert("Hello World!");
         }
         if ( typeof(display) === 'undefined')  {
            document.write('undefined');
         } else {
            document.write("Function is defined");
         }
      </script>
   </body>
</html>
Tryit Editor v3.7

Tryit: Style the first letter of a paragraph and let it float left
Calculate difference between columns of R DataFrame - GeeksforGeeks

26 Jan, 2022
Generally, the difference between two columns can be calculated from a dataframe that contains some numeric data. In this article, we will discuss how the difference between columns can be calculated in the R programming language.
Approach
Create a dataframe and the columns should be of numeric or integer data type so that we can find the difference between them.
Extract required data from columns using the $ operator into separate variables. For example, we have two columns then extract individual columns into separate variables.
Then perform the minus operation for the difference between those columns.
Finally, print the result.
Example 1 : 
R
# creating a dataframedf=data.frame(num=c(1,2,3,4),num1=c(5,4,3,2))  # Extracting column 1a=df$num # Extracting column 2b=df$num1 # printing dataframeprint(df) # printing difference among# two columnsprint(b-a)
Output :
Example 2 :
R
# creating a dataframe with some# numeric datadf=data.frame(num=c(1.9,2.9,3.4,5.6,9.8),              num1=c(6.3,7.7,8.0,9.3,10.9))print(df) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the difference between# two columnsprint(b-a)
Output :
Example 3 : 
R
# creating a dataframe with# some numeric datadf=data.frame(num=c(1,2,3,4,5),              num1=c(6,7,8,9,10)) # extracting column 1 into a# variable called aa=df$num # extracting column 2 into a# variable called bb=df$num1 # printing the dataframeprint(df) # printing the difference# between two columnsprint(b-a)
Output :
surinderdawra388
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Check if value exists in a comma separated list in MySQL?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function.
The syntax is as follows
SELECT *FROM yourTablename WHERE FIND_IN_SET(‘yourValue’,yourColumnName) > 0;
Let us first create a table. The query to create a table is as follows
mysql> create table existInCommaSeparatedList
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(200)
   - > );
Query OK, 0 rows affected (0.68 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into existInCommaSeparatedList(Name) values('John,Carol,Sam,Larry,Bob,David');
Query OK, 1 row affected (0.35 sec)
mysql> insert into existInCommaSeparatedList(Name) values('Maxwell,Chris,James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into existInCommaSeparatedList(Name) values('Robert,Ramit');
Query OK, 1 row affected (0.34 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from existInCommaSeparatedList;
The following is the output
+----+--------------------------------+
| Id | Name                           |
+----+--------------------------------+
|  1 | John,Carol,Sam,Larry,Bob,David |
|  2 | Maxwell,Chris,James            |
|  3 | Robert,Ramit                   |
+----+--------------------------------+
3 rows in set (0.00 sec)
Here is the query to check if value exists in a comma separated list. We are checking for the field with comma separated text “Robert”
mysql> SELECT *FROM existInCommaSeparatedList WHERE FIND_IN_SET('Robert',Name) > 0;
The following is the output
+----+--------------+
| Id | Name         |
+----+--------------+
|  3 | Robert,Ramit |
+----+--------------+
1 row in set (0.00 sec)
Erlang - Numbers

In Erlang there are 2 types of numeric literals which are integers and floats. Following are some examples which show how integers and floats can be used in Erlang.
Integer − An example of how the number data type can be used as an integer is shown in the following program. This program shows the addition of 2 Integers.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~w",[1+1]).
The output of the above program will be as follows −
2

Float − An example of how the number data type can be used as a float is shown in the following program. This program shows the addition of 2 Integers.
-module(helloworld).
-export([start/0]). 

start() -> 
   io:fwrite("~w",[1.1+1.2]).

The output of the above program will be as follows −
2.3

When using the fwrite method to output values to the console, there are formatting parameters available which can be used to output numbers as float or exponential numbers. Let’s look at how we can achieve this.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~f~n",[1.1+1.2]), 
   io:fwrite("~e~n",[1.1+1.2]).
The output of the above program will be as follows −
2.300000
2.30000e+0

The following key things need to be noted about the above program −
When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6.
When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6.
When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6.
When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6.
The following mathematical functions are available in Erlang for numbers. Note that all the mathematical functions for Erlang are present in the math library. So all of the below examples will use the import statement to import all the methods in the math library.
sin
This method returns the sine of the specified value.
cos
This method returns the cosine of the specified value.
tan
This method returns the tangent of the specified value.
asin
The method returns the arcsine of the specified value.
acos
The method returns the arccosine of the specified value.
atan
The method returns the arctangent of the specified value.
The method returns the exponential of the specified value.
log
The method returns the logarithmic of the specified value.
abs
The method returns the absolute value of the specified number.
float
The method converts a number to a float value.
Is_float
The method checks if a number is a float value.
Is_Integer
The method checks if a number is a Integer value.
 Print
 Add Notes
 Bookmark this page
Java | Class and Object | Question 5 - GeeksforGeeks

28 Jun, 2021
Predict the output of the following program.
   class First{      void display()    {        System.out.println("Inside First");    }}  class Second extends First{      void display()    {        System.out.println("Inside Second");    }}    class Test{      public static void main(String[] args)    {        First obj1 =  new First();        Second obj2 =  new Second();          First ref;        ref = obj1;        ref.display();          ref = obj2;        ref.display();    }}
(A) Compilation error(B)
Inside First
Inside Second
(C)
Inside First
Inside First
(D) Runtime errorAnswer: (B)Explanation: ‘ref’ is a reference variable which obtains the reference of object of class First and calls its function display().Then ‘ref’ refers to object of class Second and calls its function display().Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java | Arrays | Question 1
Java | Functions | Question 1
Java | Exception Handling | Question 6
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 4
Java | Exception Handling | Question 3
Java | Packages | Question 2
Java | Operators | Question 1
Java | Exception Handling | Question 8
Java | Exception Handling | Question 7
PHP & MySQL - Sorting Data Example

PHP uses mysqli query() or mysql_query() function to get sorted records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)

$sql
Required - SQL query to get sorted records from a table.
$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 get sorted records from a table −
Copy and paste the following example as mysql_example.php −
<html>
   <head>
      <title>Sorting MySQL Table records</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
   
         $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl order by tutorial_title asc";
         $result = $mysqli->query($sql);
           
         if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
               printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", 
                  $row["tutorial_id"], 
                  $row["tutorial_title"], 
                  $row["tutorial_author"],
                  $row["submission_date"]);               
            }
         } else {
            printf('No record found.<br />');
         }
         mysqli_free_result($result);
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show Node.js Command Prompt

var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
//Parse the address:
var q = url.parse(adr, true);
​
/*The parse method returns an object containing url properties*/
console.log(q.host);
console.log(q.pathname);
console.log(q.search);
​
/*The query property returns an object with all the querystring parameters as properties:*/
Swift - if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if, else if, else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else if...else statement in Swift is as follows −
if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
   /* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
   /* Executes when the boolean expression 3 is true */
} else {
   /* Executes when the none of the above condition is true */
}

import Cocoa

var varA:Int = 100;

/* Check the boolean condition using if statement */
if varA == 20 {
   /* If condition is true then print the following */
   println("varA is equal to than 20");
} else if varA == 50 {
   /* If condition is true then print the following */
   println("varA is equal to than 50");
} else {
   /* If condition is false then print the following */
   println("None of the values is matching");
}
println("Value of variable varA is \(varA)");
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Value of variable varA is 100


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
strpbrk() in C++

This is a string function in C++ that takes in two strings and finds the first occurrence of any character of string2 in string1. It returns the pointer to the character in string1 if there is any, otherwise returns NULL. This is not applicable for terminating NULL characters.
The syntax of strpbrk() is given as follows −
char *strpbrk(const char *str1, const char *str2)
In the above syntax, strpbrk() returns the pointer to the first character in str1 that matches any character in str2.
A program that demonstrates strpbrk() is given as follows.
 Live Demo
#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[20] = "aeroplane";
   char str2[20] = "fun";
   char *c;
   c = strpbrk(str1, str2);
   if (c != 0)
   cout<<"First matching character in str1 is "<< *c <<" at position "<< c-str1+1;
   else
   printf("Character not found");
   return 0;
}
First matching character in str1 is n at position 8
In the above program, first the two strings str1 and str2 are defined. The pointer to a character in str1 that is returned by strpbrk() is stored in c. If the value of c is not 0, then the character and its position in str1 is displayed. Otherwise, the character is not there in str1. This is demonstrated by the following code snippet.
char str1[20] = "aeroplane";
char str2[20] = "fun";
char *c;
c = strpbrk(str1, str2);
if (c != 0)
cout<<"First matching character in str1 is "<<*c <<" at position "<< c-str1+1;
else
printf("Character not found");
Count Number | Practice | GeeksforGeeks

Given an array arr consisting of integers of size n and 2 additional integers k and x, you need to find the number of subsets of this array of size k, where Absolute difference between the Maximum and Minimum number of the subset is at most x.
Note: As this number that you need to find can be rather large, print it Modulo 109+7
 
Example 1:
Input:
n = 5, k = 3, x = 5
arr[] = {1, 2, 3, 4, 5}
Output:
10
Explanation :
Possible subsets of size 3 are :-
{1,2,3} {1,2,4} {1,2,5} {1,3,4}
{1,3,5} {1,4,5} {2,3,4} {2,3,5}
{2,4,5} {3,4,5} having difference
of maximum and minimum
element less than equal to 5.
 
Example 2:
Input:
n = 8, k = 4, x = 6
arr[] = {2, 4, 6, 8, 10, 12, 14, 16}
Output:
5
Explanation :
Possible subsets of size 4 are:-
{2,4,6,8} {4,6,8,10} {6,8,10,12}
{8,10,12,14} {10,12,14,16} having
difference of maximum and minimum 
element less than equal to 6.


Your Task:
You don't have to print anything, printing is done by the driver code itself. Your task is to complete the function getAnswer() which takes the array arr[], its size n and two integers k and x as inputs and returns the required result, Modulo 109+7.
 
Expected Time Complexity: O(n. log(n))
Expected Auxiliary Space: O(n)
 
Constraints:
1 ≤ n ≤ 5×105
1 ≤ k ≤ n
1 ≤ arr[i], x ≤ 109
0
Navenkumar Duraisamy
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to create a numpy array within a given range?

We have to create a numpy array in the range provided by the user. We will use the arange() function in the numpy library to get our output.
Step1: Import numpy.
Step 2: Take start_value, end_value and Step from the user.
Step 3: Print the array using arange() function in numpy.
import numpy as np

start_val = int(input("Enter starting value: "))
end_val = int(input("Enter ending value: "))
Step_val = int(input("Enter Step value: "))
print(np.arange(start_val, end_val, Step_val))
Enter starting value: 5
Enter ending value: 50
Enter Step value: 5
[ 5 10 15 20 25 30 35 40 45]
Convert INT to DATETIME in MySQL?

You can use the in-built function from_unixtime() to convert INT to DATETIME. The syntax is as follows −
SELECT FROM_UNIXTIME(yourColumnName,’%Y-%m-%d') as AnyVariableName from
yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table IntToDateDemo
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query to insert record is as follows −
mysql> truncate table IntToDateDemo;
Query OK, 0 rows affected (4.11 sec)

mysql> insert into IntToDateDemo values(1545284721);
Query OK, 1 row affected (0.19 sec)

mysql> insert into IntToDateDemo values(1576820738);
Query OK, 1 row affected (0.19 sec)

mysql> insert into IntToDateDemo values(1513748752);
Query OK, 1 row affected (0.24 sec)

mysql> insert into IntToDateDemo values(1671515204);
Query OK, 1 row affected (0.18 sec)
Now you can display all records from the table using select statement. The query is as follows −
mysql> select *from IntToDateDemo;
+------------+
| Number     |
+------------+
| 1545284721 |
| 1576820738 |
| 1513748752 |
| 1671515204 |
+------------+
4 rows in set (0.00 sec)
Here is the query that converts int to datetime using from_unixtime() function. The query is as follows −
mysql> select from_unixtime(Number,'%Y-%m-%d') as DateDemo from IntToDateDemo;
The following is the output displaying the converted datetime −
+------------+
| DateDemo   |
+------------+
| 2018-12-20 |
| 2019-12-20 |
| 2017-12-20 |
| 2022-12-20 |
+------------+
4 rows in set (0.00 sec)
LESS - Parent Selectors

In this chapter, let us understand how Parent Selectors work. It is possible to reference the parent selector by using the &(ampersand) operator. Parent selectors of a nested rule is represented by the & operator and is used when applying a modifying class or pseudo class to an existing selector.
The following table shows the types of parent selector −
The & will represent the nearest selector and also all the parent selectors.
Prepending a selector to the inherited (parent) selectors is useful when selector ordering is changed.
The & can also produce all the possible permutation of selectors in a list separated by commas.
The following example demonstrates the use of parent selector in the LESS file −
<!doctype html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
      <title>Parent Selector</title>
   </head>

   <body>
      <h2>Welcome to TutorialsPoint</h2>
      <ul>
         <li><a>SASS</a></li>
         <li><a>LESS</a></li>
      </ul>
   </body>
</html>
Next, create the style.less file.
a {
   color: #5882FA;
   &:hover {
      background-color: #A9F5F2;
   }
}
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −
a {
   color: #5882FA;
}

a:hover {
   background-color: red;
}
In the above example, & refers to selector a.
Follow these steps to see how the above code works −
Save the above html code in the parent_selector1.htm file.
Save the above html code in the parent_selector1.htm file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
The Parent selectors operator has many uses like, when you need to combine the nested rule's selectors in other way than the default. Another typical use of & is to generate class names repeatedly. For more information click here.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Visualizing a Sparse Matrix. How do you know if you have a sparse... | by Kamil Mysiak | Towards Data Science

Many areas in machine learning commonly employ the use of a sparse matrix. If you have ever vectorized a NLP dictionary using One-Hot-Encoding, CountVectorizing or TfidVectorizing you know what I’m pertaining to.
In simplest terms, a sparse matrix is one containing many zeros and a dense matrix which does not.
import scipy.sparse as sparseimport matplotlib.pyplot as plt%matplotlib inline# adjust the density parametersparse = sparse.random(10,10, density=0.015)sparse.toarray()
plt.figure(figsize=(15, 15))plt.spy(sparse, markersize=1)
I’m currently working with an NLP dictionary of over 15,000 words and I always wanted to see what a sparse matrix of that size would look life. Enjoy!
How to find the sum of every n values in R data frame columns?

To find the sum of every n values in R data frame columns, we can use rowsum function along with rep function that will repeat the sum for rows. For example, if we have a data frame called df that contains 4 columns each containing twenty values then we can find the column sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4)).
Consider the below data frame −
 Live Demo
x1<-rpois(20,5)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1
   x1 x2
1  7  3
2  9  4
3  7  3
4  3  3
5  9  1
6  4  1
7  7  3
8  4  3
9  6  3
10 5  0
11 4  4
12 5  4
13 5  1
14 6  2
15 1  3
16 1  2
17 6  1
18 6  2
19 1  2
20 8  2
Finding the column sums for every 5 rows in df1 −
rowsum(df1,rep(1:5,each=4))
  x1 x2
1 26  13
2 24   8
3 20  11
4 13   8
5 21   7
 Live Demo
y1<-rnorm(20)
y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2
      y1           y2           y3
1  -0.46478980   0.61742170  -0.21406143
2   1.42820694  -1.68668632  -1.69183062
3  -1.09014651  -0.80538397  -1.73060665
4   0.04143155  -0.86250648  -0.50698176
5   1.31066192   1.98317492   0.81144732
6   1.05362995   1.31032857  -0.48538293
7   1.13221772   3.27862204  -1.42116882
8  -2.30864576  -0.02998736  -0.35898649
9  -1.30371212   0.26152070  -0.25968593
10 -0.93208053   0.59726153   0.31393063
11  0.23612475   1.72240765  -2.21882009
12  0.58740869   0.53739269   0.52578465
13  0.42427296  -0.84617072  -0.35684917
14 -0.33885432   0.09297437  -0.61340922
15 -0.40246042  -0.94370468   0.01108134
16 -0.97853686   1.08559425   0.71596796
17  0.28577367  -0.57999260  -0.14349388
18 -0.78154458  -2.40582173   2.50692776
19  0.05791671   0.94479521   0.79723502
20 -0.03289249  -1.46621425  -0.89169830
Finding the column sums for every 5 rows in df2 −
rowsum(df2,rep(1:5,each=4))
        y1          y2          y3
1  -0.08529781  -2.7371551  -4.1434804
2   1.18786383   6.5421382  -1.4540909
3  -1.41225921   3.1185826  -1.6387907
4  -1.29557865  -0.6113068  -0.2432091
5  -0.47074670  -3.5072334   2.2689706
How to draw a png image on a Python tkinter canvas?

To work with images in tkinter, Python provides PIL or Pillow toolkit. It has many built-in functions that can be used to operate an image of different formats.
To open an image in a canvas widget, we have use create_image(x, y, image, **options) constructor. When we pass the Image value to the constructor, it will display the image in the canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x600")

# Create a canvas widget
canvas=Canvas(win, width=700, height=600)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="Monalisa.png")

# Add the image in the canvas
canvas.create_image(350, 400, image=img, anchor="center")

win.mainloop()
Running the above code will display a window that contains image in the canvas.