code-rag-bench/online-tutorials huggingface dataset:
React Render HTML

React's goal is in many ways to render HTML in a web page.
React renders HTML to the web page by using a function called 
ReactDOM.render().
The ReactDOM.render() function takes two 
arguments, HTML code and an HTML element.
The purpose of the function is to display the specified HTML code inside the 
specified HTML element.
But render where?
There is another folder in the root directory of your React project, named "public".
In this folder, there is an index.html file.
You'll notice a single <div>
in the body of this file. This is where our React application will be rendered.
Display a paragraph inside an element with the id of "root":
ReactDOM.render(<p>Hello</p>, document.getElementById('root'));
The result is displayed in the <div id="root"> element:
<body>
  <div id="root"></div>
</body>


Run 
Example »

Note that the element id does not have to be called "root", but this is the standard convention.
The HTML code in this tutorial uses JSX which allows you to write HTML tags 
inside the JavaScript code:
Do not worry if the syntax is unfamiliar, you will learn more about JSX in the next chapter.
Create a variable that contains HTML code and display it in the "root" node:
const myelement = (
  <table>
    <tr>
      <th>Name</th>
    </tr>
    <tr>
      <td>John</td>
    </tr>
    <tr>
      <td>Elsa</td>
    </tr>
  </table>
);

ReactDOM.render(myelement, document.getElementById('root'));


Run 
Example »

The root node is the HTML element where you want to display the result.
It is like a container for content managed by React.
It does NOT have to be a <div> element and it does 
NOT have to 
have the id='root':
The root node can be called whatever you like:
<body>

  <header id="sandy"></header>

</body>

Display the result in the <header id="sandy"> element:
ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));


Run 
Example »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Lodash _.orderBy() Method

06 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers, etc. The _.orderBy() method is similar to _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.
Syntax:
_.orderBy(collection, iteratees, orders)
Parameters: This method accepts three parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: This parameter holds the iteratees to sort by.
order: This parameter holds the sort orders of iteratees.
Return Value: This method returns the new sorted array.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
// Requiring the lodash library const _ = require("lodash");        // Original array var users = [  { 'patron': 'jonny',   'age': 48 },  { 'patron': 'john', 'age': 34 },  { 'patron': 'john',   'age': 40 },  { 'patron': 'jonny', 'age': 36 }];   // Use of _.orderBy() method// Sort by `patron` in ascending order// and by `age` in descending order   let gfg = _.orderBy(users, ['patron', 'age'],              ['asc', 'desc']);  // Printing the output console.log(gfg);
Output:
[
  { 'patron': 'john',   'age': 40 },
  { 'patron': 'john', 'age': 34 },
  { 'patron': 'jonny',   'age': 48 },
  { 'patron': 'jonny', 'age': 36 }
]

Example 2:
// Requiring the lodash library const _ = require("lodash");        // Original array var users = [  { 'employee': 'hunny',   'salary': 60000 },  { 'employee': 'munny', 'salary': 40000 },  { 'employee': 'hunny',   'salary': 55000 },  { 'employee': 'munny', 'salary': 36000 }];   // Use of _.orderBy() method// Sort by `employee` in ascending order// and by `salary` in descending order   let gfg = _.orderBy(users, ['employee',            'salary'], ['asc', 'desc']);  // Printing the output console.log(gfg);
Output:
[
  { 'employee': 'hunny',   'salary': 60000 },
  { 'employee': 'hunny', 'salary': 55000 },
  { 'employee': 'munny',   'salary': 40000 },
  { 'employee': 'munny', 'salary': 36000 }
]

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between children and childNodes in JavaScript?

