code-rag-bench/online-tutorials huggingface dataset:
Sum values of a single row in MySQL?

You can use below syntax to sum values of a single row −
Case 1 − The following is the syntax if your column does not have NULL value −
SELECT yourColumnName1+yourColumnName2+yourColumnName3+.......+N as anyVariableName FROM yourTableName;
Case 2 − If your column has NULL value then use this syntax −
SELECT IFNULL(yourColumnName1,0)+ IFNULL(yourColumnName2,0)+ IFNULL(yourColumnName3,0)+.............+N
AS anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table SumValueOfSingleRow
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FirstValue int,
   -> SecondValue int,
   -> ThirdValue int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(1,0,1);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(1,NULL,0);
Query OK, 1 row affected (0.19 sec)

mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(NULL,NULL,NULL);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SumValueOfSingleRow;
The following is the output −
+----+------------+-------------+------------+
| Id | FirstValue | SecondValue | ThirdValue |
+----+------------+-------------+------------+
|  1 |          1 |           0 |          1 |
|  2 |          1 |        NULL |          0 |
|  3 |       NULL |        NULL |       NULL |
+----+------------+-------------+------------+
3 rows in set (0.00 sec)
Look at the sample output. If you use CASE 1, then you won’t get appropriate result.
Let us check CASE 1, which we discussed above. The query is as follows −
mysql> select FirstValue+SecondValue+ThirdValue as SingleRowSum from SumValueOfSingleRow;
The following is the output −
+--------------+
| SingleRowSum |
+--------------+
|            2 |
|         NULL |
|         NULL |
+--------------+
3 rows in set (0.06 sec)
Look at the sample output, the above query does not handle the NULL case. Now you can use the CASE 2 to get the appropriate result.
The query is as follows −
mysql> select ifnull(FirstValue,0)+ ifnull(SecondValue,0)+ ifnull(ThirdValue,0) as SingleRowSum from SumValueOfSingleRow;
The following is the output displaying the sum of values of a single row −
+--------------+
| SingleRowSum |
+--------------+
|            2 |
|            1 |
|            0 |
+--------------+
3 rows in set (0.06 sec)
How can matplotlib be used to plot 3 different datasets on a single graph in Python?

Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively.
Matplotlib is used to create 2 dimensional plots with the data. It comes with an object−oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on. It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.
Python can be installed on Windows using the below command −
pip install matplotlib
The dependencies of Matplotlib are −
Python ( greater than or equal to version 3.4)
NumPy
Setuptools
Pyparsing
Libpng
Pytz
Free type
Six
Cycler
Dateutil
Let us understand how Matplotlib can be used to plot 3 different data sets in a single plot −
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x = np.linspace(0, 2, 100)
fig, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x label name')
ax.set_ylabel('y label name')
ax.set_title("My Plot")
ax.legend()
The required packages are imported and its alias is defined for ease of use.
The required packages are imported and its alias is defined for ease of use.
An empty figure is created using the ‘figure’ function.
An empty figure is created using the ‘figure’ function.
The data is created using NumPy package.
The data is created using NumPy package.
The ‘subplot’ function is used to create outlines for three different plots.
The ‘subplot’ function is used to create outlines for three different plots.
The type of plot for each of the three datasets is defined.
The type of plot for each of the three datasets is defined.
The labels for ‘X’ and ‘Y’ axis is defined.
The labels for ‘X’ and ‘Y’ axis is defined.
The title of the plot is defined, and it is shown on the console.
The title of the plot is defined, and it is shown on the console.
Period normalized() method in Java with Examples - GeeksforGeeks

27 Nov, 2018
The normalized() method of Period class in Java is used to return a new instance of Period after normalizing years and months.
Syntax:
public Period normalized()
Parameters: This function does not accepts any parameter.
Return Value: This function returns a new instance of Period after normalizing year and month of the period.
Exceptions: It throws an ArithmeticException. This exception is caught if numeric overflow occurs.
Below program illustrates the above method:
Program 1:
// Java code to show the function to normalize// months and years of the periodimport java.time.Period;import java.time.temporal.ChronoUnit;  public class PeriodClass {      // Function to normalize given periods    static void toNormalize(Period p1)    {          System.out.println(p1.normalized());    }      // Driver Code    public static void main(String[] args)    {        // Defining period        int year = 4;        int months = 15;        int days = 10;        Period p1 = Period.of(year, months, days);          toNormalize(p1);    }}
P5Y3M10D

