code-rag-bench/online-tutorials huggingface dataset:
MATLAB - if... end Statement

An if ... end statement consists of an if statement and a boolean expression followed by one or more statements. It is delimited by the end statement.
The syntax of an if statement in MATLAB is −
if <expression>
   % statement(s) will execute if the boolean expression is true 
   <statements>
end

If the expression evaluates to true, then the block of code inside the if statement will be executed. If the expression evaluates to false, then the first set of code after the end statement will be executed.
Create a script file and type the following code −
a = 10;
% check the condition using if statement 
   if a < 20 
   % if condition is true then print the following 
      fprintf('a is less than 20\n' );
   end
fprintf('value of a is : %d\n', a);
When you run the file, it displays the following result −
a is less than 20
value of a is : 10


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Erlang - self

One of the most commonly used BIF, returns the pid of the calling processes.
self()

None
Returns the pid of the calling processes.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~p~n",[self()]).
When we run the above program, we will get the following result.
<0.2.0>

 Print
 Add Notes
 Bookmark this page
How to find duplicate values in a JavaScript array?

To find duplicate values in JavaScript, you can try to run the following code −
Live Demo
<html>    
   <body>              
      <script>  
         function removeDuplicate(arr) {        
            var c;        
            var len = arr.length;        
            var result = [];        
            var obj = {};                
            for (c = 0; c<len; c++)  {            
               obj[arr[c]] = 0;        
            }  
            for (c in obj) {            
               result.push(c);        
            }            
            return result;      
         }              
         var myArr = [10, 20, 30, 40, 10, 40, 70, 80, 70, 90];      
         document.write(removeDuplicate(myArr));  
      </script>          
   </body>
</html>
10,20,30,40,70,80,90
How to create an object from class in Java?

An object is created from a class using the new keyword. There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
public class Sample {
   public static void main(String args[]){
      Sample s = new Sample();
   }
}
Check if the String contains only unicode letters in Java