16 Aug, 2019
childNodes:The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes. Nodelist items are objects, not strings and they can be accessed using index numbers. The first childNode starts at index 0.Syntaxelement.childNodes
Syntax
element.childNodes
childrenThe children is a property of element which returns the child elements of an element as objects.Syntaxelement.children
Syntax
element.children
The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes.
Example 1: This example illustrates the property of childNodes.
<!DOCTYPE html><html>  <body>    <style>        p {            color: green;        }    </style><center>    <h1 style="color:green">GeeksforGeeks</h1>    <h2>childNodes</h2>    <button onclick="childNode()">        Try it    </button>      <p id="geek"></p>      <script>        function childNode() {            //accessing all the child nodes present in our code            var childNode =                 document.body.childNodes;            var string = "";            var i;                      for (i = 0; i < childNode.length; i++) {                string = string + childNode[i].nodeName + "<br>";            }              //appending the child nodes to paragraph with id "geek"            document.getElementById(            "geek").innerHTML = string;        }    </script></center></body>  </html>
Output:Before:After:
Example 2: This example illustrates the property of children.
<!DOCTYPE html><html>  <body>    <style>        p {            color: green;        }    </style><center>    <h1 style="color:green">GeeksforGeeks</h1>    <h2>children</h2>          <button onclick="myChildren()">      Try it  </button>      <p id="geek"></p>      <script>        function myChildren() {            var c = document.body.children;            var string = "";            var i;            for (i = 0; i < c.length; i++) {                string = string + c[i].tagName + "<br>";            }              document.getElementById(              "geek").innerHTML = string;        }    </script></center></body>  </html>
Output:Before:After:
Supported Browsers:
Google ChromeMozilla FirefoxApple SafariOperaInternet Explorer/Edge
Google Chrome
Mozilla Firefox
Apple Safari
Opera
Internet Explorer/Edge
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Concatenation Operator

21 Mar, 2018
Prerequisite: Basic Select statement, Insert into clause, SQL Create Clause, SQL Aliases
|| or concatenation operator is use to link columns or character strings. We can also use a literal. A literal is a character, number or date that is included in the SELECT statement.
Let’s demonstrate it through an example:
Syntax:
SELECT id, first_name, last_name, first_name || last_name, 
               salary, first_name || salary FROM myTable
Output (Third and Fifth Columns show  values concatenated by operator ||)
id  first_name  last_name    first_name||last_name  salary   first_name||salary    
1   Rajat        Rawat          RajatRawat          10000    Rajat10000                                                               
2   Geeks        ForGeeks      GeeksForGeeks        20000    Geeks20000                    
3   Shane        Watson         ShaneWatson         50000    Shane50000                           
4   Kedar        Jadhav         KedarJadhav         90000     Kedar90000                           

Note: Here above we have used || which is known as Concatenation operator which is used to link 2 or as many columns as you want in your select query and it is independent of the datatype of column. Here above we have linked 2 columns i.e, first_name+last_name as well as first_name+salary.
We can also use literals in the concatenation operator. Let’s see:
Example 1: Using character literalSyntax:
SELECT id, first_name, last_name, salary, 
      first_name||' has salary '||salary as "new"  FROM myTable

Output : (Concatenating three values and giving a name 'new')
id  first_name  last_name  salary            new
1   Rajat        Rawat     10000      Rajat has salary 10000
2   Geeks        ForGeeks  20000      Geeks has salary 20000
3   Shane        Watson    50000      Shane has salary 50000
4   Kedar        Jadhav    90000      Kedar has salary 90000


Note: Here above we have used has salary as a character literal in our select statement. Similarly we can use number literal or date literal according to our requirement.
Example 2: Using character as well as number literalSyntax:
SELECT id, first_name, last_name, salary, first_name||100||' 
                          has id '||id AS "new" FROM myTable

Output (Making readable output by concatenating a string
with values)

id  first_name   last_name     salary     new
1    Rajat       Rawat         10000    Rajat100 has id 1
2    Geeks       ForGeeks      20000    Geeks100 has id 2
3    Shane       Watson        50000    Shane100 has id 3
4    Kedar       Jadhav        90000    Kedar100 has id 4
Here above we have used has salary as a character literal as well as 100 as number literal in our select statement.
References:1) About Concatenation operator: Oracle Docs2) Performing SQL Queries Online: Oracle Live SQL
Note: For performing SQL Queries online you must have account on Oracle, if you don’t have then you can make by opening above link.
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flask â Environment

Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7.
virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.
The following command installs virtualenv
pip install virtualenv