Program 2: This will not normalize the number of days.
// Java code to show the function to normalize// months and years of the periodimport java.time.Period;import java.time.temporal.ChronoUnit;  public class PeriodClass {      // Function to normalize given periods    static void toNormalize(Period p1)    {          System.out.println(p1.normalized());    }      // Driver Code    public static void main(String[] args)    {        // Defining period        int year = 10;        int months = 25;        int days = 366;        Period p1 = Period.of(year, months, days);          toNormalize(p1);    }}
P12Y1M366D

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#normalized–
Java-Functions
Java-Period
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
PriorityQueue in Java
How to iterate any Map in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java
reflect.New() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.New() Function in Golang is used to get the Value representing a pointer to a new zero value for the specified type. To access this function, one needs to imports the reflect package in the program.
Syntax:
func New(typ Type) Value

Parameters: This function takes the following parameters:
typ : This parameter is the Type.
Return Value: This function returns a Value representing a pointer to a new zero value for the specified type.
Below examples illustrate the use of above method in Golang :Example 1:
// Golang program to illustrate// reflect.New() Function    package main   import (    "fmt"    "reflect")   // Main function func main() {    t := reflect.TypeOf(5)           //use of ArrayOf method    arr := reflect.ArrayOf(4, t)    inst := reflect.New(arr).Interface().(*[4]int)       for i := 1; i <= 4; i++ {        inst[i-1] = i*i    }       fmt.Println(inst)}
Output:
&[1 4 9 16]

Example 2:
// Golang program to illustrate// reflect.New() Function    package main   import (    "fmt"    "reflect")    type Geek struct {    A int `tag1:"First Tag" tag2:"Second Tag"`    B string}  // Main functionfunc main() {    greeting := "GeeksforGeeks"    f := Geek{A: 10, B: "Number"}      gVal := reflect.ValueOf(greeting)      fmt.Println(gVal.Interface())      gpVal := reflect.ValueOf(&greeting)    gpVal.Elem().SetString("Articles")    fmt.Println(greeting)      fType := reflect.TypeOf(f)    fVal := reflect.New(fType)    fVal.Elem().Field(0).SetInt(20)    fVal.Elem().Field(1).SetString("Number")    f2 := fVal.Elem().Interface().(Geek)    fmt.Printf("%+v, %d, %s\n", f2, f2.A, f2.B)}
Output:
GeeksforGeeks
Articles
{A:20 B:Number}, 20, Number

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fmt.Sprintf() Function in Golang With Examples
Inheritance in GoLang
Slices in Golang
Time Formatting in Golang
How to Trim a String in Golang?
How to Split a String in Golang?
How to compare times in Golang?
How to print string with double quotes in Golang?
Command Line Arguments in Golang
fmt.print() Function in Golang With Examples
How to monitor real time SQL execution statistics in Oracle?

Problem:
You want to monitor currently executing SQL statistics in Oracle.
Solution
If your database is Oracle Database 11g, you can use the following query to select from the “V$SQL_MONITOR” to monitor the near real time resource consumption of SQL queries.
The statistics in “V$SQL_MONITOR” are updated every second. This helps us to view the resource consumption as it updates. These statistics are gathered by default when a SQL statement runs in parallel or consumes more than 5 seconds of CPU or I/O time.
The “VSQLMONITOR"viewincludesasubsetofstatisticscontainedinthe"VSQL”, “VSQLAREA",and"VSQLSTATS” views.
The “VSQLMONITOR"viewdisplaysreal−timestatisticsforeachexecutionofaresource−intensiveSQLstatement,whereas"VSQL”, “VSQLAREA",and"VSQLSTATS” contain over-all sets of statistics over multiple executions of a SQL statement.
select * from (
select
 a.sid session_id
,a.sql_id
,a.status
,a.cpu_time/1000000 cpu_sec
,a.buffer_gets
,a.disk_reads
,b.sql_text sql_text
from v$sql_monitor a
    ,v$sql b
where a.sql_id = b.sql_id
order by a.cpu_time desc)
where rownum <=10;
select * from (
select
 a.sid session_id
,a.sql_id
,a.status
,a.cpu_time/1000000 cpu_sec
,a.buffer_gets
,a.disk_reads
,b.sql_text sql_text
from v$sql_monitor a
    ,v$sql b
where a.sql_id = b.sql_id
order by a.cpu_time desc)
where rownum <=10;
Python Tkinter – Set Entry width 100%

