code-rag-bench/online-tutorials huggingface dataset:
How to call a JavaScript function from an onClick event?

The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse. You can put your validation, warning etc., against this event type.
You can try to run the following code to call a JavaScript function from an onClick event
Live Demo
<html>
   <head>
      <script>
         <!--
            function display() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type="button" onclick="display()" value="Click me" />
      </form>
   </body>
</html>
Count unset bits of a number in C++

We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total unset bits of a number.
Unset bits in a binary number is represented by 0. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0’s and 1’s. So, the digit 0 is known as unset bit in the terms of the computer.
Input − int number = 50
Output − Count of total unset bits in a number are − 3
Explanation − Binary representation of a number 50 is 110010 and if we calculate it in 8-digit number then two 0’s will be appended in the beginning. So, the total unset bits in a number are 3.
Input − int number = 10
Output − Count of total unset bits in a number are: 6
Explanation − Binary representation of a number 10 is 00001010 and if we calculate it in 8-digit number then four 0’s will be appended in the beginning. So, the total unset bits in a number are 6.
Input the number in a variable of integer type
Input the number in a variable of integer type
Declare a variable count to store the total count of set bits of type unsigned int
Declare a variable count to store the total count of set bits of type unsigned int
Start loop FOR from i to 1<<7 and i > 0 and i to i / 2
Start loop FOR from i to 1<<7 and i > 0 and i to i / 2
Inside the loop, check num & 1 == TRUE then print 1 else print 0
Inside the loop, check num & 1 == TRUE then print 1 else print 0
Inside the loop, increment the value of total digits in a number.
Inside the loop, increment the value of total digits in a number.
Start loop while to calculate the total count of bits till number isn’t 0
Start loop while to calculate the total count of bits till number isn’t 0
Inside the loop, set count = count + number & 1 and also set number >>=1
Inside the loop, set count = count + number & 1 and also set number >>=1
Set count as total digits in a number - total set bits in a number.
Set count as total digits in a number - total set bits in a number.
Print the count
Print the count
 Live Demo
#include<iostream>
using namespace std;
//Count total unset bits in a number
unsigned int unset_bits(unsigned int number){
   unsigned int total_digits = 0;
   unsigned int count = 0;
   unsigned i;
   //display the total 8-bit number
   cout<<"8-bit digits of "<<number<<" is: ";
   for (i = 1 << 7; i > 0; i = i / 2){
      (number & i)? cout<<"1": cout<<"0";
      total_digits++;
   }
   //calculate the total unset bits in a number
   while (number){
      count += number & 1;
      number >>= 1;
   }
   count = total_digits - count;
   cout<<"\nCount of total unset bits in a number are: "<<count;
}
int main(){
   int number = 50;
   unset_bits(number);
   return 0;
}
If we run the above code it will generate the following output −
8-bit digits of 50 is: 00110010
Count of total set bits in a number are: 5
What is if/then directives for debug vs release in C#?

In Visual Studio Debug mode and Release mode are different configurations for
building your .Net project.
Select the Debug mode for debugging step by step their .Net project and select the
Release mode for the final build of Assembly file (.dll or .exe).
To change the build configuration −
From the Build menu, select Configuration Manager, then select Debug or Release.
Or On the toolbar, choose either Debug or Release from the Solution Configurations
list.
The code which is written inside the #if debug will be executed only if the code is
running inside the debug mode.
If the code is running in the release mode, then the #if Debug will be false and it will not execute the code present inside this.
class Program{
   static void Main(string[] args){
      #if DEBUG
         Console.WriteLine("Mode=Debug");
      #else
         Console.WriteLine("Mode=Release");
      #endif
         Console.ReadLine();
   }
}
if in Debug Mode
Mode=Debug
if in Release Mode
Mode=Release
How to get form data using JavaScript/jQuery? - GeeksforGeeks

03 Aug, 2021
The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data.
Syntax:
$(selector).serializeArray()
Parameter: It does not accept any parameter.
Return Value: It returns all the value that is inside the inputs fields.
Example:
<!DOCTYPE html><html>   <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">    </script>          <script>        $(document).ready(function() {            $("button").click(function() {                var x = $("form").serializeArray();                $.each(x, function(i, field) {                    $("#output").append(field.name + ":"                            + field.value + " ");                });            });        });    </script>          <style>        #GFG {            width: 300px;            padding: 50px;            height: 150px;            border: 2px solid green;        }    </style></head>   <body>    <div id="GFG">        <form action="#">            Name: <input type="text"                 style="margin: 10px;" name="Name">            <br>        </form>           <button>Submit</button>    </div>       <div id="output"></div></body>   </html>
Output:
Before clicking the button:
After clicking the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to get specific columns in SQLAlchemy with filter? - GeeksforGeeks