This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager.
Sudo apt-get install virtualenv

Once installed, new virtual environment is created in a folder.
mkdir newproj
cd newproj
virtualenv venv

To activate corresponding environment, on Linux/OS X, use the following −
venv/bin/activate

On Windows, following can be used
venv\scripts\activate

We are now ready to install Flask in this environment.
pip install Flask

The above command can be run directly, without virtual environment for system-wide installation.

    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Matplotlib.axes.Axes.draw() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.draw() function in axes module of matplotlib library is used to draw everything.
Syntax: Axes.draw(self, renderer=None, inframe=False)
Parameters: This method accepts the following parameters.
renderer: This parameter is the first parameter and its default value is None.
inframe: This parameter contains the boolean value and its default value is false.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.draw() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt       fig, ax = plt.subplots()     def tellme(s):     ax.set_title(s, fontsize = 16)     fig.canvas.draw()    renderer = fig.canvas.renderer    ax.draw(renderer)  tellme('matplotlib.axes.Axes.draw() function Example') plt.show() 
Output:
Example 2:
# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt       fig = plt.figure() ax = fig.add_subplot(111, projection ='3d')     X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5,                    cstride = 5)     for angle in range(0, 90):     ax.view_init(30, angle)    fig.canvas.draw()    renderer = fig.canvas.renderer    ax.draw(renderer)     plt.pause(.001)     ax.set_title('matplotlib.axes.Axes.draw()\    function Example', fontweight ="bold") 
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Python | Check if element is present in tuple of tuples

26 Jan, 2019
Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for a missing data or N.A values in data preprocessing. Let’s discuss certain ways in which this can be performed.
Method #1 : Using any()any function is used to perform this task. It just tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned.
# Python3 code to demonstrate # test for values in tuple of tuple# using any()  # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  # printing tupleprint ("The original tuple is " + str(test_tuple))  # using any()# to test for value in tuple of tupleif (any('geeksforgeeks' in i for i in test_tuple)) :    print("geeksforgeeks is present")else :    print("geeksforgeeks is not present")
Output :
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))
geeksforgeeks is present

 
Method #2 : Using itertools.chain()The chain function tests for all the intermediate tuples for the desired values and then returns true if the required value is present in any of the tuples searched.
# Python3 code to demonstrate # test for values in tuple of tuple# using itertools.chain()import itertools  # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  # printing tupleprint ("The original tuple is " + str(test_tuple))  # using itertools.chain()# to test for value in tuple of tupleif ('geeksforgeeks' in itertools.chain(*test_tuple)) :    print("geeksforgeeks is present")else :    print("geeksforgeeks is not present")
Output :
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))
geeksforgeeks is present

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Regular languages and finite automata - GeeksforGeeks

06 Oct, 2021
1. Complement of L(A) is context-free.
2. L(A) = L((11*0+0)(0 + 1)*0*1*)
3. For the language accepted by A, A is the minimal DFA.
4. A accepts all strings over {0, 1} of length at least 2. 
1) abaabaaabaa
2) aaaabaaaa
3) baaaaabaaaab
4) baaaaabaa 
1) abaabaaabaa
2) aaaabaaaa
3) baaaaabaaaab
4) baaaaabaa 
             L={| k>0, and n is a positive integer constant}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
50 Common Ports You Should Know
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Spring Boot - Thymeleaf with Example
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
How to use arrays to swap variables in JavaScript ?
Samsung R&D Interview Experience
How to add horizontal line in HTML ?
Saving all the open Matplotlib figures in one file at once