Tkinter Entry widgets accept single-line user input in a text field. We can change the properties of the Entry widget by providing the default attributes and values in its constructor.
Let us suppose that we want to create a full-width Entry widget for an application. There are several ways to do that but if we consider the simplest case where we use Pack Geometry Manager to display the Entry widget, then we can definitely set the width of Entry widget by adding fill(x or y) property.
# Import the required library
from tkinter import *
from tkinter import ttk

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

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

# Add bottom widgets in the application
label= Label(win, text= "Enter Your Name")
label.pack()

# Add an entry widget
entry= Entry(win)
entry.pack(fill='x')

win.mainloop()
Executing the above code will display a full-width Entry widget which is expanded to cover the X-axis in the window.
Java Examples - Add Text as Paragraphs

How to add text to a PDF document as paragraphs using Java.
Following is the program to add text to a PDF document as paragraphs using Java.
import com.itextpdf.io.font.FontConstants; 

import com.itextpdf.kernel.color.Color; 
import com.itextpdf.kernel.font.PdfFontFactory; 
import com.itextpdf.kernel.pdf.PdfDocument; 
import com.itextpdf.kernel.pdf.PdfWriter; 

import com.itextpdf.layout.Document; 
import com.itextpdf.layout.element.Paragraph; 
import com.itextpdf.layout.element.Text;  

public class AddingParagraphsToPdf { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf"; 
      
      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));     

      //Creating a Document object 
      Document doc = new Document(pdfDoc);        

      //Adding text to the document 
      Text text1 = new Text("Tutorials Point originated from the idea that there exists
         a class of readers who respond better to online content and prefer to
         learn new skills at their own pace from the comforts of their drawing rooms.");

      //Setting color to the text 
      text1.setFontColor(Color.RED); 

      //Setting font to the text  
      text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 

      //Creating a paragraph 1 
      Paragraph para1 = new Paragraph(text1); 

      Text text2 = new Text("The journey commenced with a single tutorial on HTML in 2006
         and elated by the response it generated, we worked our way to adding fresh
         tutorials to our repository which now proudly flaunts a wealth of tutorials and
         allied articles on topics ranging from programming languages to web designing to
         academics and much more.");  

      //Setting color to the text 
      text2.setFontColor(Color.RED); 
      
      //Setting font to the text  
      text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 

      //Creating a paragraph 2 
      Paragraph para2 = new Paragraph(text2); 

      //Adding paragraphs to the document 
      doc.add(para1);
      doc.add(para2); 

      //Closing the document 
      doc.close(); 

      System.out.println("Text added successfully.."); 
   } 
}
 Print
 Add Notes
 Bookmark this page
How to create a plot in R with gridlines using plot function?

Any plot created by using plot function does not display the plot with gridlines. On the other hand, if we create a plot using ggplot2 package then the plot has gridlines. Therefore, if we want to have gridlines on our plot then either we should create the plot using ggplot2 package or we can use the command grid() to add the gridlines on the plot created by plot function.
Creating a histogram using plot function −
> hist(rnorm(100))
Adding the grid lines to the above plot −
> grid()
Python | Ways to convert string to json object

