code-rag-bench/online-tutorials huggingface dataset:
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method - GeeksforGeeks

06 Dec, 2021
Given a list of integers, now our task is to sort the given list of integers. So we use the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. This method is overloaded in two different ways:
OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>): It is used to sort the items of the given sequence in ascending order according to the key and performs a stable sort on the given sequence or list.
OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>): It is used to sort the items of the given sequence in ascending order by using a given comparer and also performs a stable sort on the given sequence.
Example: 
Input  : [90, 87, 34, 23, 22, 56, 21, 89]
Output : [21, 22, 23, 34, 56, 87, 89, 90] 

Input  : [10, 11, 2, 3, 18, 5,]
Output : [2, 3, 5, 10, 11, 18] 
Approach:
1. Create and initialize a list of integer types. For example nums.
2. Sorting the list(named nums) using OrderBy() method
var result_set = nums.OrderBy(num => num);
3. Display the result using the foreach loop.
Example:
C#
// C# program to sort a list of integers // Using OrderBy() methodusing System;using System.Linq;using System.Collections.Generic;  class GFG{      static void Main(string[] args){    // Creating and initializing list of integers    List<int> nums = new List<int>() { 50, 20, 40, 60, 33, 70 };          // Using order by method we sort the list    var result_set = nums.OrderBy(num => num);          // Display the list    Console.WriteLine("Sorted in Ascending order:");    foreach (int value in result_set)    {        Console.Write(value + " ");    }}}
Sorted in Ascending order:
20 33 40 50 60 70 
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to Print a New Line in C#
Program to find absolute value of a given number
Data Structures | Heap | Question 5 - GeeksforGeeks

28 Jun, 2021
Consider a binary max-heap implemented using an array. Which one of the following array represents a binary max-heap? (GATE CS 2009)(A) 25,12,16,13,10,8,14(B) 25,12,16,13,10,8,14(C) 25,14,16,13,10,8,12(D) 25,14,12,13,10,8,16Answer: (C)Explanation: A tree is max-heap if data at every node in the tree is greater than or equal to it’s children’ s data.
In array representation of heap tree, a node at index i has its left child at index 2i + 1 and right child at index 2i + 2.
           25
        /      \
      /          \
    14            16
   /  \           /  \
 /      \       /     \
13     10      8       12
Quiz of this Question
Data Structures
Data Structures-Heap
Heap Quizzes
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Difference between Singly linked list and Doubly linked list
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Data Structures | Stack | Question 4
Advantages of vector over array in C++
Program to create Custom Vector Class in C++
Fetching top news using news API in Python

News API is very famous API for searching and fetching news articles from any web site, using this API anyone can fetch top 10 heading line of news from any web site.
But using this API, one thing is required which is the API key.
import requests    
def Topnews():
   # BBC news api
   my_api_key="Api_number”
   my_url = = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=my_api_key"
   my_open_bbc_page = requests.get(my_url).json()
   my_article = my_open_bbc_page["articles"]
   my_results = []
   for ar in my_article:
      my_results.append(ar["title"])
   for i in range(len(my_results)):
      print(i + 1, my_results[i])                
# Driver Code
if __name__ == '__main__':
   # function call
   Topnews()
Using pandas DataFrame is much easier to work with down the road, we can easily convert from JSON to DataFrame using pd.DataFrame.from_dict and .appy([pd.Series]).
How to change the partial plot background using ggplot2 in R?

To change the partial plot background, we can create a rectangle using geom_rect function by defining both the axes values and alpha for transparency, the color will be changed by using fill argument. The value of alpha will completely hide the grey background and we can play with its value based on our need.
 Live Demo
Consider the below data frame −
x<−rpois(20,5)
y<−rpois(20,5)
df<−data.frame(x,y)
df
x y
1 5 4
2 4 5
3 4 3
4 6 2
5 7 5
6 2 4
7 3 8
8 7 5
9 2 3
10 5 3
11 7 7
12 5 4
13 8 2
14 6 4
15 3 8
16 2 9
17 5 2
18 8 5
19 2 8
20 6 6
Loading ggplot2 package and creating a point chart between x and y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating a rectangle inside the plot to change the background of the plot −
ggplot(df,aes(x,y))+geom_point()+geom_rect(aes(xmin=3,xmax=7,ymin=0,ymax=10),fill="green",alpha=0.05)
How to set the margins of a Matplotlib figure?