04 Jan, 2022
In this article, we will see how to query and select specific columns using SQLAlchemy in Python.
For our examples, we have already created a Students table which we will be using:
Students Table
To select specific column in SQLAlchemy
Syntax: sqlalchemy.select(*entities)
entities: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and ORM-mapped classes for ORM usage.
To filter records in SQLAlchemy
Syntax: sqlalchemy.query.filter(*criterion)
criterion: Criterion is one or more criteria for selecting the records.
Python
import sqlalchemy as dbfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base  Base = declarative_base()  # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine("mysql+pymysql://\root:password@localhost/Geeks4Geeks")  # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base):      __tablename__ = 'students'      first_name = db.Column(db.String(50),                            primary_key=True)    last_name  = db.Column(db.String(50),                            primary_key=True)    course     = db.Column(db.String(50))    score      = db.Column(db.Float)  # CREATE THE SESSION OBJECTSession = sessionmaker(bind=engine)session = Session()  # SELECTING COLUMN `first_name`, `last_name` WHERE `score > 80`result = session.query(Students) \    .with_entities(Students.first_name, Students.last_name) \        .filter(Students.score > 80).all()  for r in result:    print(r.first_name, r.last_name)
Output:
Output – Example 1
Python3
import sqlalchemy as dbfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base  Base = declarative_base()  # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine("mysql+pymysql://\root:password@localhost/Geeks4Geeks")  # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base):      __tablename__ = 'students'      first_name = db.Column(db.String(50),                           primary_key=True)    last_name  = db.Column(db.String(50),                            primary_key=True)    course     = db.Column(db.String(50))    score      = db.Column(db.Float)  # CREATE THE SESSION OBJECTSession = sessionmaker(bind=engine)session = Session()  # SELECTING COLUMN `first_name`, `score`# WHERE `score > 80` AND `course` is STATISTICSresult = session.query(Students) \    .with_entities(Students.first_name, Students.score) \        .filter(Students.score > 80,                Students.course.like('Statistics')).all()  for r in result:    print(r.first_name, r.score)
Output:
Output – Example 2
Picked
Python-SQLAlchemy
Python
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 ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
crypto.randomBytes() Method in Node.js

The crypto.randomBytes() generates cyprtographically strong pseudo-random data. This method will not be completed until there is sufficient entropy in the bytes created. But even after this it does not takes more than a few milliseconds. This method basically creates a few random bytes which are further used.
crypto.randomBytes(size, [callback])
The above parameters are described as below −
size – This argument defines the number of bytes to be generated. Size must not be greater than 2**31 – 1.
size – This argument defines the number of bytes to be generated. Size must not be greater than 2**31 – 1.
callback – The callback is called if any error occurs in the method.
callback – The callback is called if any error occurs in the method.
Create a file with name – randomBytes.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node randomBytes.js
randomBytes.js
 Live Demo
// crypto.randomBytes() Asynchronous demo example

// Importing the crypto module
const crypto = require('crypto');