18 May, 2020
Data send and get generally in a string of dictionary(JSON objects) forms in many web API’s to use that data to extract meaningful information we need to convert that data in dictionary form and use for further operations.
Let’s see some ways to convert string to json.Method #1: dict object to string object using json.loads
# Python code to demonstrate# converting string to json # using json.loadsimport json  # inititialising json objectini_string = {'nikhil': 1, 'akash' : 5,               'manjeet' : 10, 'akshat' : 15}  # printing initial jsonini_string = json.dumps(ini_string)print ("initial 1st dictionary", ini_string)print ("type of ini_object", type(ini_string))  # converting string to jsonfinal_dictionary = json.loads(ini_string)  # printing final resultprint ("final dictionary", str(final_dictionary))print ("type of final_dictionary", type(final_dictionary))
Output:
initial 1st dictionary {'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5}
type of ini_object <type 'str'>
final dictionary {'nikhil': 1, 'manjeet': 10, 'akshat': 15, 'akash': 5}
type of final_dictionary <type 'dict'>

Method #2: str object to dict object using eval()
# Python code to demonstrate# converting string to json # using eval    # inititialising json object stringini_string = """{'nikhil': 1, 'akash' : 5,            'manjeet' : 10, 'akshat' : 15}"""  # printing initial jsonprint ("initial 1st dictionary", ini_string)print ("type of ini_object", type(ini_string))  # converting string to jsonfinal_dictionary = eval(ini_string)  # printing final resultprint ("final dictionary", str(final_dictionary))print ("type of final_dictionary", type(final_dictionary))
Output:
initial 1st dictionary {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}
type of ini_object <class 'str'>
final dictionary {'nikhil': 1, 'manjeet': 10, 'akash': 5, 'akshat': 15}
type of final_dictionary <class 'dict'>

dannyronson
JSON
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.write() function in Python

16 Feb, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to write text at the current turtle position. 
Syntax :
turtle.write(arg, move=False, align=’left’, font=(‘Arial’, 8, ‘normal’))  
Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # write textturtle.write("GeeksForGeeks")
  
Output :
 
 
Example 2 :
 
Python3
# import packageimport turtle # write text# move turtleturtle.write("GeeksForGeeks", move=True)
Output :
Example 3 :
Python3
# import packageimport turtle # write text# styling fontturtle.write("GeeksForGeeks", font=("Verdana",                                    15, "normal"))
Output :
Example 4 :
Python3
# import packageimport turtle # write text# align at rightturtle.write("GeeksForGeeks", align="right")
  
Output :
 
 
prikospy
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create singleton design pattern in PHP 5 ?

06 Jul, 2021
php
<?php class DataBaseConnector {                     private static $obj;                     private final function __construct() {        echo __CLASS__ . " initialize only once ";    }         public static function getConnect() {        if (!isset(self::$obj)) {            self::$obj = new DataBaseConnector();        }                 return self::$obj;    }} $obj1 = DataBaseConnector::getConnect();$obj2 = DataBaseConnector::getConnect(); var_dump($obj1 == $obj2);?>
DataBaseConnector initialize only once bool(true)
 

anikaseth98
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Set Library - set() Function

The C++ constructor std::set::set() (Range Constructor) constructs a set container with as many elements as mentioned in the range [first,last), with each set element constructed from its corresponding element in that range.
Following is the declaration for std::set::set() range constructor from std::set header.
template <class InputIterator>
 set (InputIterator first, InputIterator last,
      const key_compare& comp = key_compare(),
      const allocator_type& alloc = allocator_type());

template <class InputIterator>
   set (InputIterator first, InputIterator last,
        const key_compare& comp = key_compare(),
        const allocator_type& = allocator_type());
template <class InputIterator>
  set (InputIterator first, InputIterator last,
       const key_compare& comp = key_compare(),
       const allocator_type& = allocator_type());
template <class InputIterator>
  set (InputIterator first, InputIterator last,
       const allocator_type& = allocator_type());

alloc − Input iterator to initial position.
alloc − Input iterator to initial position.
comp − Comparison function object to use for all comparisons of keys
comp − Comparison function object to use for all comparisons of keys
first, last − The range to copy from which are Input Iterators. This range includes the elements from first to last, including the element pointed by first but excluding the one pointed by last.
first, last − The range to copy from which are Input Iterators. This range includes the elements from first to last, including the element pointed by first but excluding the one pointed by last.
Constructor never returns any value.
This member function has no effect in case any exception is thrown. However, if the range specified by [first,last) is invalid, it may result in undefined behavior.
N log(N), where N = std::distance(first, last);
else linear (O(N)) in the distance between the iterators, if the elements are already sorted.
The following example shows the usage of std::set::set() range constructor.
#include <iostream>
#include <set>

using namespace std;

int main(void) {
   char vowels[] = {'a','e','i','o','u'};
  
   // Range Constructor
   std::set<char> t_set (vowels, vowels+5);  

   std::cout <> "Size of set container t_set is : " << t_set.size();
   return 0;
}
Let us compile and run the above program, this will produce the following result −
Size of set container t_set is : 5

 Print
 Add Notes
 Bookmark this page
How can we set the background color to a JPanel in Java?

A JPanel is a container and it is an invisible component in Java. The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, table, list, tree and etc. to a JPanel. We can set a background color to JPanel by using the setBackground() method.
import java.awt.*
import javax.swing.*;
public class JPanelBackgroundColorTest extends JFrame {
   private JPanel panel;
   public JPanelBackgroundColorTest() {
      setTitle("JPanelBackgroundColor Test");
      panel = new JPanel();
      panel.add(new JLabel("Welcome to Tutorials Point"));
      panel.setBackground(Color.green);
      add(panel, BorderLayout.CENTER);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JPanelBackgroundColorTest();
   }
}
Powershell - Read Text File

Get-Content cmdlet is used to read content of a text file.
In this example, we're reading content of test.txt.
Get-Content D:\temp\test\test.txt 

You can see following output in PowerShell console.
Welcome to TutorialsPoint


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
C# Linq SkipLast Method

Skip elements from the end and return the remaining elements using the SkipLast() method.
The following is an array.
int[] marks = { 45, 88, 50, 90, 95, 85 };
Now, let us skip two elements from the end using SkipLast() and Lambda Expressions, but this is done after arranging the elements in descending order.
IEnumerable<int> selMarks = marks.AsQueryable().OrderByDescending(s => s).SkipLast(2);
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      int[] marks = { 45, 88, 50, 90, 95, 85 };
      IEnumerable<int> selMarks = marks.AsQueryable().OrderByDescending(s => s).SkipLast(2);
      Console.WriteLine("Skipped the marks of last two students...");
      foreach (int res in selMarks)
      Console.WriteLine(res);
   }
}
Skipped the marks of last two students...
95
90
88
85
Explain Generator functions in JavaScript?