To set the margins of a matplotlib figure, we can use margins() method.
Set the figure size and adjust the padding between and around the subplots.
Create t and y data points using numpy.
Add a subplot to the current figure at index 1.
Plot t and y data points using plot() method.
Set the title of the plot.
Add a subplot to the current figure at index 2.
Plot t and y data points using plot() method.
Set the title of the plot.
Set margins of the plot using margins(x=0, y=0).
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

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

t = np.linspace(-2, 2, 10)
y = np.exp(-t)
plt.subplot(121)
plt.plot(t, y)
plt.title("Without margins")
plt.subplot(122)
plt.plot(t, y)
plt.title("With x=0 and y=0 margins")
plt.margins(x=0, y=0)
plt.show()
How to initialize an array using lambda expression in Java?

An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java. But generic array initializes cannot be used.
interface Algebra {
   int operate(int a, int b);
}
public class LambdaWithArray1 {
   public static void main(String[] args) {
      // Initialization of an array in Lambda Expression
      Algebra alg[] = new Algebra[] {
                                        (a, b) -> a+b,
                                        (a, b) -> a-b,
                                        (a, b) -> a*b,
                                        (a, b) -> a/b
                                    };
      System.out.println("The addition of a and b is: " + alg[0].operate(30, 20));
      System.out.println("The subtraction of a and b is: " + alg[1].operate(30, 20));
      System.out.println("The multiplication of a and b is: " + alg[2].operate(30, 20));
      System.out.println("The division of a and b is: " + alg[3].operate(30, 20));
   }
}
The addition of a and b is: 50
The subtraction of a and b is: 10
The multiplication of a and b is: 600
The division of a and b is: 1
interface CustomArray<V> {
   V arrayValue();
}
public class LambdaWithArray2 {
   public static void main(String args[]) {
      // Initilaize an array in Lambda Expression
      CustomArray<String>[] strArray = new CustomArray[] {
                                                     () -> "Adithya",
                                                     () -> "Jai",
                                                     () -> "Raja",
                                                     () -> "Surya"
                                                 };
      System.out.println(strArray[0].arrayValue());
      System.out.println(strArray[1].arrayValue());
      System.out.println(strArray[2].arrayValue());
      System.out.println(strArray[3].arrayValue());
   }
}
Adithya
Jai
Raja
Surya
Insert Data from Database to Spreadsheet

How to insert data from a database to a spread sheet using Java.
Following is the program to insert data from a database to a spread sheet using Java.
import java.io.File;
import java.io.FileOutputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class InsertDataFromDataBaseToSpreadSheet {
   public static void main(String[] args) throws Exception {

      //Connecting to the database
      Class.forName("com.mysql.jdbc.Driver");
      Connection connect = DriverManager.getConnection(
         "jdbc:mysql://localhost:3306/details", "root" , "password");

      //Getting data from the table emp_tbl
      Statement statement = connect.createStatement();
      ResultSet resultSet = statement.executeQuery("select * from student_data");

      //Creating a Work Book
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Creating a Spread Sheet
      XSSFSheet spreadsheet = workbook.createSheet("employe db");
      XSSFRow row = spreadsheet.createRow(1);
      XSSFCell cell;
      
      cell = row.createCell(1);
      cell.setCellValue("EMP ID");
      
      cell = row.createCell(2);
      cell.setCellValue("EMP NAME");
      
      cell = row.createCell(3);
      cell.setCellValue("DEG");
      
      cell = row.createCell(4);
      cell.setCellValue("SALARY");
      
      cell = row.createCell(5);
      cell.setCellValue("DEPT");
      int i = 2;

      while(resultSet.next()) {
         row = spreadsheet.createRow(i);
         cell = row.createCell(1);
         cell.setCellValue(resultSet.getInt("ID"));
         
         cell = row.createCell(2);
         cell.setCellValue(resultSet.getString("NAME"));
         
         cell = row.createCell(3);
         cell.setCellValue(resultSet.getString("BRANCH"));
         
         cell = row.createCell(4);
         cell.setCellValue(resultSet.getString("PERCENTAGE"));
         
         cell = row.createCell(5);
         cell.setCellValue(resultSet.getString("EMAIL"));
         i++;
      }
      
      FileOutputStream out = new FileOutputStream(
         new File("C:/poiexcel/exceldatabase.xlsx"));
      
      workbook.write(out);
      out.close();
      
      System.out.println("exceldatabase.xlsx written successfully");
   }
}
mysql> select * from student_data; 
+----+--------+--------+------------+---------------------+ 
| ID | NAME   | BRANCH | PERCENTAGE | EMAIL               | 
+----+--------+--------+------------+---------------------+ 
|  1 | Ram    | IT     |         85 | ram123@gmail.com    | 
|  2 | Rahim  | EEE    |         95 | rahim123@gmail.com  | 
|  3 | Robert | ECE    |         90 | robert123@gmail.com | 
+----+--------+--------+------------+---------------------+ 
3 rows in set (0.00 sec)

 Print
 Add Notes
 Bookmark this page