To save all the open Matplotlib figures in one file at once, we can take follwong steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure (fig1) or activate an existing figure using figure() method.
Plot the first line using plot() method.
Create a new figure (fig2) or activate an existing figure using figure() method.
Plot the Second line using plot() method.
Initialize a variable, filename, to make a pdf file.
Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp.
Get the number of open figures.
Iterate the opened figures and save them into a file.
To display the figure, use show() method.
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig1 = plt.figure()
plt.plot([2, 1, 7, 1, 2], color='red', lw=5)

fig2 = plt.figure()
plt.plot([3, 5, 1, 5, 3], color='green', lw=5)

def save_multi_image(filename):
   pp = PdfPages(filename)
   fig_nums = plt.get_fignums()
   figs = [plt.figure(n) for n in fig_nums]
   for fig in figs:
      fig.savefig(pp, format='pdf')
   pp.close()

filename = "multi.pdf"
save_multi_image(filename)
When we execute the code, it will save the following two plots as a PDF file (multi.pdf) in the project directory.
How to find datatype of all the fields in MongoDB?

Use typeof to find datatype of all the fields −
typeof db.yourCollectionName.findOne().yourFieldName;
Let us first create a collection with documents −
> db.findDataTypeDemo.insertOne({"ClientName":"Chris","isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf2064dceb9a92e6aa1952")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDataTypeDemo.findOne();
This will produce the following output −
{
   "_id" : ObjectId("5ccf2064dceb9a92e6aa1952"),
   "ClientName" : "Chris",
   "isMarried" : false
}
Following is the query to find datatype of a field in MongoDB −
> typeof db.findDataTypeDemo.findOne().isMarried;
This will produce the following output −
Boolean
Here is the query to get the data type of another field −
> typeof db.findDataTypeDemo.findOne().ClientName;
This will produce the following output −
String
You can get the value also. The query is as follows −
> db.findDataTypeDemo.findOne().ClientName;
Chris
> db.findDataTypeDemo.findOne().isMarried;
False
7 Ways to Check CPU Clock Speed in Linux - GeeksforGeeks

20 Apr, 2021
In general, a higher clock speed means a faster CPU. However, many other factors come into play. Your CPU processes many instructions (low-level calculations like arithmetic) from different programs every second. The clock speed measures the number of cycles your CPU executes per second, measured in GHz (gigahertz). A “cycle” is technically a pulse synchronized by an internal oscillator, but for our purposes, they’re a basic unit that helps understand a CPU’s speed. During each cycle, billions of transistors within the processor open and close.
On Linux, there are a number of commands that can be used to obtain the CPU speed of the processor. In this article, we’ll look at some of the most widely used commands for obtaining CPU speed about the CPU.
Hardinfo is a graphical user interface (GUI) tool that produces reports on various hardware components. It is written in Gtk. However, if there is no GUI display available, it can also be run from the command line.
$ hardinfo | less
Using hardinfo
The /proc/cpuinfo system file lists each CPU Core. System’s individual speed.
$ cat /proc/cpuinfo | grep MHz
From /proc/cpuinfo
Inxi is a Linux script that allows you to print the system’s hardware details. To print processor-related details, use the inxi command with the ‘-C’ option:
$ sudo  inxi -C
Using Inxi script
In Linux, the hwinfo command prints detailed details about each hardware unit.
$ sudo hwinfo --cpu
Using hwinfo
Lscpu is a Linux command that displays CPU architecture details. The util-linux package contains this instruction.
$ sudo lscpu
Using lscpu
Dmesg displays messages from the kernel ring buffer and dumps them to /var/log/messages in Linux.
$ sudo dmesg | grep MHz
Using Dmesg
The i7z is a dedicated tool for displaying processor states on Intel i3, i5, and i7 based CPUs.
$ sudo i7z
Using i7z
On Linux-based systems such as Ubuntu, Fedora, Debian, CentOS, and others, those were some commands to check CPU speed.
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
mv command in Linux with examples
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Basic Operators in Shell Scripting
Python - Filter immutable rows representing Dictionary Keys from Matrix - GeeksforGeeks

01 Nov, 2020
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable.
Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]] Output : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] Explanation : All elements in tuples are immutable. 
Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4), [3, 2]], [{5:4}, 3, “good”], [True, “best”]] Output : [[True, ‘best’]] Explanation : All elements in tuples are immutable. 
Method #1 : Using all() + isinstance()
In this, we check for all elements to be of the instance of immutable data types, rows that return True for all elements, is filtered.
Python3
# Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using all() + isinstance()  # initializing listtest_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [    True, "best"]]  # printing original listprint("The original list is : " + str(test_list))  # checking for each immutable data typeres = [row for row in test_list if all(isinstance(ele, int) or isinstance(ele, bool)                                       or isinstance(ele, float) or isinstance(ele, tuple)                                       or isinstance(ele, str) for ele in row)]  # printing resultprint("Filtered rows : " + str(res))
Output:
The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]
Method #2 : Using filter() + lambda + isinstance() + all()
In this, we perform task of filtering using filter() + lambda function, rest all functionalities are performed as above method.
Python3
# Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using filter() + lambda + isinstance() + all()  # initializing listtest_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [    True, "best"]]  # printing original listprint("The original list is : " + str(test_list))  # checking for each immutable data type# filtering using filter()res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool)                                  or isinstance(ele, float) or isinstance(ele, tuple)                                  or isinstance(ele, str) for ele in row), test_list))  # printing resultprint("Filtered rows : " + str(res))
Output:
The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Go - Method

Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call a function using "." operator. For example −
func (variable_name variable_data_type) function_name() [return_type]{
   /* function body*/
}