JavaScript supports Generator functions and Generator Objects. A generator function is the same as a normal function, but whenever it needs to generate a value it uses the 'yield' keyword rather than 'return'. The 'yield' keyword halts the function execution and sends a value back to the caller. It has an ability that it can resume the functionality from where it is left off. 
function* generator(){
   yeild 1;
   yeild 2;
}
In the following example, using a generator function, natural numbers 10,9 and 8 were printed. Instead of printing each number individually we can run a for loop and print whatever numbers we need.  
Live Demo
<html>
<body>
<script>
   function * number() {
      var num = 10;
      while (true) {
         yield num--;
      }
   }
   var gen = number();
   document.write(gen.next().value);
   document.write("</br>");
   document.write(gen.next().value);
   document.write("</br>");
   document.write(gen.next().value);
</script>
</body>
</html>
10
9
8
Java Program to Find the Area of Trapezium - GeeksforGeeks

22 Dec, 2020
A trapezium is a convex quadrilateral, which has only two parallel sides and the other two sides are non-parallel. The non-parallel sides of the trapezium are referred to as its legs while the parallel sides are called the bases. It is also called a trapezoid. A parallelogram is also often referred to as a trapezoid with two parallel sides.
In the figure below, AB and DC are parallel to each other while AD and BC are the non-parallel sides. ‘h’ is also the distance that indicates the height of the trapezium between the two parallel sides.
Area of trapezium:
Area = 1/2*(sum of parallel sides)*height of the trapezium
Example:
Input : base1 = 3, base2 = 4, height = 6
Output: area = 21

Input : base1 = 5, base2 = 7, height = 3 
Output: area = 18
Approach:
Take three input as two bases of the trapezium and height.Apply the area of the trapezium formula to calculate the area.Print the area.
Take three input as two bases of the trapezium and height.
Apply the area of the trapezium formula to calculate the area.
Print the area.
Below is the implementation of the above approach:
Java
// Java Program to Find the Area of Trapezium  import java.io.*;  class GFG {    public static void main(String[] args)    {        double base_1 = 10.00;          double base_2 = 20.00;          double height = 50.00;          // formula for calculating the area        double area_of_trapezium            = ((base_1 + base_2) * height) / 2;          // printing the area        System.out.println("Area of trapezium:"                           + area_of_trapezium);    }}
Area of trapezium:750.0
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
Convert a String to Character array in Java
Java Programming Examples
How to Iterate HashMap in Java?
Implementing a Linked List in Java using Class
Min Heap in Java
Live Reloading with Browser Sync