Natural Sort in JavaScript

We have an array that contains some numbers and some strings, we are required to sort the
array such that the numbers get sorted and get placed before every string and then the string
should be placed sorted alphabetically.
Let’s say this is our array −
const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
The output should look like this −
[1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd']
Therefore, let’s write the code for this −
const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];
const sorter = (a, b) => {
   if(typeof a === 'number' && typeof b === 'number'){
      return a - b;
   }else if(typeof a === 'number' && typeof b !== 'number'){
      return -1;
   }else if(typeof a !== 'number' && typeof b === 'number'){
      return 1;
   }else{
      return a > b ? 1 : -1;
   }
}
arr.sort(sorter);
console.log(arr);
The output in the console will be −
[
   1, 6, 7,
   9, 47, 'afv',
   'bdf', 'fdf', 'svd'
]
Is it possible to select text boxes with JavaScript?

Yes, select text box with JavaScript using the select() method. At first, let us create an input
text −
Enter your Name:<input type="text" id="txtName" value="John">
<br>
<button type="button" onclick="check()">Select Text Box</button>
Now, let us select the text box on button click −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
Enter your Name:<input type="text" id="txtName" value="John">
<br>
<button type="button" onclick="check()">Select Text Box</button>
<script>
   function check(){
      document.getElementById("txtName").select();
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
When you click the button “Select Text Box”, it will select the text box. This will produce the
following output −
PyQt5 - How to hide the items from drop down box in Combo Box - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can hide the items of the combo box from the drop down box i.e from view box. In order to do so we have to get the view object of combo box and had to hide it.
In order to hide the items we have to do the following steps –
1. Create Combo box2. Add items to the combo box3. Get the view object of combo box4. Hide the view object
Syntax :
# getting view part of combo box
view = self.combo_box.view()

# hiding the view part
view.setHidden(True)

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # making it editable        self.combo_box.setEditable(True)          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # getting view part of combo box        view = self.combo_box.view()          # making view box hidden        view.setHidden(True)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Python Program to Filter Rows with a specific Pair Sum - GeeksforGeeks

12 Nov, 2020
Given Matrix, the following program shows how to extract all rows which have a pair such that their sum is equal to a specific number, here denoted as K.
Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], k = 8 Output : [[1, 5, 3, 6], [6, 9, 3, 2]] Explanation : 5 + 3 = 8 and 6 + 2 = 8. Input : test_list = [[1, 5, 4, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 7]], k = 8 Output : [] Explanation : No list with 8 as pair summation. 
Method 1 : Using loop and list comprehension
In this we perform the task of getting all the pair whose sum is equal to a given value using external function and filtering of lists is done using list comprehension.
Python3
# get pair sumdef pair_sum(x, k):      # checking pair sum    for idx in range(len(x)):        for ix in range(idx + 1, len(x)):            if x[idx] + x[ix] == k:                return True    return False    # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing Kk = 8  # checking for pair sumres = [ele for ele in test_list if pair_sum(ele, k)]  # printing resultprint("Filtered Rows : " + str(res))
Output:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]
Method 2 : Using filter() and lambda
In this, we perform task of filtering using filter() and lambda function. 
Python3
# get pair sumdef pair_sum(x, k):      # checking pair sum    for idx in range(len(x)):        for ix in range(idx + 1, len(x)):            if x[idx] + x[ix] == k:                return True    return False    # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing Kk = 8  # checking for pair sum# filtering using filter() and lambdares = list(filter(lambda ele: pair_sum(ele, k), test_list))  # printing resultprint("Filtered Rows : " + str(res))
Output:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to show legend in heatmap in R? - GeeksforGeeks