In order to check if a String has only Unicode letters in Java, we use the isDigit() and charAt() methods with decision-making statements.
The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter. It returns a boolean value, either true or false.
Declaration −The java.lang.Character.isLetter() method is declared as follows −
public static boolean isLetter(int codePoint)
Here, the parameter codePoint represents the character to be checked.
The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.
Declaration −The java.lang.String.charAt() method is declared as follows −
public char charAt(int index)
Let us see a program in Java to check if a String has only Unicode Letters.
public class Example {
   boolean check(String s) {
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is not a letter
         // if it is not a letter ,it will return false
         if ((Character.isLetter(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "@asd"; // returns false due to special character presence
      String s1 = "134s"; // returns false due to presence of digits
      String s2 = "abcd"; // returns true
      String s3= "g c1"; // returns false due to space and digits
      System.out.println("String "+s+" has only unicode letters : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters : "+e.check(s3));
   }
}
String @asd has only unicode letters : false
String 134s has only unicode letters : false
String abcd has only unicode letters : true
String g c1 has only unicode letters : false
HTML DOM getElementsByClassName() method

The HTML DOM getElementsByClassName() method is used for getting the collection of all the elements in the document having a given class name. It returns all the given elements as a NodeList object. You can access any element in the returned object using the index number. This method can be called on any individual element to have its descendant child elements having the given class name.
Following is the syntax for the getElementsByClassName() method −
document.getElementsByClassName(classname)
Here, the classname is of type string indicating the class name of element you want to access. Multiple class names can also be searched by separating them with space.
Let us look at an example of the getElementsByClassName() method −
<!DOCTYPE html>
<html>
<head>
<script>
   function changePara() {
      var p = document.getElementsByClassName("PARA1");
      p[0].innerHTML = "This text has been changed";
      p[1].style.color = "red";
      p[1].style.backgroundColor = "yellow";
   }
</script>
</head>
<body>
<h1>getElementsByClassName() example</h1>
<p class="PARA1">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p class="PARA1"> Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>
This will produce the following output −
On clicking the CHANGE button −
In the above example −
We have created two paragraphs that have classname=”PARA1” associated with them.
<p class="PARA1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>

<p class="PARA1"> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
We have then created a button CHANGE that will execute the changePara() on being clicked by the user −
<button onclick="changePara()">CHANGE</button>
The changePara() method gets both the <p> elements as nodeListObject using the getElementsByClassName() method upon the document object and assigns it to variable p. Using the index numbers we change the text for the first paragraph and apply some styling to the second paragraph −
function changePara() {
   var p = document.getElementsByClassName("PARA1");
   p[0].innerHTML = "This text has been changed";
   p[1].style.color = "red";
   p[1].style.backgroundColor = "yellow";
}
snmptrapd - Unix, Linux Command

Note: the default is to listen on UDP port 162 on all IPv4 interfaces.
Since 162 is a privileged port,
snmptrapd must typically be run as root.


Note that this needs to come before any -Lf options
that it should apply to.


To get a list of compiled modules, run the agent with the arguments
-Dmib_init -H (assuming debugging support has been compiled in).


snmptrapd interprets format strings similarly to
printf(3) .
It understands the following formatting sequences:


In addition to these values, an optional field
width and precision may also be specified , just as in
printf(3) ,
and a flag value. The following flags are supported:


The "use alternate form" flag changes the behavior of various format
string sequences:


To get a message like "14:03 TRAP3.1 from humpty.ucd.edu" you
could use something like this:



snmptrapd -P -F "%02.2h:%02.2j TRAP%w.%q from %A\n"


If you want the same thing but in GMT rather than local time, use



snmptrapd -P -F "%#02.2h:%#02.2j TRAP%w.%q from %A\n"


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How can I get the number of times a specific word appears in a column with MySQL?

For this, you can use COUNT() function. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(100)
   -> );
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(EmployeeName) values('John');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(EmployeeName) values('David');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(EmployeeName) values('Carol');
Query OK, 1 row affected (0.29 sec)

mysql> insert into DemoTable(EmployeeName) values('Bob');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable(EmployeeName) values('Sam');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|          1 | John         |
|          2 | Carol        |
|          3 | David        |
|          4 | Carol        |
|          5 | Carol        |
|          6 | Bob          |
|          7 | Sam          |
+------------+--------------+
7 rows in set (0.00 sec)
Following is the query to get the number of times a specific word appears in MySQL. Here, we are finding the occurrences of Employee “Carol” −
mysql> select EmployeeName,count(EmployeeId) as Occurrence from DemoTable where
EmployeeName='Carol';
This will produce the following output −
+--------------+------------+
| EmployeeName | Occurrence |
+--------------+------------+
| Carol        | 3          |
+--------------+------------+
1 row in set (0.05 sec)
Difference between an id and class in HTML

In Html DOM both id and class are the element selector and are used to identify an element based on the name assign to these parameters.
The following are the important differences between Id and Class.
Id.html
<!DOCTYPE html>
<html>
<head>
<title>
Id demo
</title>
<style>
   #idDemo{
      color:green;
      font-size:25px;
   }
</style>
</head>
<body style="text-align:center">
<h1>Get element by Id</h1>
<p id="idDemo">Demo for Id selector</p>
</body>
</html>
Class.html
<!DOCTYPE html>
<html>
<head>
<title>
Class demo
</title>
<style>
   .classDemo{
      color:orange;
      font-size:25px;
   }
</style>
</head>
<body style="text-align:center">
<h1>Get element by class</h1>
<p class="classDemo">Demo for class selector</p>
</body>
</html>
How to read the pixel value of a single channel image in OpenCV using C++?

Digital images are made of pixels. Using OpenCV, it is easy to read the value of pixels. However, if we want to get the pixel values, we have to handle a single channel separately.
Here we are loading an image in the matrix named 'cimage', and then it converts the image using 'cvtColor(cimage, img, COLOR_BGR2GRAY); ' and store it in the matrix named 'img'.
The following program read the pixel value of an image and shows the values in console window.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
   int x;//Declaring an integer variable to hold values of pixels//
   Mat cimage = imread("colors.jpg");//loading an image//
   Mat img;//Declaring an empty matrix to store converted image//
   cvtColor(cimage, img, COLOR_BGR2GRAY);//Converting loaded image to grayscale image//
   for (int i = 0; i < img.rows; i++)//loop for rows// {
      for (int j = 0; j < img.cols; j++)//loop for columns// {
         x = (int)img.at<uchar>(i, j);//storing value of (i,j) pixel in variable//
         cout << "Value of pixel" << "(" << i << "," << j << ")" << "=" << x << endl;//showing the values in console window//
      }
   }
   imshow("Show", img);//showing the image//
   waitKey();//wait for keystroke from keyboard//
   return 0;
}
Rexx - Update Operation