Live Reload specifies the changes in the file system. The BrowserSync is used to watch all HTML and CSS files in the css directory and performs the live reload to the page in all browsers whenever files were changed. BrowserSync makes workflow faster by synchronizing URL's, interactions and code changes across multiple devices.
The BrowserSync plugin gives you cross browser CSS injecting and can be installed by using below command:
npm install browser-sync --save-dev
To use BrowserSync plugin, you need to write dependency in your configuration file as shown below:


var browserSync = require('browser-sync').create();
You need to create task for BrowserSync to work with server using Gulp. Since you are running server, so you need to tel BrowserSync about the root of your server. Here, we are using base directory as 'build'.
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: 'build'
    },
  })
})
You can also inject new styles into the browser by using below task for CSS file:
gulp.task('styles', function() {
  gulp.src(['src/styles/*.css'])
    .pipe(concat('style.css'))
    .pipe(autoprefix('last 2 versions'))
    .pipe(minifyCSS())
    .pipe(gulp.dest('build/styles/'))
    .pipe(browserSync.reload({
       stream: true
    }))
});
Before creating task for BrowserSync, you need to install the plugins using package manager and write dependencies in your configuration file as defined in this chapter.
When you are done with configuration, run the both browserSync and watch tasks for the occurrence of live reloading effect. Instead of running two command lines separately, we will run them together by adding browserSync task along with the watch task as shown below:
gulp.task('default', ['browserSync', 'styles'], function (){
  gulp.watch('src/styles/*.css', ['styles']);
});
Just run the following command in your project directory to execute the above combined tasks:
gulp
After running the task by using the above command, you will get to see below result in the command prompt: 
C:\project>gulp
[13:01:39] Using gulpfile C:\project\gulpfile.js
[13:01:39] Starting 'browserSync'...
[13:01:39] Finished 'browserSync' after 20 ms
[13:01:39] Starting 'styles'...
[13:01:39] Finished 'styles' after 21 ms
[13:01:39] Starting 'default'...
[13:01:39] Finished 'default' after 15 ms
[BS] 1 file changed (style.css)
[BS] Access URLs:
 ------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.4:3000
 ------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.1.4:3001
 ------------------------------------
[BS] Serving files from: build
It will open the browser window with the URL http://localhost:3000/. Any changes made to the CSS file, will reflect in the command prompt and browser reloads automatically with the changed styles.
 Print
 Add Notes
 Bookmark this page
How to check if event exists on element in jQuery?

To check if event exists on element in jQuery, check for the existing events on the element. 
Here, I have set the div −
<div id="demo">
  This is demo text. Click here!
</div>
When you click div, then the alert generates which I have set using the div id:
$("#demo").click(function() {
  alert("Does event exists? - "+hasEvents);
});
You can try to run the following code to check if event exists −
Live Demo
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#demo").click(function() {
        alert("Does event exists? - "+hasEvents);
     });
     var events = $._data(document.getElementById('demo'), "events");
     var hasEvents = (events != null);
   });
   </script>
  </head>
<body>
  <div id="demo">This is demo text. Click here!</div>
</body>
</html>
EnumSet allof() Method in Java - GeeksforGeeks

02 Jul, 2018
The Java.util.EnumSet.allOf(Class elementType) in Java is used to create an enum set that will be used to contain all of the elements in the specified elementType.
Syntax:
public static > EnumSet allOf(Class elementType)
Parameters: The method accepts one parameter elementType of element type and refers to the class object whose elements are to be stored into the set.
Return Value: The method does not return any value.
Exceptions: The method throws NullPointerException if the elementType is Null.
Below programs illustrate the working of Java.util.EnumSet.allOf() method:Program 1:
// Java program to demonstrate allof() methodimport java.util.*;  // Creating an enum of GFG typeenum GFG {    Welcome,    To,    The,    World,    of,    Geeks};  public class Enum_Set_Demo {      public static void main(String[] args)    {        // Creating an empty EnumSet        EnumSet<GFG> e_set = null;          // Displaying the empty EnumSet        System.out.println(e_set);          // Getting all elements from GFG        e_set = EnumSet.allOf(GFG.class);          // Displaying the final set        System.out.println("The updated set is:" + e_set);    }}
null
The updated set is:[Welcome, To, The, World, of, Geeks]