23 Feb, 2021
A heat map is a graphical representation of data where each data value is represented in terms of color value. Heatmap is created using heatmap() function in R. Legend associated with histogram makes it easy to understand what the color values mean. Legend is shown with histogram using legend() function in R.
heatmap() function in R Language is used to plot a heatmap. Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix.
Syntax: heatmap(data)
Parameters:data: It represent matrix data, such as values of rows and columns
Return: This function draws a heatmap
legend() function in R Language is used to add legends to an existing Plot. A legend is defined as an area of the graph plot describing each of the parts of the plot. The legend plot is used to show statistical data in graphical form.
Syntax:legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
Parameters:x and y: These are co-ordinates to be used to position the legendlegend: Text of the legendfill: Colors to use for filling the boxes with legend textcol: Colors of linesbg: It defines background color for the legend box.title: Legend title (optional)text.font: An integer specifying the font style of the legend (optional)
Returns: Legend plot
Create data matrix
Plot heatmap using heatmap() method
Provide appropriate attributes with respective values
Associate legend with heatmap using legend() method
Run code to display plot
Example 1:
R
# Create data matrixA <- matrix(rnorm(25, 0, 5), nrow = 5, ncol = 5)  print(A)  # Plot a heatmap heatmap(A,Rowv=NA,Colv=NA,col=heat.colors(3))  # Plot a corresponding legendlegend(x="right", legend=c("min", "med", "max"),fill=heat.colors(3))
Output:
Example 2:
R
# Import library for colorlibrary(RColorBrewer)  # Create data matrixA = matrix(  c(1,2,0,3,4,0,2,1,3,3,0,0,4,    4,1,4,3,1,4,3,0,2,1,1,4),  nrow = 5, ncol = 5)          # Plot a heatmapheatmap(A, Rowv = NA, Colv = NA,         col = colorRampPalette(brewer.pal(8,"Blues"))(3))  # Plot a legend in bottom right part of heatmaplegend(x = "bottomright", legend = c("low", "medium", "high"),       cex = 0.8, fill = colorRampPalette(brewer.pal(8, "Blues"))(3))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
Logistic Regression in R Programming
R - if statement
Python | Sort list of numbers by sum of their digits - GeeksforGeeks

11 May, 2020
Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits.
Examples:
Input : [12, 10, 106, 31, 15]
Output : [10, 12, 31, 15, 106]

Input : [1111, 19, 29, 11, 12, 9]
Output : [11, 12, 1111, 9, 19, 29]

Let’s discuss few Pythonic ways to do this task.
Approach #1 : List comprehension
Using for loop to convert each element of list to a different list with its digits as elements. Now, use the sorted function with the above-mentioned function as key.
# Python3 Program to Sort list of# integers according to sum of digits  def sortList(lst):    digits = [int(digit) for digit in str(lst) ]    return sum(digits)      # Driver Codelst = [12, 10, 106, 31, 15]print(sorted(lst, key = sortList))
[10, 12, 31, 15, 106]

Approach #2 : Using map()
This approach is similar to the above approach with a slight difference that instead of for loop, we use map() to convert each element of list to a different list with its digit as elements and then follow the similar approach as above.
# Python3 Program to Sort list of# integers according to sum of digits  def sortList(num):    return sum(map(int, str(num)))      # Driver Codelst = [12, 10, 106, 31, 15]result = sorted(lst, key = sortList)print(result)
[10, 12, 31, 15, 106]

There is also a one-liner alternative to the above mentioned approach.
def sortList(lst):    return sorted(lst, key = lambda x:(sum(map(int, str(x)))))
Python list-programs
python-list
Python-sort
Python
Python Programs
python-list
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | sympy.sec() method - GeeksforGeeks