The UPDATE Operation on any database means to update one or more records, which are already available in the database. The following procedure updates all the records having SEX as 'M'.
in the following example, we increase the AGE of all the males by one year.
/* Main program */ 
Call RxFuncAdd 'SQLLoadFuncs', 'rexxsql', 'SQLLoadFuncs' 
Call SQLLoadFuncs 

if SQLConnect(c1,'testuser','test123','testdb') == 0 then say 'Connect Succedded' 
if SQLCommand(u1,"use testdb") == 0 then say 'Changed database to testdb' 
   sqlstr = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'" 

say SQLCommand(c2,sqlstr)
 Print
 Add Notes
 Bookmark this page
Add class (odd and even) in HTML via JavaScript?

To add class, use nth-child(odd) and nth-child(even). Following is the code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=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>
<section class="subjects">
<article class="subjectName ">MongoDB</article>
<article class="subjectName ">Javascript</article>
<article class="subjectName ">Java</article>
<article class="subjectName ">MySQL</article>
</section>
<style>
   .subjectName:nth-child(odd) {
      color: blue;
   }
   .subjectName:nth-child(even) {
      color: purple;
   }
</style>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
Difference Between System.out.println() and System.err.println() in Java - GeeksforGeeks

03 Nov, 2021
System.out is a PrintStream to which we can write characters.  It outputs the data we write to it on the Command Line Interface console/terminal. It is mostly used for console applications/programs to display the result to the user. It can be also useful in debugging small programs.
Syntax:
System.out.println("Your Text which you want to display");
Example:
Java
// Java program to Demonstrate Use of System.out.println() // Importing required input output classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Print statement        System.out.println("GeeksForGeeks!");    }}
GeeksForGeeks!
Now let us come onto the next concept of System.err which is also very closely related to System.out.System.err is also a print stream. It works the same as System.out. It is mostly used to output error texts. Some programs (like Eclipse) will show the output to System.err in red text, to make it more obvious that it is error text. 
Syntax:
System.err.println("Your Text which you want to display");
Example
Java
// Java Program to Demonstrate Use of System.err.println() // Importing required classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Print statement        System.err.println("GeeksForGeeks!");    }}
Output:
GeeksForGeeks!
Note:
System.err and System.out both are defined in System class as reference variable of PrintStream class as:
public final static PrintStream out = null;
public final static PrintStream err = null;
Both outputs are displayed on the same console, Most of the IDEs differentiate the error output with red color.
We can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.
Now let us finally conclude out the differences between the two which are depicted below in tabular format as follows:
simmytarika5
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
PrintWriter flush() method in Java with Examples - GeeksforGeeks

29 Jan, 2019
The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value.
Syntax:
public void flush()
Parameters: This method do not accepts any parameter.
Return Value: This method do not returns any value. It just flushes the Stream.
Below methods illustrates the working of flush() method:
Program 1:
// Java program to demonstrate// PrintWriter flush() method  import java.io.*;  class GFG {    public static void main(String[] args)    {          // The string to be written in the Writer        String str = "GeeksForGeeks";          try {              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // Write the above string to this writer            // This will put the string in the stream            // till it is printed on the console            writer.write(str);              // Now clear the stream            // using flush() method            writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GeeksForGeeks