Program 2:
// Java program to demonstrate allof() methodimport java.util.*;  // Creating an enum of CARS typeenum CARS {    RANGE_ROVER,    MUSTANG,    CAMARO,    AUDI,    BMW};  public class Enum_Set_Demo {      public static void main(String[] args)    {        // Creating an empty EnumSet        EnumSet<CARS> e_set = null;          // Displaying the empty EnumSet        System.out.println(e_set);          // Getting all elements from CARS        e_set = EnumSet.allOf(CARS.class);          // Displaying the final set        System.out.println("The updated set is:" + e_set);    }}
null
The updated set is:[RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW]

java-EnumSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java
C# Program to Sort Student Names in Descending Order using LINQ - GeeksforGeeks

29 Dec, 2021
Given a list of student names, now our task is to sort the names given in the list in descending order using the LINQ, This task can be done using OrderByDescending() method of LINQ. This method is used to sort the elements in the collection in descending order. While using this method in the LINQ query you don’t need to add an extra condition to sort the list in descending order.
Example:
Input  : [ "sai", "narendra", "Mohan", "sundar", "vasu" ]
Output : [ "vasu", "sundar", "sai", "narendra", "mohan" ]

Input  : [ "akhil", "amrutha", "yeswanth", "praveen" ]
Output : [ "yeswanth", "praveen", "amrutha", "akhil" ]
Approach
Create and initialize a list of strudent names of type string. For example arr.
Sorting the list(named arr) using OrderByDescending() method.
var finalres = arr.OrderByDescending(n => n);
Display the result using the foreach loop.
C#
// C# program to sort student names in// descending order using Linq.using System;using System.Linq;using System.Collections.Generic; class GFG{     static void Main(string[] args){         // Creating and initializing list    List<string> students = new List<string>(){ "akhil", "amrutha",                                                "yeswanth", "praveen" };                                                      // Sorting the student names in descending order    var result = students.OrderByDescending(n => n);         // Display the sorted list    Console.Write("Sorted list in Descending order:\n");    foreach (string student in result)    {        Console.Write(student + " ");    }}}
Sorted list in Descending order:
yeswanth praveen amrutha akhil 
rkbhola5
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to find absolute value of a given number
jQuery - Set Attribute Properties

The attr( properties) method set a key/value object as properties to all matched elements.
Here is the simple syntax to use this method −
selector.attr({property1:value1, property2:value2})

Here is the description of all the parameters used by this method −
property − This is the CSS property of the matched element.
property − This is the CSS property of the matched element.
value − This is the value of the property to be set.
value − This is the value of the property to be set.
Following example would change the properties of an image tag −
<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("img").attr({ 
               src: "/images/jquery.jpg",
               title: "jQuery",
               alt: "jQuery Logo"
            });
         });
      </script>	
   </head>
	
   <body>
      <div class = "division" id = "divid">
         <p>Following is the logo of jQuery</p>
         <img src="/jquery/images/jquery-mini-logo.jpg" title="None" alt="None" />
      </div>
   </body>
</html>
This will produce following result −
Following is the logo of jQuery

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
F# - for...to and for...downto

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for...to loop in F# programming language is −
for var = start-expr to end-expr do
   ... // loop body

The syntax of a for...downto loop in F# programming language is −
for var = start-expr downto end-expr do
   ... // loop body

The following program prints out the numbers 1 - 20 −
let main() =
   for i = 1 to 20 do
      printfn "i: %i" i
main()
When you compile and execute the program, it yields the following output −
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10
i: 11
i: 12
i: 13
i: 14
i: 15
i: 16
i: 17
i: 18
i: 19
i: 20

The following program counts in reverse and prints out the numbers 20 - 1 −
let main() =
   for i = 20 downto 1 do
      printfn "i: %i" i
main()
When you compile and execute the program, it yields the following output −
i: 20
i: 19
i: 18
i: 17
i: 16
i: 15
i: 14
i: 13
i: 12
i: 11
i: 10
i: 9
i: 8
i: 7
i: 6
i: 5
i: 4
i: 3
i: 2
i: 1

 Print
 Add Notes
 Bookmark this page
LEX program to add line numbers to a given file

30 Apr, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt.Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Prerequisite: Flex (Fast lexical Analyzer Generator)
Example:
Input:
#include<stdio.h>
// Driver Code
int main()
{
int a; 
/* we have to delete comments */
return 0;
}

Output:
1 #include<stdio.h>
2 // Driver Code
3 int main()
4 {
5 int a; 
6 /* we have to delete comments */
7 return 0;
8 }