package main

import (
   "fmt" 
   "math" 
)

/* define a circle */
type Circle struct {
   x,y,radius float64
}

/* define a method for circle */
func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

func main(){
   circle := Circle{x:0, y:0, radius:5}
   fmt.Printf("Circle area: %f", circle.area())
}
When the above code is compiled and executed, it produces the following result −
Circle area: 78.539816


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to display an image with rounded corners on iOS App using Swift?

To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer.
First of all, let’s add an UIImageView Object in our storyboard. Or let’s create one programmatically.
Below is a function that will programmatically create an image view and add an image to it.
func addImage(imageName img: String) {
   let imageView = UIImageView()
   imageView.frame = CGRect(x: 10, y: 20, width: 200, height: 200)
   imageView.contentMode = . scaleAspectFill
   if let newImage = UIImage(named: img) {
      imageView.image = newImage
   }
   self.view.addSubview(imageView)
}
Let’s suppose the original image that we want to add in our application is −
in our viewDidLoad, let’s call the code below to add this image to our application.
Below is how it looks without any change to its corner property.
Now, let’s add the corner radius property to our existing code and see how it looks.
imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true
Add these two lines in the addImage function, right above the addSubview method. When we run the application this is how it looks now −
We can also create an extension of UIImageView and use the same like as shown below, which again produces the same result.
extension UIImageView {
   func makeRoundCorners(byRadius rad: CGFloat) {
      self.layer.cornerRadius = rad
      self.clipsToBounds = true
   }
}
imageView.makeRoundCorners(byRadius: 20)
Tryit Editor v3.7

Tryit: bigger emojis
How to Get Last Modified Date of File in Linux? - GeeksforGeeks

28 Mar, 2021
Here we are going to see how to get the last modified date of the file in Linux, sometimes we may require timestamps of the file and apart from this it also ensures that we have the latest version of that file.
It can be done in four ways:
Using Stat command.
Using date command.
Using ls -l command.
Using httpie
Example 1: Using Stat command.
Apart from this if you only want to see the modified date then use the below command
$ stat -c ‘%y’ filename
-c displays the date and %y displays the modification time.
Example 2: Using date command.
You can use the below command to display the last modification date of the file
$ date -r filename
Example 3: Using ls -l command:
The below command is used.
$ ls -lt filename
Example 4: Using httpie:
You can check the last modified date of the file which is residing on the webserver and the command is also used for interacting with HTTP servers and APIs.
Below syntax is used to check the last modified date of the file which is on the webserver.
$ http -h  [url] | grep 'Last-Modified'
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Is it possible to override a Java method of one class in same?