Program 2:
// Java program to demonstrate// PrintWriter flush() method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // Write the char to this writer            // This will put the char in the stream            // till it is printed on the console            writer.write(65);              // Now clear the stream            // using flush() method            writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
A

Java-Functions
Java-IO package
Java-PrintWriter
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
How to create a scatterplot with colors of the group of points in R?

A scatterplot is the plot that has one dependent variable plotted on Y-axis and one independent variable plotted on X-axis. Sometimes the pair of dependent and independent variable are grouped with some characteristics, thus, we might want to create the scatterplot with different colors of the group based on characteristics. For this purpose, we can use colour argument in ggplot function.
Consider the below data frame −
set.seed(123)
x <-rpois(10,2)
y <-rpois(10,5)
group <-c("A","B","C","A","A","A","C","B","B","C")
df <-data.frame(x,y,group)
df
x y group
1 1 9 A
2 3 5 B
3 2 6 C
4 4 5 A
5 4 2 A
6 0 8 A
7 2 3 C
8 4 2 B
9 2 4 B
10 2 9 C
Creating a simple scatterplot −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating a scatterplot with color of points based on groups −
ggplot(df,aes(x,y,colour=group))+geom_point()
Python Program for Gnome Sort

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using gnome sort.
1. Firstly we traverse the array from left to right.
2. Now,if the current element is larger or equal to the previous element then we traverse one step ahead
3. otherwise,if the current element is smaller than the previous element then swap these two elements and traverse one step back.
4. Repeat steps given above till we reach the end of the array
Now let’s observe the solution in the implementation below −
 Live Demo
def gnomeSort( arr, n):
   index = 0
   while index < n:
      if index == 0:
         index = index + 1
      if arr[index] >= arr[index - 1]:
         index = index + 1
      else:
         arr[index], arr[index-1] = arr[index-1], arr[index]
         index = index - 1
   return arr
# main
arr = [1,4,2,3,6,5,8,7]
n = len(arr)
arr = gnomeSort(arr, n)
print ("Sorted sequence is:")
for i in arr:
   print (i,end=" ")
Sorted sequence is:
1 2 3 4 5 6 7 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for Gnome Sort
numpy.tril() in Python

09 Mar, 2022
numpy.tril(a, k=0) : Returns copy of array with lower part of the triangle w.r.t kParameters :
a : input array
k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal above main diagonal or vice versa.

Returns :
Lower triangle of a, having same shape and data-type as a.
# Python Programming illustrating# numpy.tril method  import numpy as geek  # string inputa = geek.matrix([[1, 21, 30],                  [63 ,434, 3],                  [54, 54, 56]])  print("Main Diagonal elements : \n", geek.tril(a), "\n")  print("Diagonal above main Diagonal elements : \n", geek.tril(a, 1), "\n\n")  print("Main Diagonal elements : \n", geek.tril(a, -1))
Output :
Main Diagonal elements : 
 [[  1   0   0]
 [ 63 434   0]
 [ 54  54  56]] 

Diagonal above main Diagonal elements : 
 [[  1  21   0]
 [ 63 434   3]
 [ 54  54  56]] 


Main Diagonal elements : 
 [[ 0  0  0]
 [63  0  0]
 [54 54  0]]

References:https://docs.scipy.org/doc/numpy/reference/generated/numpy.tril.html#numpy.trilNote :These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating Tables with PrettyTable Library – Python

18 Aug, 2020
PrettyTable class inside the prettytable library is used to create relational tables in Python. For example, the table below has been created using this library, in Command Prompt on Windows.
Installing the Library:
pip install prettytable 

Let’s create the sample table using the prettytable library in Python.
Creating the Table: Row-Wise
Python3
from prettytable import PrettyTable  # Specify the Column Names while initializing the TablemyTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])  # Add rowsmyTable.add_row(["Leanord", "X", "B", "91.2 %"])myTable.add_row(["Penny", "X", "C", "63.5 %"])myTable.add_row(["Howard", "X", "A", "90.23 %"])myTable.add_row(["Bernadette", "X", "D", "92.7 %"])myTable.add_row(["Sheldon", "X", "A", "98.2 %"])myTable.add_row(["Raj", "X", "B", "88.1 %"])myTable.add_row(["Amy", "X", "B", "95.0 %"])  print(myTable)
  