Approach:A new line is encountered because of the /n. To count the number of lines, count the number of /n occurred with initial value as 1 as there exists an initial single line. All the other things can be ignored as focus is on number of /n. Take a counter initially set to 1 and increment it whenever a new line (/n) occurs.
Input File: testtest.c
Below is the implementation to add line numbers to a given file.
/* Program to add line numbers to a given file*/%{int line_number = 1;  // initializing line number to 1%}  /* simple name definitions to simplifythe scanner specification name definition of line*/line .*\n      %%{line} { printf("%10d %s", line_number++, yytext); }    /* whenever a line is encountered increment count*/   /* 10 specifies the padding from left side to                     present the line numbers*/    /* yytext The text of the matched pattern is stored                           in this variable (char*)*/%%  int yywrap(){}   int main(int argc, char*argv[]){extern FILE *yyin;    // yyin as pointer of File type  yyin = fopen("testtest.c","r");  /* yyin points to the file                                    testtest.c and opens it                                   in read mode.*/  yylex();   // The function that starts the analysis.  return 0;}
Output:
Lex program
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
How to create a dialog with “yes” and “no” options in JavaScript?

No, you cannot create a dialog box with “yes” or “no”. A confirmation dialog box in JavaScript has “Ok” and “Cancel” button.
To create a dialog with “yes” or “nor”, use a custom dialog box.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         function functionConfirm(msg, myYes, myNo) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes,.no").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.find(".no").click(myNo);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #91FF00;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 80px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message"></div>
         <button class="yes">Yes</button>
         <button class="no">No</button>
      </div>
      <button onclick = 'functionConfirm("Do you like Football?", function yes() {
         alert("Yes")
      },
      function no() {
         alert("no")
      });'>submit</button>
   </body>
</html>
Click here to download the project code
How to move an array element from one array position to another in Java?

To move an element from one position to other (swap) you need to –
Create a temp variable and assign the value of the original position to it.
Now, assign the value in the new position to original position.
Finally, assign the value in the temp to the new position.
Live Demo
import java.util.Arrays;

public class ChangingPositions {
   public static void main(String args[]) {
      int originalPosition = 1;
      int newPosition = 4;
      int [] myArray = {23, 93, 56, 92, 39};
      int temp = myArray[originalPosition];
      myArray[originalPosition] = myArray[newPosition];
      myArray[newPosition] = temp;
      System.out.println(Arrays.toString(myArray));
   }
}
[23, 39, 56, 92, 93]
Matplotlib.pyplot.savefig() in Python

26 May, 2020
Matplotlib is highly useful visualization library in Python. It is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Visualization plays a very important role as it helps us to understand huge chunks of data and extract knowledge.
As the name suggests savefig() method is used to save the figure created after plotting data. The figure created can be saved to our local machines by using this method.
Syntax: savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
Parameters:
Example 1:
# importing required modules import matplotlib.pyplot as plt  # creating plotting dataxaxis =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]yaxis =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # plotting plt.plot(xaxis, yaxis)plt.xlabel("X")plt.ylabel("Y")  # saving the file.Make sure you # use savefig() before show().plt.savefig("squares.png")  plt.show()
Output :
Example 2:
# importing the modules import matplotlib.pyplot as plt    # creating data and plotting a histogramx =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]plt.hist(x)  # saving the figure.plt.savefig("squares1.png",            bbox_inches ="tight",            pad_inches = 1,            transparent = True,            facecolor ="g",            edgecolor ='w',            orientation ='landscape')  plt.show()
Output :
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
Python | Pandas Series.dt.freq

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.freq attribute return the time series frequency applied on the given series object if any, else it return None.
Syntax: Series.dt.freq
Parameter : None
Returns : frequency
Example #1: Use Series.dt.freq attribute to find the frequency of the underlying datetime based data in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30',               '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.freq attribute to find the frequency of the datetime based data in the given series object.
# find the frequencyresult = sr.dt.freq  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.freq attribute has returned None indicating the frequency for the given datetime data is not known.
Example #2 : Use Series.dt.freq attribute to find the frequency of the underlying datetime based data in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D',                            tz = 'US / Central'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.freq attribute to find the frequency of the datetime based data in the given series object.
# find the frequencyresult = sr.dt.freq  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.freq attribute has successfully returned the frequency of the underlying datetime based data in the given Series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
Introduction To PYTHON