When we have two classes where one extends another and if, these two classes have the same method including parameters and return type (say, sample) the method in the subclass overrides the method in the superclass.
i.e. Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass.
But if you call the method (sample), the sampling method of the subclass will be executed overriding the super class’s method.
 Live Demo
class Super{
   public static void sample(){
      System.out.println("Method of the superclass");
   }
}
public class OverridingExample extends Super {
   public static void sample(){
      System.out.println("Method of the subclass");
   }  
   public static void main(String args[]){
      Super obj1 = (Super) new OverridingExample();
      OverridingExample obj2 = new OverridingExample();
      obj1.sample();
      obj2.sample();
   }
}
Method of the superclass
Method of the subclass
While overriding −
Both methods should be in two different classes and, these classes must be in an inheritance relation.
Both methods should be in two different classes and, these classes must be in an inheritance relation.
Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods.
Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods.
The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception.
The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception.
If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception).
If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception).
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
Minimum Moves to Equal Array Elements II in Python

Suppose we have a non-empty integer array, we have to find the minimum number of moves that are required to make all array elements equal, where a move is incrementing or decrementing a selected element by 1. So when the array is like [1, 2, 3], then the output will be 2, as 1 will be incremented to 2, and 3 will be decremented to 2.
To solve this, we will follow these steps −
sort the array nums
set counter as 0
for i in nums, docounter := counter + absolute of (i – nums[length of nums / 2])
counter := counter + absolute of (i – nums[length of nums / 2])
return counter
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution:
   def minMoves2(self, nums):
      nums.sort()
      counter = 0
      for i in nums:
         counter += abs(i-nums[len(nums)//2])
      return counter
ob1 = Solution()
print(ob1.minMoves2([2,5,3,4]))
[2,5,3,4]
4
How to open browser window in incognito/private mode using python selenium webdriver?

We can open a browser window in incognito/private mode with Selenium webdriver in Python using the ChromeOptions class. We have to create an object of the ChromeOptions class.
Then apply the method add_argument to that object and pass the parameter -- incognito has a parameter. Finally, this information has to be passed to the webdriver object.
c = webdriver.ChromeOptions()
c.add_argument("--incognito")
from selenium import webdriver
#object of ChromeOptions class
c = webdriver.ChromeOptions()
#incognito parameter passed
c.add_argument("--incognito")
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",options=c)
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
How to sort List in descending order using Comparator in Java

Let us first create an ArrayList −
ArrayList<Integer>arrList = new ArrayList<Integer>();
arrList.add(10);
arrList.add(50);
arrList.add(100);
arrList.add(150);
arrList.add(250);
Use Comparators interface to order in reverse order with reverseOrder() −
Comparator comparator = Collections.reverseOrder();
Now, sort with Collections:
Collections.sort(arrList, comparator);
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer>arrList = new ArrayList<Integer>();
      arrList.add(10);
      arrList.add(50);
      arrList.add(100);
      arrList.add(150);
      arrList.add(250);
      arrList.add(100);
      arrList.add(150);
      arrList.add(250);
      Comparator comparator = Collections.reverseOrder();
      System.out.println("List = "+arrList);
      Collections.sort(arrList, comparator);
      System.out.println("Sorted List in descending order = "+arrList);
   }
}
List = [10, 50, 100, 150, 250, 100, 150, 250]
Sorted List in descending order = [250, 250, 150, 150, 100, 100, 50, 10]
WWW-Authenticate Response Header Field