+--------------+-------+---------+------------+
| Student Name | Class | Section | Percentage |
+--------------+-------+---------+------------+
|   Leanord    |   X   |    B    |   91.2%    |
|    Penny     |   X   |    C    |   63.5%    |
|    Howard    |   X   |    A    |   90.23%   |
|  Bernadette  |   X   |    D    |   92.7%    |
|   Sheldon    |   X   |    A    |   98.2%    |
|     Raj      |   X   |    B    |   88.1%    |
|     Amy      |   X   |    B    |   95.0%    |
+--------------+-------+---------+------------+

 
Creating the Table: Column-Wise
Python3
from prettytable import PrettyTable  columns = ["Student Name", "Class", "Section", "Percentage"]  myTable = PrettyTable()  # Add ColumnsmyTable.add_column(columns[0], ["Leanord", "Penny", "Howard",                       "Bernadette", "Sheldon", "Raj", "Amy"])myTable.add_column(columns[1], ["X", "X", "X", "X", "X", "X", "X"])myTable.add_column(columns[2], ["B", "C", "A", "D", "A", "B", "B"])myTable.add_column(columns[3], ["91.2 %", "63.5 %", "90.23 %", "92.7 %",                                           "98.2 %", "88.1 %", "95.0 %"])  print(myTable)
  
+--------------+-------+---------+------------+
| Student Name | Class | Section | Percentage |
+--------------+-------+---------+------------+
|   Leanord    |   X   |    B    |   91.2%    |
|    Penny     |   X   |    C    |   63.5%    |
|    Howard    |   X   |    A    |   90.23%   |
|  Bernadette  |   X   |    D    |   92.7%    |
|   Sheldon    |   X   |    A    |   98.2%    |
|     Raj      |   X   |    B    |   88.1%    |
|     Amy      |   X   |    B    |   95.0%    |
+--------------+-------+---------+------------+

Deleting Rows
myTable.del_row(0)
This will delete the first row from the table, i.e, the rows follow standard indexing starting from index 0. 
Clearing the Table
myTable.clear_rows()
This will clear the entire table (Only the Column Names would remain).
There are many advanced features associated with these tables, like converting these tables to HTML or converting a CSV to a PrettyTable. Those functions would be covered in a separate article.
Python-PrettyTable
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert string to boolean in PHP?

08 Jan, 2019
Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value.
Examples:
Input  : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); 
Output : true

Input  : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN);
Output : false

Approach using PHP filter_var() Function: The filter_var() function is used to filter a variable with specified filter. This function is used to both validate and sanitize the data.
Syntax:
filter_var( var, filterName, options )
Parameters: This function accepts three parameters as mentioned above and described below:
var: It is the required field. It denotes the variable to filter.
filterName: It is used to specify the ID or name of the filter to use. The default filter is FILTER_DEFAULT. It is optional field.
options: It is used to specify one or more flags/options to use. Check each filter for possible options and flags. It is also optional field.
Return Value: Returns the filtered data on success, or False on failure.
Program:
<?php// PHP program to illustrate the conversion// of String to Boolean value  // The below statement returns the boolean value truevar_dump(filter_var('true', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('1', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('on', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('yes', FILTER_VALIDATE_BOOLEAN));  // The below statement returns the boolean value falsevar_dump(filter_var('false', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('0', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('off', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('no', FILTER_VALIDATE_BOOLEAN));var_dump(filter_var('', FILTER_VALIDATE_BOOLEAN));  ?>
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

PHP-string
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Download file from URL using PHP
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
C program to print employee details using Structure

21 Dec, 2017
In this program, we will read and display details of n employees using Structure. Employee details like Name, age, phone number, salary will be printed.
Method :
Declare variables using Structure