crypto.randomBytes(64, (err, buf) => {
   if (err) throw err;
   console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
C:\home\node>> node randomBytes.js
64 bytes of random data:
eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be
9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5
Let's take a look at one more example.
 Live Demo
// crypto.randomBytes() Synchronous demo example

// Importing the crypto module
const crypto = require('crypto');

const buffer = crypto.randomBytes(256);
console.log(
   `${buffer.length} bytes of random data: ${buffer.toString('base64')}`);
C:\home\node>> node randomBytes.js
256 bytes of random data:
n7yfRMo/ujHfBWSF2VFdevG4WRbBoG9Fqwu51+/9ZBUV6Qo88YG7IbcEaIer+g+OgjMv4RyNQ6/67a
F5xWmkOR3oA6J6bdAJ1pbstTuhIfItF1PQfP26YXk1QlaoKy/YJxPUngyK4kNG9O04aret4D+2qIq9
BUaQcv+R9Xi014VKNUDZ+YQKEaLHBhJMq6JgehJ56iNbdNJ4+PN7SQwjNdZ8gS76izAwYsSZ7Kuyx2
VzdXIKsLmjleuJ2DZ7/6Yyn8WM9463dhuh0KQ5nwFbgzucvjmdvDjBlGFZBGlKs6AXqYh+0Oe6Ckkv
3OpnXOJs+GExbmnvjaeDQ03khpdJfA==
What is a JavaScript call() Method?

JavaScript call() method is used to call a function with another object as the first argument.
You can try to run the following code to learn how to implement call() method in JavaScript −
<html>
   <head>
      <script>
         var person = {
            Name:"John",
            Department: "Finance",
            fullName: function() {
               return this.Name + " is from " + this.Department + " Department";
            }
         }

         var myObject = {
            Name: "Amit",
            Department: "Marketing",
         }
         x = person.fullName.call(myObject);
         document.write(x);
      </script>
   </head>

   <body>
   </body>
</html>
Addition of tuples in Python

When it is required to add the tuples, the 'amp' and lambda functions can be used.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Anonymous function is a function which is defined without a name.
In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword.  It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it. Below is a demonstration of the same −
Live Demo
my_tuple_1 = (11, 14, 54, 56, 87)
my_tuple_2 = (98, 0, 10, 13, 76)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

my_result = tuple(map(lambda i, j: i + j, my_tuple_1, my_tuple_2))

print("The tuple after addition is: ")
print(my_result)
The first tuple is :
(11, 14, 54, 56, 87)
The second tuple is :
(98, 0, 10, 13, 76)
The tuple after addition is:
(109, 14, 64, 69, 163)
Two tuples are defined, and are displayed on the console.
The lambda function is applied on every element of both the tuples, and the 'map' method is used to map the process of addition.
It is then converted to a tuple.
This is assigned to a value.
It is displayed on the console.
Array - GeeksforGeeks

06 May, 2017
A program P reads in 500 integers in the range [0..100] representing the scores of 500 students. It then prints the frequency of each score above 50. What would be the best way for P to store the frequencies? (GATE CS 2005) 
An array of 50 numbers 
An array of 100 numbers 
An array of 500 numbers 
A dynamically allocated array of 550 numbers 
See question 1 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-22/ 
The First occurence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is i.The Last occurrence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is j.Now number of occuerence of that element(count) is (j-i+1). Overall time complexity = log n +log n +1 = O(logn)
The First occurence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is i.
The Last occurrence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is j.
Now number of occuerence of that element(count) is (j-i+1). Overall time complexity = log n +log n +1 = O(logn)
For unsorted array, we can always insert an element at end and do insert in O(1) timeFor Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations for details.For sorted array, insert takes O(n) time as we may have to move all elements worst case.For sorted doubly linked list, insert takes O(n) time to find position of element to be inserted.
For unsorted array, we can always insert an element at end and do insert in O(1) time
For Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations for details.
For sorted array, insert takes O(n) time as we may have to move all elements worst case.
For sorted doubly linked list, insert takes O(n) time to find position of element to be inserted.
Option A is correct. Int is the data type used,geeks is the name of the array and [20] is the size of the array.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Difference between sh and bash
What is "network ID" and "host ID" in IP Addresses?
Primer CSS Flexbox Flex Direction
Converting an image to a Torch Tensor in Python
Prime CSS Marketing Buttons Animated Arrow Symbol
How to Calculate Cosine Similarity in Python?
Python Program for Breadth First Search or BFS for a Graph
10 Best C and C++ Books For Beginners & Advanced Programmers
Show all columns of Pandas DataFrame in Jupyter Notebook
How to split a Dataset into Train and Test Sets using Python
How to change Button Border in Java Swing

For Button border, use createLineBorder() method in Java, which allows you to set the color of the Border as well:
JButton button = new JButton("Demo Button!");
Border border = BorderFactory.createLineBorder(Color.BLUE);
The following is an example to change button border in Java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Button Border");
      Container container = frame.getContentPane();
      JButton button = new JButton("Demo Button!");
      Border border = BorderFactory.createLineBorder(Color.BLUE);
      button.setBorder(border);
      container.add(button, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
How to check the version of ReactJS ? - GeeksforGeeks

30 Sep, 2021
React is a Javascript front-end library that is used to build single-page applications (SPA). If we want to know which react version we are using to build a project then there are some easy ways to find it.
In this article, we are going to discuss three ways to find out the React version.
Using package.json fileUsing command lineUsing version property of default import from React
Using package.json file
Using command line
Using version property of default import from React
Using package.json file
The package.json contains metadata about our project. It is created by default when we create our React project. We can create a react app using the command mentioned below. 
npx create-react-app name_of_the_app
The package.json file contains a lot of information in the name/value pairs in JSON format. We can easily check our React version under the list of dependencies as shown in the image given below.
Using command line
We can easily check the React version by using the command mentioned below on our command line.
npm view react version
The output demonstrating the use of the above command on the command line is mentioned below.
Using version property of default import from React
The default import from React library is an object that has version property on it. We can use this property inside our JSX elements in our desired manner. 
Syntax: The syntax to use the version property is mentioned below.
import React from 'react';
let a = React.version
To follow along with the article create a react project using the command that was discussed above in the article. 
Filename: App.js The content of the App.js file is mentioned in the code given below in which we have demonstrated the use of version property on React object.
Javascript
import React from 'react';  const App = () => {  return <h1>    We are currently using react version {React.version}  </h1>;}  export default App;
Step to run the application: Use the following command on the command line to start the application.
npm start
Output: Open the browser and go to http://localhost:3000, you will see the following output.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
React-Router Hooks
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
ReactJS useNavigate() Hook
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
How to link jQuery from my local machine?

You can add jQuery using CDN or through downloading it on local machine. For Local Installation, download jQuery library on your local machine and include it in your HTML code. The following are the steps:
Go to the jQuery website to download the latest version available.
Now put downloaded jquery-3.2.1.min.js file in a directory of your website, e.g. /jquery.
You can try to run the following code to learn how to link jQuery from local machine:
Live Demo
<html>
   <head>
      <title>jQuery Example</title>
      <script src = "/jquery/jquery-3.2.1.min.js"></script>
      <script>
         $(document).ready(function(){
            document.write("Hello, World!");
         });
      </script>        
   </head>
   
   <body>
      <h1>Hello</h1>
   </body>
   
</html>
Prototype - update() Method

This method replaces the content of the element with the provided newContent argument and returns the element.
Given newContent can be a plain text, an HTML snippet, or any JavaScript object, which has a toString() method. If it contains any <script> tags, these will be evaluated after element has been updated.
If no argument is provided, Element.update will simply clear element of its content.
element.update( newContent );

Updated HTML element.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            $('movies').update("Spider Man, USV-315");
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result</p>
      
      <div id = "movies">
         Speed, Titanic, Brave Heart
      </div>
      
      <input type = "button" value = "Click" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
D3.js brushSelection() Function - GeeksforGeeks

31 Jul, 2020
The d3.brushSelection() function in D3.js is used to get the brush selection for a given node.
Syntax:
d3.brushSelection(this);
Parameters: 
this: used to get the bounds for the current brush.
Return Value: This function returns the array containing the bounds of the brush element.
Example: In this example, we will create a brush and will get its selection bound sides using this method.
<!DOCTYPE html><html>    <head>        <title>            D3.js | d3.brushSelection() Function        </title>          <script src="https://d3js.org/d3.v4.min.js">       </script>    </head>      <body>        <h1 style="color: green;                   text-align: center;">            Geeksforgeeks        </h1>          <p style="text-align: center;">            D3.js | d3.brushSelection() Function <br />            Dimensions are:<br />        </p>          <p style="text-align: center;"            id="p"></p>          <svg width="600"              height="600"              id="brush"></svg>        <script>            // Selecting SVG element            d3.select("#brush")                // Creating a brush                .call(                    d3                        .brush()                 // Calling a function on brush change                        .on("brush", brushed)           /* Initialise the brush area: start at 0, 0          and finishes at given width, height*/                        .extent([                            [0, 0],                            [600, 600],                        ])                );            function brushed() {// Using d3.brushSelection to get bounds of the brush                const sel = d3.brushSelection(this);                console.log(sel);                var p = document.getElementById("p");                p.innerHTML = "side1 : "                   + sel[0][1] + `<br>`                   + "side2 : " + sel[1][1]                   + `<br>` + "side3 : "                   + sel[0][0] + `<br>`                  + "side4 : " + sel[1][0] + `<br>`;            }        </script>    </body></html>
Output:
D3.js
JavaScript
Web Technologies
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
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?
Python | Maximum and Minimum value from two lists

28 Feb, 2019
The problem of finding a maximum and minimum values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using max() + min() + “+” operatorThe maximum and minimum values can be determined by the conventional max and min function of python and the extension of one to two lists can be dealt using the “+” operator.
# Python3 code to demonstrate# maximum and minimum values in two lists # using max() + min() + "+" operator  # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1]  # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using max() + min() + "+" operator# maximum and minimum values in two lists max_all = max(test_list1 + test_list2)min_all = min(test_list1 + test_list2)  # printing resultprint ("The maximum of both lists is : " + str(max_all))print ("The minimum of both lists is : " + str(min_all))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The maximum of both lists is : 10
The minimum of both lists is : 1

 Method #2 : Using max() + min() + chain()Another method to perform this particular task is by using the chain function which performs the task similar to the “+” operator but using an iterator, hence faster.
# Python3 code to demonstrate# maximum and minimum values in two lists # using max() + min() + "+" operatorfrom itertools import chain  # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1]  # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using max() + min() + "+" operator# maximum and minimum values in two lists max_all = max(chain(test_list1, test_list2))min_all = min(chain(test_list1, test_list2))  # printing resultprint ("The maximum of both lists is : " + str(max_all))print ("The minimum of both lists is : " + str(min_all))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The maximum of both lists is : 10
The minimum of both lists is : 1

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Using Data-Attributes (data-*) in CSS

We can store extra information about elements using data-* attribute. The following examples illustrate CSS data-* attribute.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
dl {
   margin: 2%;
}
p {
   width: 60%;
   background-color: lightgreen;
   padding: 2%;
   color: white;
   text-align: center;
}
dt {
   font-weight: bold;
}
dt:hover {
   cursor: pointer;
}
dd {
   font-style: italic;
}
</style>
</head>
<body>
<dl>
<dt onmouseover="showDescription(this)" data-food-type="beverages">Tea</dt>
<dd>Hot Spicy Tea or Ice Lemon Tea </dd>
<dt onmouseover="showDescription(this)" data-food-type="snacks">Toast</dt>
<dd>Hot Garlic Butter Toast</dd>
</dl>
<p>(hover over food item)</p>
</body>
<script>
function showDescription(food) {
   let foodType = food.getAttribute("data-food-type");
   document.querySelector('p').textContent = ("We have " + food.innerHTML + " in " + foodType + ".");
}
</script>
</html>
This will produce the following result −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
section {
   margin: 8%;
   box-shadow: inset 0 0 20px red;
   width: 300px;
   padding: 2%;
}
section[data-number='77'] {
   height: 120px;
   border-radius: 15px;
}
section::before {
   content: attr(data-user);
   font-size: 1.2em;
}
section::after {
   content: attr(data-number);
}
</style>
</head>
<body>
<section data-number="77" data-user="Client">
<p>Demo Text</p>
</section>
</body>
</html>
This will produce the following result −
Z score for Outlier Detection – Python

27 Aug, 2020
Z score is an important concept in statistics. Z score is also called standard score. This score helps to understand if a data value is greater or smaller than mean and how far away it is from the mean. More specifically, Z score tells how many standard deviations away a data point is from the mean.
Z score = (x -mean) / std. deviation
A normal distribution is shown below and it is estimated that68% of the data points lie between +/- 1 standard deviation.95% of the data points lie between +/- 2 standard deviation99.7% of the data points lie between +/- 3 standard deviation
Z score and Outliers:If the z score of a data point is more than 3, it indicates that the data point is quite different from the other data points. Such a data point can be an outlier.For example, in a survey, it was asked how many children a person had.Suppose the data obtained from people is
1, 2, 2, 2, 3, 1, 1, 15, 2, 2, 2, 3, 1, 1, 2
Clearly, 15 is an outlier in this dataset.
Let us use calculate the Z score using Python to find this outlier.Step 1: Import necessary libraries
import numpy as np 
Step 2: Calculate mean, standard deviation
data = [1, 2, 2, 2, 3, 1, 1, 15, 2, 2, 2, 3, 1, 1, 2]mean = np.mean(data)std = np.std(data)print('mean of the dataset is', mean)print('std. deviation is', std)
Output:
mean of the dataset is 2.6666666666666665
std. deviation is 3.3598941782277745
Step 3: Calculate Z score. If Z score>3, print it as an outlier.
threshold = 3outlier = []for i in data:    z = (i-mean)/std    if z > threshold:        outlier.append(i)print('outlier in dataset is', outlier)
Output:
outlier in dataset is [15]
Conclusion: Z score helps us identify outliers in the data.
nidhi_biet
statistical-algorithms
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Precision Handling in Python

05 Jul, 2022
Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the “math” module. In this article, we will use high-precision calculations in Python with Decimal in Python.
In this example, we will cover some math methods. such as trunc() method, ceil() method, and floor() method.
trunc(): This function is used to eliminate all decimal parts of the floating-point number and return the integer without the decimal part.
ceil(): This function is used to print the least integer greater than the given number.
floor(): This function is used to print the greatest integer smaller than the given integer.
Python3
# importing "math" for precision functionimport math # initializing valuea = 3.4536 # using trunc() to print integer after truncatingprint("The integral value of number is : ", end="")print(math.trunc(a)) # using ceil() to print number after ceilingprint("The smallest integer greater than number is : ", end="")print(math.ceil(a)) # using floor() to print number after flooringprint("The greatest integer smaller than number is : ", end="")print(math.floor(a))
Output: 
The integral value of number is : 3
The smallest integer greater than number is : 4
The greatest integer smaller than number is : 3
In this example, we will see How to Limit Floats to Two Decimal Points in Python. In python float precision to 2 floats in python, and python float precision to 3. There are many ways to set the precision of the floating-point values. Some of them are discussed below.
Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming. Using format():- This is yet another way to format the string for setting precision. Using round(x,n):- This function takes 2 arguments, number, and the number till which we want decimal part rounded. 
Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.
 Using format():- This is yet another way to format the string for setting precision.
 Using round(x,n):- This function takes 2 arguments, number, and the number till which we want decimal part rounded. 
Python3
# Python code to demonstrate precision# and round() # initializing valuea = 3.4536 # using "%" to print value till 2 decimal placesprint("The value of number till 2 decimal place(using %) is : ", end="")print('%.2f' % a) # using format() to print value till 3 decimal placesprint("The value of number till 2 decimal place(using format()) is : ", end="")print("{0:.3f}".format(a)) # using round() to print value till 2 decimal placesprint("The value of number till 2 decimal place(using round()) is : ", end="")print(round(a, 2))
Output : 
The value of number till 2 decimal place(using %) is : 3.45
The value of number till 2 decimal place(using format()) is : 3.453
The value of number till 2 decimal place(using round()) is : 3.45
rishabk2000
surajkumarguptaintern
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to run Python functions from command line?

To run this function from the command line we can use the -c (command) argument as follows:
$ python -c 'import foobar; print foobar.sayHello()'
Alternatively, we can also write:
$ python -c 'from foobar import *; print sayHello()'
Or like this
$ python -c 'from foobar import sayHello; print sayHello()'
OUTPUT
Hello
How to Convert From BLOB to Text in MySQL?

28 Nov, 2021
In this article, we will see the conversion of a BLOB to TEXT in MySQL.
BLOB: It stands for Binary Large Object. It is a kind of data type in MySQL that can store files or images in the database in binary format.  It has four types i.e TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. All four types are similar, the only difference among them is the amount of data they can hold. 
AS the name suggests, LONGBLOB can hold the maximum amount of data and TINYBLOB can hold the least amount of data among the four types.
TEXT datatype in MySQL is used for storing long text strings in the database. It is just like VARCHAR. In order to convert BLOB to TEXT, we will use the CONVERT statement.
Syntax:
CONVERT( column_name using utf8);
utf8 is the way of encoding Unicode characters. It is recommended to use ut8 while creating web pages and databases. For demonstration, follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have demo_table in our geek’s database.
Query:
 CREATE TABLE demo_table(
   NAME VARCHAR(20),
   AGE INT,
  CITY VARCHAR(20),
   FILE BLOB);
Step 4: Insert data into a table
Query:
 INSERT INTO demo_table VALUES ('Romy', 21, 
 'Delhi', 'My name is romy kumari,
 I am 21 yrs old'),
('Pushkar', 22, 'Delhi', 
'My name is Pushkar jha,
 I am 22 yrs old'),
 ('Rinkle', 22, 'Punjab',
  'My name is Rinkle Arora,
  I am 22 yrs old'),
('Ayushi', 22, 'Patna', 'My name is
 Ayushi choudhary, I am 22 yrs old');
Step 5: View the content
Execute the below query to see the content of the table
Query:
SELECT * FROM demo_table;
Output:
We can see that content of the FILE column is in encoded format.
Step 6: Conversion from BLOB to TEXT.
Query:
SELECT convert(File using utf8)
from demo_table;
If you want to update the BLOB datatype column to the TEXT datatype column. Follow these steps:
Alter the table and add a column having data type TEXT.
Add content to that column after converting BLOB data to TEXT date.
Drop BLOB column.
Step 1: Add column
Syntax:
ALTER Table demo_table ADD 
COLUMN AFTER_CONERSION TEXT;
Step 2: Add content to column
 UPDATE demo_table SET AFTER_CONERSION 
 = CONVERT (FILE using utf8);
Step 3: Drop BLOB column
 ALTER TABLE demo_table 
 DROP COLUMN FILE;
mysql
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL | DROP, TRUNCATE
Number guessing game in C

01 Jul, 2022
Given an integer N. A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end after 10 attempts and if the player failed to guess the number, and then he loses the game.
Examples:
N = 100Number chosen: 20 
Machine: Guess a number between 1 and NPlayer: 30Machine: Lower number please!Player: 15Machine: Higher number please!Player: 20Machine: You guessed the number in 3 attemptsNow, terminate the game.
Approach: The following steps can be followed to design the game:
Generate a random number between 0 and N.
Then iterate from 1 to 10 and check if the input number is equal to the assumed number or not.
If yes, then the player wins the game.
Otherwise, terminate the game after 10 attempts.
Below is the implementation of the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h>#include <stdlib.h>#include <time.h> // Function that generate a number in// the range [1, N] and checks if the// generated number is the same as the// guessed number or notvoid guess(int N){    int number, guess, numberofguess = 0;     //Seed random number generator    srand(time(NULL));     // Generate a random number    number = rand() % N;     printf("Guess a number between"           " 1 and %d\n",           N);     // Using a do-while loop that will    // work until user guesses    // the correct number    do {         if (numberofguess > 9) {            printf("\nYou Loose!\n");            break;        }         // Input by user        scanf("%d", &guess);         // When user guesses lower        // than actual number        if (guess > number)         {            printf("Lower number "                   "please!\n");            numberofguess++;        }         // When user guesses higher        // than actual number        else if (number > guess)         {            printf("Higher number"                   " please!\n");            numberofguess++;        }         // Printing number of times        // user has taken to guess        // the number        else            printf("You guessed the"                   " number in %d "                   "attempts!\n",                   numberofguess);     } while (guess != number);} // Driver Codeint main(){    int N = 100;     // Function call    guess(N);     return 0;}
Output: 
7nf2fq8bwubgskh2p1tqxqqmxy2m1q0lln34anu2
Numbers
Technical Scripter 2020
C Language
C Programs
Randomized
Technical Scripter
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2007 | Question 85

27 Sep, 2021
Define the connective * for the Boolean variables X and Y as: X * Y = XY + X’ Y’. Let Z = X * Y.
Consider the following expressions P, Q and R.
P: X = Y⋆Z 
Q: Y = X⋆Z 
R: X⋆Y⋆Z=1
Which of the following is TRUE?(A) Only P and Q are valid(B) Only Q and R are valid.(C) Only P and R are valid.(D) All P, Q, R are valid.Answer: (D)Explanation: * is nothing but working as EX NOR here.Explanation:
P:

X= Y * Z

=(Y XOR Z)’

=YZ + Y’Z’

=Y(XY + X’Y’)+Y’(XY+X’Y’)’

=XY+Y’((Y XOR X)’)’

=XY+Y’(Y XOR X)

=XY+Y’(Y’X+X’Y)

=XY+Y’X

=X(Y+Y’)

=X 
Q:

Y=X*Z

=(X XOR Z)’

=X(XY + X’Y’) + X’(XY + X’Y’)’

=XY+X’(X’Y+XY’)

=XY+X’Y

=Y 
R:

X * Y *Z

WE HAVE SEEN FROM P Y*Z =X

SO X * X

	NOT(X XOR X)=X’X’+XX
	1
 
NOT(X XOR X)=X’X’+XX
1
SO ALL P,Q,R ARE CORRECT
ANS IS (D)
Boolean Algebra and Identities | GATE PYQs  with Rishabh Setiya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersBoolean Algebra and Identities | GATE PYQs  with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0015:57 / 22:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mDkgr_tIfYc" 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-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Find the Normal and Trace of a Matrix

23 May, 2022
For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix.
Normal of a matrix is defined as the square root of the sum of squares of all the elements of the matrix.
Trace of a given square matrix is defined as the sum of all the elements in the diagonal.
Examples :
Input : matrix[][] = {{1, 4, 4},
                     {2, 3, 7},
                     {0, 5, 1}};
Output : Normal = 11  
         Trace  = 5
Explanation :  
Normal = sqrt(1*1+ 4*4 + 4*4 + 2*2 +
             3*3 + 7*7 + 0*0 + 5*5 + 1*1)    
       = 11
Trace  = 1+3+1 = 5

Input :matrix[][] = {{8, 9, 11},
                    {0, 1, 15},
                    {4, 10, -7}};
Output : Normal = 25  
         Trace  = 2
Explanation :  
Normal = sqrt(8*8 +9*9 + 11*11 + 0*0 + 1*1 +  
            15*15 + 4*4 + 10*10 + -7*-7) = 25   
Trace  = (8+1-7) = 2
Example:
Java
// Java program to find the trace// and normal of the given matrix import java.io.*; class geeksforgeeks {     // Dimension of the given matrix    static int max = 50;     // Finds Normal of the given    // matrix of size N x N    static int Normal(int matrix[][], int N)    {        // Initializing sum        int s = 0;        for (int j = 0; j < N; j++)            for (int k = 0; k < N; k++)                s += matrix[j][k] * matrix[j][k];        return (int)Math.sqrt(s);    }     // Finds trace of the given    // matrix of size N x N    static int Trace(int matrix[][], int N)    {        int s = 0;        for (int j = 0; j < N; j++)            s += matrix[j][j];        return s;    }     // The Driver code    public static void main(String[] args)    {         int matrix[][] = {            { 2, 3, 5, 6, 7 },      { 8, 9, 10, 11, 12 },            { 13, 14, 15, 16, 17 }, { 18, 1, 3, 0, 6 },            { 7, 8, 11, 8, 11 },        };         System.out.println("Trace of the Matrix is: "                           + Trace(matrix, 5));        System.out.println("Normal of the Matrix is: "                           + Normal(matrix, 5));    }}
Trace of the Matrix is: 37
Normal of the Matrix is: 50
Time Complexity: O(N*N), as we are using nested loops for traversing the matrix.
Auxiliary Space: O(1), as we are not using any extra space.
rohitsingh07052
java-basics
Java
Java Programs
Mathematical
Mathematical
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Byte intValue() method in Java with examples

05 Dec, 2018
The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.
Syntax
ByteObject.intValue()
Return Value: It returns the value of ByteObject as int.
Below is the implementation of intValue() method in Java:
Example 1:
// Java code to demonstrate// Byte intValue() method  class GFG {    public static void main(String[] args)    {          // byte value        byte a = 17;          // wrapping the byte value        // in the wrapper class Byte        Byte b = new Byte(a);          // intValue of the Byte Object        int output = b.intValue();          // printing the output        System.out.println("Integer value of "                           + a + " is : " + output);    }}
Integer value of 17 is : 17

Example 2:
// Java code to demonstrate// Byte intValue() method  class GFG {    public static void main(String[] args)    {          String value = "17";          // wrapping the byte value        // in the wrapper class Byte        Byte b = new Byte(value);          // intValue of the Byte Object        int output = b.intValue();          // printing the output        System.out.println("Integer value of "                           + b + " is : " + output);    }}
Integer value of 17 is : 17

Java - util package
Java-Byte
Java-Functions
java-lang-reflect-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function - GeeksforGeeks

01 Jun, 2021
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. 
Syntax: paste0(“0”, vec) or sprintf(“%0d”, vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros  
Example 1:  
r
# R Program to add leading zeros # Create example vectorvec <- c(375, 21, 1, 7, 0)vec   # Add leading zerosvec_0 <- paste0("0", vec)vec_0     
Output :  
[1] 375  21   1   7   0
[1] "0375" "021"  "01"   "07"   "00"  
Example 2:  
r
# R Program to add leading zeros # Create example vectorvec <- seq(5) # Add leading zerossprintf("sequence_%03d", vec)
Output :  
[1] "sequence_001" "sequence_002" "sequence_003" "sequence_004" "sequence_005"
 
arorakashish0911
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Time Series Analysis in R
R - if statement
How to import an Excel File into R ?