02 Aug, 2019
With the help of sympy.sec() method, we are able to find the value of sec theta using sympy.sec() function.
Syntax : sympy.sec()Return : Return value of sec theta.
Example #1 :In this example we can see that by using sympy.sec() method, we can find the value of sec theta.
# import sympyfrom sympy import *  # Use sympy.sec() methodgfg = simplify(sec(pi / 6))    print(gfg)
Output :
2*sqrt(3)/3
Example #2 :
# import sympyfrom sympy import *  # Use sympy.sec() methodgfg = simplify(sec(pi / 3))    print(gfg)
Output :
2
SymPy
Python
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
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
SVG font-size Attribute - GeeksforGeeks

31 Mar, 2022
The font-size attribute refers to the size of the font from baseline when multiple lines of text are set solid in a multiline layout environment.
Syntax:
font-size="size"
Attribute Values:
length: Length at which we want to set the size.
percentage: Percentage at which we want to set the size.
We will use the font size attribute for setting the size of font.
Example 1 
<!DOCTYPE html><html>  <body>    <svg viewBox="0 0 600 100"         xmlns="http://www.w3.org/2000/svg">                  <text x="10" y="50"             font-size="smaller">            smaller        </text>                  <text x="10" y="30"             font-size="2em">            larger        </text>    </svg></body>  </html>
Output:
Example 2: 
<!DOCTYPE html><html>  <body>    <svg viewBox="0 0 600 100"         xmlns="http://www.w3.org/2000/svg">                  <text x="10" y="50"             font-size="60%">            smaller        </text>                  <text x="10" y="30"             font-size="240%">            larger        </text>    </svg></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to Convert Models Data into JSON in Django ? - GeeksforGeeks

16 Mar, 2021
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design.  It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc.
How to Convert Models Data Into Json Data In Django ?
First create new project
django-admin startproject tryJson
cd tryJson
Then create new app inside your project
python manage.py startapp main
Add your main app inside the tryJson/settings.py in INSTALLED_APPS
Edit the models.py in main app
Python3
from django.db import models  class Student(models.Model):    course_choices = (        ('1','Java'),        ('2','Python'),        ('3','Javascript')        )    name = models.CharField(max_length=50)    rollno = models.IntegerField()    course = models.CharField(max_length=15,        choices = course_choices)
Then to create model we have to write below commands in cmd or terminal
python manage.py makemigrations
python manage.py migrate
So we have created our model Students with some fields like name , roll no , course.
Insert Some data into model.
Create a new file inside your main app 
urls.py
Python3
from django.urls import pathfrom .  import *  urlpatterns = [    path("",views.jsondata,name = "jsondata"),]
Write logic to convert models data into Json data
views.py
Python3
from django.http import JsonResponsefrom .models import Students  def jsondata(request):      data list(Students.objects.values())    return JsonResponse(data,safe = False)
Use values() method to get all the data and convert into list using list() function and store in a variable.
return a JsonResponse and pass the data and   put safe = False
Then  open cmd or terminal to run this app
python manage.py runserver
Output :-
Django-models
JSON
Python Django
Python Framework
Python
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
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Selenium WebDriver Error: AttributeError: 'list' object has no attribute 'click'

We can get the Selenium webdriver error: AttributeError: 'list' object has no attribute 'click' while working on a test. Let us see an example of code where we have encountered such an error.
Code Implementation
from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.tutorialspoint.com/index.htm")
#identify an element
m = driver.find_elements_by_name('search')
m.click()
#browser quit
driver.quit()
In the above code, we have got the error as we have used find_elements_by_name instead of find_element_by_name to perform a click operation on a single element. The method find_elements_by_name returns a list of elements.
Here, we want to perform click operation on an element, so the webdriver fails to identify the element on which it should perform the click. In this scenario, if we want to use the find_elements_by_name method, we have to explicitly mention the index of the element to be clicked.
Code Implementation
from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.tutorialspoint.com/index.htm")
#identify an element with find_element_by_name
m = driver.find_element_by_name('search')
m.click()
m.send_keys('Selenium')
s = m.get_attribute('value')
print('Value entered: ' + s)
#browser quit
driver.quit()
Why main() method must be static in java?