Read details of all employees like employee name, 
age, phone number and salary.

Display all the details of employees
Below is CPP program showing employee details :
// CPP program to print details of employees// using Structure#include <iostream>using namespace std;  struct employee {    string ename;    int age, phn_no;    int salary;};  // Function to display details of all employeesvoid display(struct employee emp[], int n){    cout << "Name\tAge\tPhone Number\tSalary\n";    for (int i = 0; i < n; i++) {        cout << emp[i].ename << "\t" << emp[i].age << "\t"             << emp[i].phn_no << "\t" << emp[i].salary << "\n";    }}  // Driver codeint main(){    int n = 3;    // Array of structure objects    struct employee emp[n];      // Details of employee 1    emp[0].ename = "Chirag";    emp[0].age = 24;    emp[0].phn_no = 1234567788;    emp[0].salary = 20000;      // Details of employee 2    emp[1].ename = "Arnav";    emp[1].age = 31;    emp[1].phn_no = 1234567891;    emp[1].salary = 56000;      // Details of employee 3    emp[2].ename = "Shivam";    emp[2].age = 45;    emp[2].phn_no = 1100661111;    emp[2].salary = 30500;      display(emp, n);      return 0;}
Output :
Name     Age    Phone Number   Salary
Chirag   24     1234567788      20000
Arnav    31     1234567891      56000
Shivam   45     8881101111      30500

cpp-structure
C++ Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axes.Axes.pcolormesh() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.pcolormesh() function in axes module of matplotlib library is also used to create a pseudocolor plot with a non-regular rectangular grid.It is is more specialized than pcolor for the given purpose and thus is faster. It supports Gouraud shading
Syntax: Axes.pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading=’flat’, antialiased=False, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
C : This parameter contains the values in 2D array which are to be color-mapped.
X, Y: These parameter are the coordinates of the quadrilateral corners.
cmap : This parameter is a colormap instance or registered colormap name.
norm : This parameter is the Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors
vmin, vmax : These parameter are optional in nature and they are colorbar range.
alpha : This parameter is a intensity of the color.
snap : This parameter is used to snap the mesh to pixel boundaries.
edgecolors : This parameter is the color of the edges. {‘none’, None, ‘face’, color, color sequence}
shading : This parameter is the fill style. It cabe flat or gouraud.
Returns: This returns the following:
mesh : This returns the matplotlib.collections.QuadMesh
Below examples illustrate the matplotlib.axes.Axes.pcolormesh() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm    Z = np.random.rand(25, 25)    fig, ax0 = plt.subplots()    ax0.pcolormesh(Z)    ax0.set_title('matplotlib.axes.Axes.pcolormesh() Examples')plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm    dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy),                slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 6 + y ** 3) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max()  fig, ax = plt.subplots()    c = ax.pcolormesh(x, y, z, cmap ='Greens', vmin = z_min,                  vmax = z_max)  fig.colorbar(c, ax = ax)ax.set_title('matplotlib.axes.Axes.pcolormesh() Examples')plt.show()
Output:
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to use Modal Component in ReactJS ?