The resource server must include the HTTP "WWW-Authenticate" response header field, if the protected resource request contains an access token that is invalid or if the access token is malformed.
"WWW-Authenticate" header field uses the following format −
challenge               =   "OAuth" RWS token-challenge
token-challenge         =   realm
                            [CS error]
                            [CS error-uri]
                            [CS scope]
                            [CS 1#auth –param]
error                   =   "error"  "=" <"> token <">
error-desc              =   "error_description" "=" quoted-string
error-uri               =   "error_uri" = <"> URI-Reference <">
scope                   =   quoted-value / <"> quoted-value *(1*SP quoted-value) <">
    quoted-value        =   1* quoted-char

where,
realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once.
realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once.
error − It is an attribute used to provide a client the specific reason why the access request was declined.
error − It is an attribute used to provide a client the specific reason why the access request was declined.
error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred.
error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred.
error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred.
error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred.
scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource.
scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource.
 Print
 Add Notes
 Bookmark this page
Birthday Paradox in C++

The birthday paradox is a very famous problem in the section of probability. The problem statement of this problem is stated as,
There are several people at a birthday party, some are having the same birthday collision. We need to find the approximate no. of people at a birthday party on the basis of having the same birthday.
In the probability we know that the chance of getting ahead is 1/2 same as if we have some coins, the chance of getting 10 heads is 1/100 or 0.001.
Let us understand the concept,
The chance of two people having the different birthday is,
364/365 which is 1-1/365 in a Non-leap year.
Thus we can say that the first person having the probability of a specific birthday is ‘1’ and for others, it would be different which is,
P(different)= 1×(1-1/365)× (1-2/365)× (1-3/365) × (1-4/365).......
Thus P(same)= 1- P(different)
For Example,
No. of people having the same birthday for which probability is 0.70.
N= √2×365×log(1-1/p).
N= √2×365×log(1-1/0.70)= 30
Thus total approximate no. of people having the same birthday is 30.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
int findPeople(double p){
   return ceil(sqrt(2*365*log(1/(1-p))));
}
int main(){
   printf("%d",findPeople(0.70));
}
30
Difference between Image Sampling and Quantization

03 Dec, 2019
To create a digital image, we need to convert the continuous sensed data into digital form.This process includes 2 processes:
Sampling: Digitizing the co-ordinate value is called sampling.Quantization: Digitizing the amplitude value is called quantization.
Sampling: Digitizing the co-ordinate value is called sampling.
Quantization: Digitizing the amplitude value is called quantization.
To convert a continuous image f(x, y) into digital form, we have to sample the function in both co-ordinates and amplitude.
Difference between Image Sampling and Quantization:
computer-graphics
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert a string into number in PHP?

31 Jul, 2021
Strings in PHP can be converted to numbers (float / int / double) very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert string into number in PHP some of them are discussed below:
Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.
Example:
<?php  $num = "1000.314";  // Convert string in number using // number_format(), functionecho number_format($num), "\n";  // Convert string in number using // number_format(), functionecho number_format($num, 2);?>
1,000
1,000.31

Method 2: Using type casting: Typecasting can directly convert a string into float, double or integer primitive type. This is the best way to convert a string into number without any function.
Example:
<?php  // Number in string format$num = "1000.314";  // Type cast using intecho (int)$num, "\n";  // Type cast using floatecho (float)$num, "\n";  // Type cast using doubleecho (double)$num;?>
1000
1000.314
1000.314

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.
Example:
<?php  // Number in string format$num = "1000.314";  // intval() function to convert // string into integerecho intval($num), "\n";  // floatval() function to convert// string to floatecho floatval($num);?>
1000
1000.314

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.
<?php      // Number into string format$num = "1000.314";  // Performing mathematical operation // to implicitly type conversionecho $num + 0, "\n";  // Performing mathematical operation // to implicitly type conversionecho $num + 0.0, "\n";  // Performing mathematical operation // to implicitly type conversionecho $num + 0.1;?>
1000.314
1000.314
1000.414

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | Marquee loop attribute

14 Jan, 2022
The Marquee loop attribute in HTML is used to define the number of time marquee should loop. The default value of loop is INFINITE.Syntax:  
<marquee loop="number" >
Attribute value:  
number: Specify the number of loop.
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML Marquee loop attribute</title>    <style>        .main {            text-align: center;            font-family: "Times New Roman";        }                 .marq {            padding-top: 30px;            padding-bottom: 30px;        }                 .geek1 {            font-size: 36px;            font-weight: bold;            color: white;            text-align: center;        }                 .geek2 {            text-align: center;        }    </style></head> <body>    <div class="main">        <marquee class="marq"                 bgcolor="Green"                 direction="up"                 loop="1">                       <div class="geek1">GeeksforGeeks</div>            <div class="geek2">              A computer science portal for geeks          </div>        </marquee>        <marquee class="marq"                 bgcolor="Green"                 direction="up"                 loop="2">                       <div class="geek1">GeeksforGeeks</div>            <div class="geek2">              A computer science portal for geeks          </div>        </marquee>    </div></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML Marquee loop attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
NLP | WordNet for tagging

18 Dec, 2019
WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing.
Code #1 : Creating class to look up words in WordNet.
from nltk.tag import SequentialBackoffTaggerfrom nltk.corpus import wordnetfrom nltk.probability import FreqDist  class WordNetTagger(SequentialBackoffTagger):          '''    >>> wt = WordNetTagger()    >>> wt.tag(['food', 'is', 'great'])    [('food', 'NN'), ('is', 'VB'), ('great', 'JJ')]    '''          def __init__(self, *args, **kwargs):                  SequentialBackoffTagger.__init__(self, *args, **kwargs)        self.wordnet_tag_map = {        'n': 'NN',        's': 'JJ',        'a': 'JJ',        'r': 'RB',        'v': 'VB'        }          def choose_tag(self, tokens, index, history):              word = tokens[index]    fd = FreqDist()          for synset in wordnet.synsets(word):        fd[synset.pos()] += 1                        return self.wordnet_tag_map.get(fd.max())
This WordNetTagger class will count the no. of each POS tag found in the Synsets for a word and then, the most common tag is to treebank tag using internal mapping.
Code #2 : Using a simple WordNetTagger()
from taggers import WordNetTaggerfrom nltk.corpus import treebank  # Initializingdefault_tag = DefaultTagger('NN')  # initializing training and testing set    train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:]  wn_tagging = WordNetTagger()a = wn_tagger.evaluate(test_data)  print ("Accuracy of WordNetTagger : ", a)
Output :
Accuracy of WordNetTagger : 0.17914876598160262

Using Code 3, we can improve the accuracy.Code #3 : WordNetTagger class at the end of an NgramTagger backoff chain
from taggers import WordNetTaggerfrom nltk.corpus import treebankfrom tag_util import backoff_taggerfrom nltk.tag import UnigramTagger, BigramTagger, TrigramTagger  # Initializingdefault_tag = DefaultTagger('NN')  # initializing training and testing set    train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:]  tagger = backoff_tagger(train_data,                        [UnigramTagger, BigramTagger,                         TrigramTagger], backoff = wn_tagger)      a = tagger.evaluate(test_data)  print ("Accuracy : ", a)
Output :
Accuracy : 0.8848262464925534

shubham_singh
Natural-language-processing
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove One to Make Average k in Python

Suppose we have a list of numbers called nums and an integer k, we have to check whether we
can remove exactly one element from the list to make the average equal to exactly k. Now we
have to keep in mind that, there are some constraints −
2 ≤ n ≤ 1,000 where n is number of elements of nums list
nums[i], k ≤ 1,000,000
So, if the input is like [5,3,2,4,6,10], k = 4, then the output will be True as if we remove 10, then
the average of elements will be (5+3+2+4+6)/5 = 4, this is same as k.
To solve this, we will follow these steps −
s:= total sum of all elements in nums
t := k*(size of nums - 1)
for each i in nums, doif s-i is same as t, thenreturn True
if s-i is same as t, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums, k):
      s=sum(nums)
      t = k*(len(nums)-1)
      for i in nums:
         if s-i == t:
            return True
      return False
ob = Solution()
nums = [5,3,2,4,6,10]
k = 4
print(ob.solve(nums, k))
[5,3,2,4,6,10], 4
True