Static − If you declare a method, subclass, block, or a variable static it is loaded along with the class.
In Java whenever we need to call an (instance) method we should instantiate the class (containing it) and call it. If we need to call a method without instantiation it should be static. Moreover, static methods are loaded into the memory along with the class.
In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static.
The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line.
You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program.
It searches for the main method which is public, static, with return type void, and a String array as an argument.
public static int main(String[] args){
}
If such a method is not found, a run time error is generated.
In the following Java program in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static.
 Live Demo
import java.util.Scanner;
public class Sample{
   public void main(String[] args){
      System.out.println("This is a sample program");
   }
}
On executing, this program generates the following error −
Error: Main method is not static in class Sample, please define the main method
as:public static void main(String[] args)
Adding elements in a vector in R programming - append() method - GeeksforGeeks

10 May, 2020
append() method in R programming is used to append the different types of integer values into a vector in the last.
Syntax: append(x, value, index(optional))
Return: Returns the new vector after appending given value.
Example 1:
x <- rep(1:5)  # Using rep() methodgfg <- append(x, 10)  print(gfg)
Output:
[1]  1  2  3  4  5 10

Example 2:
x <- rep(10:15)  # Using rep() methodgfg <- append(x, 1, 1)  print(gfg)
Output:
[1] 10  1 11 12 13 14 15

R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Enumerated Types or Enums in C++

In this tutorial, we will be discussing a program to understand Enumerated types or Enums in C++.
Enumerated types are user-defined data types in which the user can specify a limited number of values that can be allocated to the variable.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   //defining enum variable
   enum Gender {
      Male,
      Female
   };
   Gender gender = Male;
   switch (gender) {
      case Male:
         cout << "Gender is Male";
         break;
      case Female:
         cout << "Gender is Female";
         break;
      default:
         cout << "Value can be Male or Female";
   }
   return 0;
}
Gender is Male
Binary array to corresponding decimal in JavaScript

We are required to write a JavaScript function that takes in a binary array (consisting of only 0 and 1).
Our function should first join all the bits in the array and then return the decimal number corresponding to that binary.
Following is the code −
 Live Demo
const arr = [1, 0, 1, 1];
const binaryArrayToNumber = arr => {
   let num = 0;
   for (let i = 0, exponent = 3; i < arr.length; i++) {
      if (arr[i]) {
         num += Math.pow(2, exponent);
      };
      exponent--;
   };
   return num;
};
console.log(binaryArrayToNumber(arr));
11
Adding a column that doesn't exist in a query?