22 Feb, 2021
The modal component provides a solid foundation for creating dialogs, lightboxes, popovers, etc. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Modal Component in ReactJS using the following approach.
Creating React Application And Installing Module.
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React from 'react';import Modal from '@material-ui/core/Modal';  export default function App() {    const [open, setOpen] = React.useState(false);    const handleClose = () => {    setOpen(false);  };      const handleOpen = () => {    setOpen(true);  };      return (    <div style={{ display: 'block', padding: 30 }}>      <h4>How to use Modal Component in ReactJS?</h4>      <button type="button"       onClick={handleOpen}>        Click Me to Open Modal      </button>      <Modal        onClose={handleClose}        open={open}        style={{          position: 'absolute',          border: '2px solid #000',          backgroundColor: 'gray',          boxShadow: '2px solid black',          height:80,          width: 240,          margin: 'auto'        }}      >        <h2>How are you?</h2>      </Modal>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/modal/
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Find Fibonacci Numbers using Recursion

The following is an example of fibonacci series using recursion.
 Live Demo
#include <iostream>
using namespace std;
int fib(int x) {
   if((x==1)||(x==0)) {
      return(x);
   }else {
      return(fib(x-1)+fib(x-2));
   }
}
int main() {
   int x , i=0;
   cout << "Enter the number of terms of series : ";
   cin >> x;
   cout << "\nFibonnaci Series : ";
   while(i < x) {
      cout << " " << fib(i);
      i++;
   }
   return 0;
}
Enter the number of terms of series : 15
Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
In the above program, the actual code is present in the function ‘fib’ as follows −
if((x==1)||(x==0)) {
   return(x);
}else {
   return(fib(x-1)+fib(x-2));
}
In the main() function, a number of terms are entered by the user and fib() is called. The fibonacci series is printed as follows.
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
   cout << " " << fib(i);
   i++;
}
Programs for printing pyramid patterns in Python

Taking advantage of the for loop and range function in python, we can draw a variety of for pyramid structures. The key to the approach is designing the appropriate for loop which will leave both vertical and horizontal space for the position of the symbol we choose for drawing the pyramid structure.
We draw a right angle based pattern.
 Live Demo
def pyramid(p):
   for m in range(0, p):
      for n in range(0, m+1):
         print("* ",end="")
      print("\r")
p = 10
pyramid(p)
Running the above code gives us the following result −
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
We make a 180 degree rotation to the above pattern.
 Live Demo
def pyramid(p):
   X = 2*p - 2
   for m in range(0, p):
      for n in range(0, X):
         print(end=" ")
      X = X - 2
      for n in range(0, m+1):
         print("* ", end="")
      print("\r")
p = 10
pyramid(p)
Running the above code gives us the following result −
                  *
                * *
              * * *
            * * * *
          * * * * *
        * * * * * *
      * * * * * * *
    * * * * * * * *
  * * * * * * * * *
* * * * * * * * * *
In this case we draw a triangle shape of type isosceles. Both the sides of the triangle are of equal length.
 Live Demo
n = 0
r = 12
for m in range(1, r+1):
   for gap in range(1, (r-m)+1):
      print(end=" ")
   while n != (2*m-1):
      print("* ", end="")
      n = n + 1
   n = 0
   print()
Running the above code gives us the following result −
                      *
                    * * *
                  * * * * *
                * * * * * * *
              * * * * * * * * *
            * * * * * * * * * * *
          * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
Now we draw a case of triangle in which all the three sides are equal. Also called equilateral triangle.
 Live Demo
length = 12
k = (2 * length) - 2
for p in range(0, length):
   for n in range(0, k):
      print(end=" ")
   k = k - 1
   for n in range(0, p + 1):
      print("@", end=' ')
   print(" ")
Running the above code gives us the following result −
           @
          @ @
         @ @ @
        @ @ @ @
       @ @ @ @ @
      @ @ @ @ @ @
     @ @ @ @ @ @ @
    @ @ @ @ @ @ @ @
   @ @ @ @ @ @ @ @ @
  @ @ @ @ @ @ @ @ @ @
 @ @ @ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @ @ @ @ @ @
Iterate through the values of HashMap in Java

Use Iterator to iterate through the values of HashMap −
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Now, use Iterator to display each and every value and key −
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
   Map.Entry me = (Map.Entry)i.next();
   System.out.print(me.getKey() + ": ");
   System.out.println(me.getValue());
}
The following is an example to iterate through the values of HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}
Elements in HashMap...
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
C/C++ program to shutdown a system?

Here we will see how we can shut down the system by writing a simple C or C++ code. The shutdown process varies in different OS. If we are Linux user, we can use this terminal command to shut down.
shutdown –P now
If we are using Windows system, we can use this command −
c:\\windows\\system32\\shutdown /i
We will see the code for Linux and Windows
#include<iostream>
using namespace std;
int main() {
   system("shutdown -P now");
}
#include<iostream>
using namespace std;
int main() {
   system("c:\\windows\\system32\\shutdown /i ");
}
How do Python modules work?

Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
When you import a module, say `hello`, the interpreter searches for a file named hello.py in the directory containing the input script and then in the list of directories specified by the environment variable PYTHONPATH.
Create a file called fibonacci.py and enter the following code in it:
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()
def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
Now open your terminal and use cd command to change to the directory containing this file and open the Python shell. Enter the following statements:
>>> import fibonacci
>>> fibonacci.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibonacci.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
You imported the module and used its functions.
How to format JSON string in JavaScript?

To format HSON string in JavaScript, use JSON.stringify() with some parameters. Following is
the code −
var details = {
   studentId: 101,
   studentFirstName: 'David',
   studentLastName: 'Miller',
   studentAge:21,
   subjectDetails: {
      subjectId: 'JavaScript_101',
      subjectName: 'Introduction to JavaScript',
   }
};
console.log("Not Pretty JSON Format=")
console.log(JSON.stringify(details));
console.log("Pretty JSON Format=")
console.log(JSON.stringify(details, null, 3));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo127.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo127.js
Not Pretty JSON Format=
{"studentId":101,"studentFirstName":"David","studentLastName":"Miller","studentAge":21,"subj
ectDetails":{"subjectId":"JavaScript_101","subjectName":"Introduction to JavaScript"}}
Pretty JSON Format={
   "studentId": 101,
   "studentFirstName": "David",
   "studentLastName": "Miller",
   "studentAge": 21,
   "subjectDetails": {
      "subjectId": "JavaScript_101",
      "subjectName": "Introduction to JavaScript"
   }
}
C library function - isdigit()

The C library function int isdigit(int c) checks if the passed character is a decimal digit character.
Decimal digits are (numbers) − 0 1 2 3 4 5 6 7 8 9.
Following is the declaration for isdigit() function.
int isdigit(int c);
c − This is the character to be checked.
c − This is the character to be checked.
This function returns non-zero value if c is a digit, else it returns 0.
The following example shows the usage of isdigit() function.
#include <stdio.h>
#include <ctype.h>

int main () {
   int var1 = 'h';
   int var2 = '2';
    
   if( isdigit(var1) ) {
      printf("var1 = |%c| is a digit\n", var1 );
   } else {
      printf("var1 = |%c| is not a digit\n", var1 );
   }
   
   if( isdigit(var2) ) {
      printf("var2 = |%c| is a digit\n", var2 );
   } else {
      printf("var2 = |%c| is not a digit\n", var2 );
   }
   
   return(0);
}
Let us compile and run the above program, to produce the following result −
var1 = |h| is not a digit
var2 = |2| is a digit


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Calculate Time Difference between Dates in R Programming - difftime() Function - GeeksforGeeks

10 Jun, 2020
difftime() function in R Language is used to calculate time difference between dates in the required units like days, weeks, months, years, etc.
Syntax: difftime(date1, date2, units)
Parameters:date1, date2: Dates to calculate differenceunits: Days, weeks, months, etc.
Example 1:
# R program to find time difference  # Calling difftime() functiondifftime("2020-5-16", "2020-1-15", units = "days")difftime("2020-5-16", "2020-1-15", units = "weeks")
Output:
Time difference of 122 days
Time difference of 17.42857 weeks

Example 2:
# R program to find time difference  # Calling difftime() functiondifftime("2020-5-16", "2020-1-15", units = "hours")difftime("2020-5-16", "2020-1-15", units = "mins")
Output:
Time difference of 2928 hours
Time difference of 175680 mins

R Date-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Display today’s date in Java with SimpleDateFormat

To work with SimpleDateFormat class in Java, import the following package.
import java.text.SimpleDateFormat;
To get the date, use the format() method as shown below. Firstly, set the date format −
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MM/yyyy");
Now, we will get the date −
simpleformat.format(cal.getTime())
The following is the complete example −
 Live Demo
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MM/yyyy");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
   }
}
Today's date = 26/11/2018