Add a column that does not exist in a query, with the help of AS keyword. The syntax is as follows −
SELECT yourColumnName1,yourColumnName2,....N,yourValue AS yourColumnName,....N' FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ColumnDoesNotExists
    -> (
    -> UserId int,
    -> UserName varchar(20)
    -> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(100,'Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(101,'Sam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(102,'Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(103,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(104,'Robert');
Query OK, 1 row affected (0.10 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(105,'Maxwell');
Query OK, 1 row affected (0.20 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(106,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(107,'John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(108,'James');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from ColumnDoesNotExists;
+--------+----------+
| UserId | UserName |
+--------+----------+
|    100 |    Larry |
|    101 |      Sam |
|    102 |     Mike |
|    103 |    David |
|    104 |   Robert |
|    105 |  Maxwell |
|    106 |      Bob |
|    107 |     John |
|    108 |    James |
+--------+----------+
9 rows in set (0.00 sec)
Here is the query to add a column name that does not exist in a query −
mysql> select UserId,UserName,23 AS Age from ColumnDoesNotExists;
+--------+----------+-----+
| UserId | UserName | Age |
+--------+----------+-----+
|    100 |    Larry |  23 |
|    101 |      Sam |  23 |
|    102 |     Mike |  23 |
|    103 |    David |  23 |
|    104 |   Robert |  23 |
|    105 |  Maxwell |  23 |
|    106 |      Bob |  23 |
|    107 |     John |  23 |
|    108 |    James |  23 |
+--------+----------+-----+
9 rows in set (0.00 sec)
How to run an external application through a C# application?

An external application can be run from a C# application using Process. A process is a program that is running on your computer. This can be anything from a small background task, such as a spell-checker or system events handler to a full-blown application like Notepad etc.
Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread. Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process. Process is present in System.Diagnostics namespace.
Example to run notepad from C# application
using System;
using System.Diagnostics;
namespace DemoApplication{
   class Program{
      static void Main(){
         Process notepad = new Process();
         notepad.StartInfo.FileName = "notepad.exe";
         notepad.StartInfo.Arguments = "DemoText";
         notepad.Start();
         Console.ReadLine();
      }
   }
}
The above output shows the console application opened Notepad with the name DemoText provided in the arguments.
using System;
using System.Diagnostics;
namespace DemoApplication{
   class Program{
      static void Main(){
         Process.Start("https://www.google.com/");
         Console.ReadLine();
      }
   }
}
The above code will open the browser and redirect to www.google.com.
How to use a pipe with Linux find command?

Linux find statement is one of the most widely used statements that allows us to walk a file hierarchy. It is used to mostly find a specific file or directories and we can also append different other Linux statements or flags along with it to enhance or do a complex operation.
Let’s explore an example of a find statement to understand it better.
In the Linux code shown below, I am trying to search for a file inside my Downloads folder, and for that I am making use of the find statement
find sample.sh
sample.sh
Notice that if the find command is able to locate the file then it will simply print the name of the file, if not then it will not return anything the terminal process will terminate.
Now we know how the find statement works, let’s explore the case where we want to use the find command along with a pipe.
A pipe in Linux is just a vertical bar on your keyboard. It is used to consider the command that is on the left side of it as an input to the command on the right side of it.
Now that we know about both the find command the pipe in Linux, let’s consider an example where we will make use of both of these in a Linux command.
find . -name '*.txt' | xargs cat
In the above command, just before the pipe, I am considering all the files that has a name that ends with a .txt extension and then after the pipe, I am simply printing those with the help of the cat command.
immukul@192 directory1 % find . -name '*.txt' | xargs cat
this is a test file and it is used for testing and is not available for anything else so
please stop asking, lionel messi
orange
orange
blabla
blabla
foofoo
here
is the
text
to keep between the 2 patterns
bar
blabla
blabla
HTML | <li> type Attribute

08 Mar, 2022
The <li> type attribute in HTML is used to specify the type of a list items. This attribute also defines the style of the bullet point of the list items. 
Syntax: 
<li type="1|a|A|i|I|disc|circle|square">
Attribute Values: For ordered list items:  
1: It is the default value. It is used to specify the numerical ordered list.
a: It arranged the list items in lower case letters.
A: It arrange the list items in the form of upper case.
i: It arrange the list items in the roman numbers in the form of lower case letters.
I: It arranged the list in roman numerals in the form of uppercase letters.
For unordered list items:  
disc: It is the default value. It creates a filled circle.
circle: It creates an unfilled circle.
square: It creates a filled square.
Note: The <li> type attribute is not supported by HTML 5 Instead of using this attribute we can use CSS list-style-type property.
Example 1:  
HTML
<!DOCTYPE html><html> <head>    <title>        HTML li type Attribute    </title></head>     <body>         <h1 style = "color: green;">        GeeksforGeeks    </h1>                 <h2>        HTML list item type Attribute    </h2>                   <p>Sorting Algorithms</p>                <ol>        <li type="a">Merge sort</li>        <li>Quick sort</li>        <li type="I">Insertion sort</li>    </ol></body> </html>                   
Output: 
Example 2:  
HTML
<!DOCTYPE html><html> <head>    <title>        HTML li type Attribute    </title></head>     <body>         <h1 style = "color: green;">        GeeksforGeeks    </h1>                 <h2>        HTML li type Attribute    </h2>                   <p>Sorting Algorithms</p>                <ul>        <li>Merge sort</li>        <li>Quick sort</li>        <li type="square">Insertion sort</li>    </ul></body> </html>                   
Output: 
Supported Browsers: The browser supported by HTML <li> type attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
anikaseth98
hritikbhatnagar2182
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)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
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
Python – String Integer Product

25 Jun, 2020
Sometimes, while working with data, we can have a problem in which we receive a series of lists with data in string format, which we wish to find the product of each string list integer. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + int()This is the brute force method to perform this task. In this, we run a loop for the entire list, convert each string to integer and perform product listwise and store in a separate list.
# Python3 code to demonstrate working of# String Integer Product# using loop + int()  # getting Productdef prod(val) :    res = 1     for ele in val:        res *= int(ele)    return res   # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']]  # printing original list print("The original list : " + str(test_list))  # String Integer Product# using loop + int()res = []for sub in test_list:    par_prod = prod(sub)    res.append(par_prod)  # printing resultprint("List after product of nested string lists : " + str(res))
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after product of nested string lists : [4, 30, 70]

 
Method #2 : Using loop + int() + list comprehensionThis is the shorthand with the help of which this task can be performed. In this, we run a loop on lists using list comprehension and extract product using explicit product function.
# Python3 code to demonstrate working of# String Integer Product# using loop + int() + list comprehension  # getting Productdef prod(val) :    res = 1     for ele in val:        res *= int(ele)    return res   # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']]  # printing original list print("The original list : " + str(test_list))  # String Integer Product# using loop + int() + list comprehensionres = [prod(sub) for sub in test_list]  # printing resultprint("List after product of nested string lists : " + str(res))
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after product of nested string lists : [4, 30, 70]

nidhi_biet
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | strip_tags() Function

02 Nov, 2020
The strip_tags() function is an inbuilt function in PHP which is used to strips a string from HTML, and PHP tags. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.
Syntax: 
string strip_tags( $str, $allowable_tags ) 




Parameters: This function accepts two parameters as mentioned above and described below: 
$string: It is a required parameter that specifies the string to be check.
$allow: It is an optional parameter that specifies allowable tags. These tags will not be removed.
Return Value: This function Returns the stripped string.
Exceptions:  
This function strip HTML comments and PHP tags. It can not be used this in $allow tags because this is already hardcoded.
PHP 5.3.4 and later versions, ignored the self-closing XHTML tags
strip_tags() does not validate the HTML.
Below programs illustrate the strip_tags() function in PHP: 
Program 1:  
PHP
<?php // PHP programme to illustrate// strip_tags function without $allow parameterecho strip_tags("Hello <b>GeeksforGeeks!</b>");?>
Hello GeeksforGeeks!





 
Program 2: 
PHP
<?php // PHP programme to illustrate// strip_tags function with $allow parameter echo strip_tags("Hello <b><i>GeeksorGeeks!</i></b>", "<b>");?>
Hello <b>GeeksorGeeks!</b>





 
Related Articles: 
PHP | str_split() Function
PHP | chop() Function
Reference: http://php.net/manual/en/function.strip-tags.php 
arorakashish0911
PHP-function
PHP-string
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to delete columns by their name in data.table in R?

We can do this by setting the column to NULL
> library(data.table)
> df <- data.frame(numbers = 1:10, x = runif(10,25,75))
> data_table <- data.table(df)
To delete one column x
> data_table[, x:=NULL]
> data_table
numbers
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
10: 10
To delete two columns
> df <- data.frame(numbers = 0:9, x = runif(10,25,75), y=rnorm(10))
> Data_table <- data.table(df)
Data_table[, c("x","y"):=NULL]
> Data_table
numbers
1: 0
2: 1
3: 2
4: 3
5: 4
6: 5
7: 6
8: 7
9: 8
10: 9
Program to find largest rectangle area under histogram in python

Suppose we have a list of numbers representing heights of bars in a histogram. We have to find area of the largest rectangle that can be formed under the bars.
So, if the input is like nums = [3, 2, 5, 7]
then the output will be 10
To solve this, we will follow these steps −
stk := a stack and initially insert -1 into it
insert 0 at the end of heights
ans := 0
for i in range 0 to size of heights, dowhile heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w)push i into stk
while heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w)
h := heights[top of stk] and pop from stk
w := i - top of stk - 1
ans := maximum of ans and (h * w)
push i into stk
return ans
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
   def solve(self, heights):
      stk = [-1]
      heights.append(0)
      ans = 0
      for i in range(len(heights)):
         while heights[i] < heights[stk[-1]]:
            h = heights[stk.pop()]
            w = i - stk[-1] - 1
            ans = max(ans, h * w)
         stk.append(i)
      return ans

ob = Solution()
nums = [3, 2, 5, 7]
print(ob.solve(nums))
[3, 2, 5, 7]
10