code-rag-bench/online-tutorials huggingface dataset:
Ignore Outliers in ggplot2 Boxplot in R

30 Jun, 2021
In this article, we will understand how we can ignore or remove outliers in ggplot2 Boxplot in R programming language.
Removing/ ignoring outliers is generally not a good idea because highlighting outliers is generally one of the advantages of using box plots. However, sometimes extreme outliers, on the other hand, can alter the size and obscure other characteristics of a box plot, therefore it’s best to leave them out in those circumstances. We can remove outliers in R by setting the outlier.shape argument to NA. In addition, the coord_cartesian() function will be used to reject all outliers that exceed or below a given quartile. The y-axis of ggplot2 is not automatically adjusted. You can adjust the axis by using the coord_cartesian() function.
For creating Boxplot with outliers we require two functions one is ggplot() and the other is geom_boxplot()
Dataset Used: Crop_recommendation
Let us first create a regular boxplot, without removing any outliers so that the difference becomes apparent.
Example:
R
# Loadinglibrary(ggplot2)  # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE)ds  # create a boxplot by using geom_boxplot() # function of ggplot2 package with outliersbox_plot_crop<-ggplot(data=ds, aes( y=rainfall))  box_plot_crop+geom_boxplot()
Output:
 
Now, for removing the outliers, you can use the outlier.shape to NA argument.
Syntax:
geom_boxplot(outlier.shape = NA)
You can change the axis directly with the coord_cartesian() function since ggplot2 does not automatically adjust the axes. In the coord_catesian() you can set the limit of the axes by using the argument ylim or xlim.
Syntax:
coord_cartesian( xlim = NULL, ylim = NULL, expand = TRUE, default = FALSE, clip = “on )
Parameters:
xlim, ylim-> set the limits of x and y-axis and also allows zooming in and zoom out.
expand–  It is TRUE by default, and if it is TRUE then it increases the limit by a small amount to ensure that data and axes do not overlap. and if it is FALSE then the limit is taken from the exact data or the xlim/ ylim.
default–  used for checking is this is the default coordinate system 
clip- It checks Should the drawing be cropped to fit the plot panel
Example:
R
# Loadinglibrary(ggplot2)  # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE)ds  # remove outliers or create boxplot without outliersbox_plot_crop<-ggplot(data=ds, aes(y = rainfall)) box_plot_crop+ geom_boxplot(outlier.shape = NA) +  coord_cartesian(ylim =  c(50, 300))
Output: 
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python program to print all the common elements of two lists.

Given two lists, print all the common element of two lists.
Input : L1 = [5, 6, 7, 8, 9] 
        L2 = [5, 13, 34, 22, 90]
Output : {5}

The common elements of both the list is 5.
Step1 : create two user input lists.
Step2 : Convert the lists to sets and then print set1&set2.
Step3 : set1 and set2 returns the common elements set, where set1 is the list1 and set2 is the list2.

# Python program to find the common elements  
# in two lists 
def commonelemnets(a, b): 
   seta = set(a) 
   setb = set(b) 
   if (seta & setb): 
      print("Common Element ::>",seta & setb) 
   else: 
      print("No common elements")  
              
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k) 
B=list()
n=int(input("Enter the size of the Second List ::"))
print("Enter the Element of Second List ::")
for i in range(int(n)):
   k=int(input(""))
   B.append(k) 
commonelemnets(A,B)
Enter the size of the First List :: 4
Enter the Element of First List ::
4
5
6
7
Enter the size of the Second List :: 4
Enter the Element of Second List ::
1
2
3
4
Common Element ::> {4}
Enter the size of the First List :: 4
Enter the Element of First List ::
1
2
3
4
Enter the size of the Second List :: 4
Enter the Element of Second List ::
5
6
7
8
No common elements
HTTP headers | X-Forwarded-Proto

07 Nov, 2020
The HTTP headers are used to communicate between client and server. HTTP headers let the client and server pass additional information with an HTTP request or response. X-Forwarded-Proto (XPF) header is used to identifying the protocol that the client used to connect with a proxy or load balancer. It can be HTTP or HTTPS. Your server access log usually contains information about the protocol used between server and load balancer, but it does not contain any information about the protocol used between the client and load balancer. To get information about which protocol used between client and load balancer, we can use the X-Forwarded-Proto request header. Using this header, the client can make an HTTP request to an HTTPS-only resource.
Syntax:  
X-Forwarded-Proto: <protocol>


Directives:  
<protocol>: This contains an X-Forwarded-Proto request header for a request that originated from the client(http or https).
Example 1: The following example contains an X-Forwarded-Proto request header for a request that originated from the client as an HTTP request: 
HTML
// X-Forwarded-Proto: originatingprotocolX-Forwarded-Proto: http
Example 2: The following example contains an X-Forwarded-Proto request header for a request that originated from the client as an HTTPS request:  
HTML
// X-Forwarded-Proto: originatingprotocolX-Forwarded-Proto: https
Example 3: This example is for other non-standard form.  
HTML
# MicrosoftFront-End-Https: on X-Forwarded-Protocol: httpX-Forwarded-Ssl: onX-Url-Scheme: http
Note: This HTTP headers X-Forwarded-Proto is useful when you want to keep a record of the protocol client and load balancer.  
Supported Browsers: Compatibility for the HTTP headers X-Forwarded-Proto for the browsers still unknown. 
Vijay Sirra
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert matrix rows into a list in R?

Depending on our objective, a matrix rows might be needed to converted into a list that means each row will be an element of the list. This can be done by using the function as.list but firstly we need to convert the matrix into data frame after transposing. For example, if we have a matrix called M then it’s rows will be converted to a list using the command writtem below −
as.list(data.frame(t(M)))
 Live Demo
M1<−matrix(1:25,nrow=5)
M1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11   16   21
[2,] 2    7   12   17   22
[3,] 3    8   13   18   23
[4,] 4    9   14   19   24
[5,] 5   10   15   20   25
as.list(data.frame(t(M1)))
$X1
[1] 1 6 11 16 21
$X2
[1] 2 7 12 17 22
$X3
[1] 3 8 13 18 23
$X4
[1] 4 9 14 19 24
$X5
[1] 5 10 15 20 25
 Live Demo
M2<−matrix(rnorm(36),nrow=6)
M2
       [,1]       [,2]      [,3]        [,4]        [,5]         [,6]
[1,] 1.320181 0.17152409 −1.76634091 −0.48085533   −1.6186915   −1.4374249
[2,] −0.220481 −0.31776877 −2.16503900 −1.04481201 −1.2440593   −0.5943860
[3,] −0.138843 1.24491033 −0.23453374 0.09363227   0.1624981    −2.2085699
[4,] −0.535679 1.05556228 1.27692225 −1.00761472   −0.6388036    0.2438138
[5,] 1.563999 −0.08637959 −0.10161734 −3.03514376  −0.2729878 −0.4657192
[6,] 1.252191 2.09451091 −0.04484482 −0.96138526   1.2211188    −0.5685082
as.list(data.frame(t(M2)))
$X1
[1] 1.3201811 0.1715241 −1.7663409 −0.4808553 −1.6186915 −1.4374249
$X2
[1] −0.2204810 −0.3177688 −2.1650390 −1.0448120 −1.2440593 −0.5943860
$X3
[1] −0.13884303 1.24491033 −0.23453374 0.09363227 0.16249808 −2.20856995
$X4
[1] −0.5356790 1.0555623 1.2769222 −1.0076147 −0.6388036 0.2438138
$X5
[1] 1.56399912 −0.08637959 −0.10161734 −3.03514376 −0.27298782 −0.46571917
$X6
[1] 1.25219067 2.09451091 −0.04484482 −0.96138526 1.22111884 −0.56850819
 Live Demo
M3<−matrix(rpois(16,2),ncol=4)
M3
   [,1] [,2] [,3] [,4]
[1,] 1    2    2    2
[2,] 0    5    1    3
[3,] 1    4    3    1   
[4,] 0    1    4    2
as.list(data.frame(t(M3)))
$X1
[1] 1 2 2 2
$X2
[1] 0 5 1 3
$X3
[1] 1 4 3 1
$X4
[1] 0 1 4 2
 Live Demo
M4<−matrix(runif(25,2,10),nrow=5)
M4
        [,1]     [,2]     [,3]     [,4]    [,5]
[1,] 9.470178 3.844069 3.126983 7.666309 8.801446
[2,] 4.517685 6.602599 6.353498 9.570915 2.854464
[3,] 5.104221 5.793673 4.875067 6.810684 2.926270
[4,] 2.694206 4.677686 8.749031 6.201677 4.149385
[5,] 2.085755 9.849269 9.084727 3.010815 7.153298
as.list(data.frame(t(M4)))
$X1
[1] 9.470178 3.844069 3.126983 7.666309 8.801446
$X2
[1] 4.517685 6.602599 6.353498 9.570915 2.854464
$X3
[1] 5.104221 5.793673 4.875067 6.810684 2.926270
$X4
[1] 2.694206 4.677686 8.749031 6.201677 4.149385
$X5
[1] 2.085755 9.849269 9.084727 3.010815 7.153298
 Live Demo
M5<−matrix(rexp(16),nrow=4)
M5
       [,1]      [,2]       [,3]    [,4]
[1,] 1.4500225 1.2780952 3.8074267 0.5150933
[2,] 0.6914497 3.0919047 4.9547217 1.5925355
[3,] 0.6407890 0.1222374 1.3573294 1.1416469
[4,] 1.0918338 1.1835358 0.8053099 0.2225276
as.list(data.frame(t(M5)))
$X1
[1] 1.4500225 1.2780952 3.8074267 0.5150933
$X2
[1] 0.6914497 3.0919047 4.9547217 1.5925355
$X3
[1] 0.6407890 0.1222374 1.3573294 1.1416469
$X4
[1] 1.0918338 1.1835358 0.8053099 0.2225276
Java Program to calculate the area of a triangle using Heron's Formula

Heron’s formula gives the area of a triangle when the length of all three sides are already known.
Let’s say we have the following three sides of a triangle −
s1 = 15191235.0;
s2 = 15191235.0;
s3 = 1.01235479;
Now, use the Heron’s formulae to find the area −
area = (s1+s2+s3)/2.0d;
resArea = Math.sqrt(area* (area - s1) * (area - s2) * (area - s3));
 Live Demo
public class Demo {
   public static void main(String[] args) {
      // sides of a triangle
      double s1, s2, s3;
      double area, resArea;
      // three sides of a triangle
      s1 = 15191235.0;
      s2 = 15191235.0;
      s3 = 1.01235479;
      area = (s1+s2+s3)/2.0d;
      resArea = Math.sqrt(area* (area - s1) * (area - s2) * (area - s3));
      System.out.println("Area of Triangle = " + resArea);
   }
}
Area of Triangle = 7689459.767977145
How to find minimum value in MongoDB?

To find the minimum value in MongoDB, you can use sort() along with limit(1). The syntax is as follows −
db.yourCollectionName.find().sort({yourFieldName: 1}).limit(1);
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findMinValueDemo.insertOne({"StudentMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80ea2f684a30fbdfd59f")
}
> db.findMinValueDemo.insertOne({"StudentMarks":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f02f684a30fbdfd5a0")
}
> db.findMinValueDemo.insertOne({"StudentMarks":79});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f32f684a30fbdfd5a1")
}
> db.findMinValueDemo.insertOne({"StudentMarks":59});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f82f684a30fbdfd5a2")
}
> db.findMinValueDemo.insertOne({"StudentMarks":91});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80fb2f684a30fbdfd5a3")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findMinValueDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8f80ea2f684a30fbdfd59f"), "StudentMarks" : 78 }
{ "_id" : ObjectId("5c8f80f02f684a30fbdfd5a0"), "StudentMarks" : 69 }
{ "_id" : ObjectId("5c8f80f32f684a30fbdfd5a1"), "StudentMarks" : 79 }
{ "_id" : ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks" : 59 }
{ "_id" : ObjectId("5c8f80fb2f684a30fbdfd5a3"), "StudentMarks" : 91 }
Here is the query to find the minimum value in MongoDB −
> db.findMinValueDemo.find().sort({StudentMarks: 1}).limit(1);
The following is the output −
{ "_id" : ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks" : 59 }
Tryit Editor v3.7

CSS Grid Container
Tryit: Using align-content: space-evenly
Include a header for a document or section in HTML5?

Use the <header> tag in HTML5 to add a header. The HTML <header> tag specifies a header for a document or section.
You can try to run the following code to include a header for a document −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Header Tag</title>
   </head>
   <body>
      <header>
         <h1>Simply Easy Learning</h1>
         <p>You're visiting tutorialspoint.com -
         tutorial hub for simply easy learning.</p>
      </header>
   </body>
</html>
How to remove Duplicate Records except a single record in MySQL?

You can use DELETE command with some condition for this since we need to keep one record and delete rest of the duplicate records.
Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(40)
);
Query OK, 0 rows affected (0.48 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.26 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | John        |
| 2         | Carol       |
| 3         | Sam         |
| 4         | Carol       |
| 5         | David       |
| 6         | Carol       |
+-----------+-------------+
6 rows in set (0.00 sec)
Here is the query to remove duplicate records except a single record −
mysql> delete tbl1 from DemoTable tbl1,DemoTable tbl2
WHERE
tbl1.StudentName = tbl2.StudentName AND tbl1.StudentId > tbl2.StudentId;
Query OK, 2 rows affected (0.79 sec)
The above query deleted 2 rows for “Carol” and left one of the “Carol” record. 
Let us now display the records of table −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | John        |
| 2         | Carol       |
| 3         | Sam         |
| 5         | David       |
+-----------+-------------+
4 rows in set (0.00 sec)
How can I prevent a window from being resized with Tkinter?

Tkinter windows can be resized automatically by hovering and pulling over the window. We can disable the resizable property using the resizable(boolean value) method. We will pass false value to this method which will disable the window to be resized.
#Import the tkinter library
from tkinter import *

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

#Set the geometry
win.geometry("650x250")

Label(win, text= "Hello World", font=('Times New Roman bold',
20)).pack(pady=20)

#Make the window resizable false
win.resizable(False,False)

win.mainloop()
Running the above code will display the following the tkinter window, but you won't be able to resize it.
Java Files

File handling is an important part of any application.
Java has several methods for creating, reading, updating, and 
deleting files.
The File class from the java.io package, allows 
us to work with files.
To use the File class, create an object of 
the class, and specify the filename or directory name: 


import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information 
about files. 
For example:
You will learn how to create, write, read and delete files in the next chapters:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Tryit Editor v3.7

Tryit: Simple text shadow effect
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
12345678910111213141516171819202122232425262728293031323334353637/******************************************************************************                            Online C Compiler.                Code, Compile, Run and Debug C program online.Write your code in this editor and press "Run" button to compile and execute it.*******************************************************************************/#include <stdio.h>#include <stdlib.h>#include<stdbool.h>bool notsame(char* c, int len){    bool a = false;    for(int i=0;i<len-1;++i)    {        if(c[i]!=c[i+1]) a= true;    }        return a;}bool notpresent(int* nums, int ele, int idx){    bool a= true;    for(int i=0;i<idx;i++)    {        if(nums[i]==ele) a=false;    }    return a;}int main(){    int len;    scanf("%d",&len);ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
How can we retrieve file from database using JDBC?

The ResultSet interface provides the methods named getClob() and getCharacterStream() to retrieve Clob datatype, In which the contents of a file are typically stored.
These methods accept an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column.
The difference is the getClob() method returns a Clob object and the getCgaracterStream() method returns a Reader object which holds the contents of the Clob datatype.
Assume we have created a table named Articles in the database with the following description.
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| Name    | varchar(255) | YES  |     | NULL    |       |
| Article | longtext     | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
And, we have inserted three articles in it with names article 1, article 2 and, article 3 as shown below:
Following program retrieves the contents of the table Articles using the getString() and getClob() methods and saves it in the specified files.
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingFileFromDatabase {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating aStatement
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Articles");
      int j = 0;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         Clob clob = rs.getClob("Article");
         Reader reader = clob.getCharacterStream();
         String filePath = "E:\\Data\\clob_output"+j+".txt";
         FileWriter writer = new FileWriter(filePath);
         int i;
         while ((i = reader.read())!=-1) {
            writer.write(i);
         }
         writer.close();
         System.out.println(filePath);
         j++;
      }
   }
}
Connection established......
Contents of the table are:
article1
E:\Data\clob_output0.txt
article2
E:\Data\clob_output1.txt
article3
E:\Data\clob_output2.txt
Python - Replace negative values with latest preceding positive value in Pandas DataFrame

We want to replace the negative values with latest preceding positive value. With that, if there’s no positive preceding value, then the value should update to 0.
For example, the input is −
DataFrame:  
One  two
0  -2   -3
1   4   -7
2   6    5
3   0   -9
The output should be −
   One two
0   0   0
1   7   0
2   4   2
3   0   2
Data Frame masking is used to replace negative values. To fill the missing values, we used forward fill. At first, let us create pandas dataframe −
# create pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0], 'two': [-6, -1, 2, -8]})
Let us perform masking −
df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')
Following is the code −
import pandas as pd

# create pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0],'two': [-6, -1, 2, -8]})

# displaying the DataFrame
print"DataFrame: \n",df

# masking
df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')

# displaying the updated DataFrame
print"\nUpdated DataFrame: \n",df
This will produce the following output −
DataFrame:
   One   two
0   -3   -6
1    7   -1
2    4    2
3    0   -8
Updated DataFrame:
   One   two
0    0    0
1    7    0
2    4    2
3    0    2
Tryit Editor v3.7

Tryit: HTML picture element
How to use string.Empty or String.Empty to initialize a string in C#?

Set the string as empty using the string.Empty in C# −
string myStr = string.Empty;
To check whether it is a string or not, use the IsNullOrEmpty() method −
if (string.IsNullOrEmpty(myStr)) {
   Console.WriteLine("String is empty or null!");
}
The following is an example −
 Live Demo
using System;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         string myStr = string.Empty;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         } else {
            Console.WriteLine("String isn't empty or null!");
         }
      }
   }
}
String is empty or null!
Java 8 - Nashorn JavaScript

With Java 8, Nashorn, a much improved javascript engine is introduced, to replace the existing Rhino. Nashorn provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invoke dynamics feature, introduced in Java 7 to improve performance.
For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console.
Create and save the file sample.js in c:\> JAVA folder.
print('Hello World!');
Open console and use the following command.
C:\JAVA>jjs sample.js

It will produce the following output:
Hello World!

Open the console and use the following command.
C:\JAVA>jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>

Open the console and use the following command.
C:\JAVA> jjs -- a b c
jjs> print('letters: ' +arguments.join(", "))
letters: a, b, c
jjs>

Using ScriptEngineManager, JavaScript code can be called and interpreted in Java.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Java8Tester {

   public static void main(String args[]) {
      ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
      ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
		
      String name = "Mahesh";
      Integer result = null;
      
      try {
         nashorn.eval("print('" + name + "')");
         result = (Integer) nashorn.eval("10 + 2");
         
      } catch(ScriptException e) {
         System.out.println("Error executing script: "+ e.getMessage());
      }
      System.out.println(result.toString());
   }
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester

It should produce the following result −
Mahesh
12

The following example explains how to import and use Java classes in java script.
Create and save sample.js in c:\> JAVA folder.
var BigDecimal = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

   var result = new BigDecimal(amount).multiply(new BigDecimal(percentage)).divide(
      new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
   
   return result.toPlainString();
}
var result = calculate(568000000000000000023,13.9);
print(result);
Open the console and use the following command.
C:\JAVA>jjs sample.js

It should produce the following output −
78952000000000000003.20


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Decimal.Truncate() Method in C# - GeeksforGeeks

17 Feb, 2019
This method is used to get the integral digits of the specified Decimal by discarding any fractional digits. This method rounds the specified value to the nearest whole number by removing the digits after the decimal point.
Syntax: public static decimal Truncate (decimal d);Here, d is the decimal number which is to be truncated.
Return Value: It returns the result of d rounded toward zero, to the nearest whole number.
Example:
// C# program to demonstrate the// Decimal.Truncate(Decimal) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              // Taking decimal variables            // having fractional part            Decimal dec1 = 214748.78549M;            Decimal dec2 = 21458565.2996m;              // using Decimal.Truncate(Decimal) Method            Decimal val1 = Decimal.Truncate(dec1);              // using Decimal.Truncate(Decimal) Method            Decimal val2 = Decimal.Truncate(dec2);              // Printing the Integral part only            Console.WriteLine("The integral part of "+                                "dec1 is: {0}", val1);              Console.WriteLine("The integral part of "+                                "dec2 is: {0}", val2);        }          catch (OverflowException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The integral part of dec1 is: 214748
The integral part of dec2 is: 21458565

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.truncate?view=netframework-4.7.2
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Delegates
C# | Data Types
How to Color a Pandas DataFrame | by Roman Orac | Towards Data Science

Pandas needs no introduction as it became the de facto tool for Data Analysis in Python. As a Data Scientist, I use pandas daily and it never ceases to amaze me with better ways of achieving my goals.
Another useful feature that I learned recently is how to color a pandas Dataframe.
Here are few links that might interest you:
- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]
Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything.
Let’s create a pandas DataFrame with random numbers:
import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(0, 100, size=(15, 4)), columns=list("ABCD"))
Coloring cells (by frequencies) is as simple as:
df.style.background_gradient(cmap="Blues")
If we increase column B by 1000, it won’t interfere with other column colors.
df["B"] *= 1000
As we see in the image below, maximums of columns A, C, D retained their color.
You can set any colormap supported in matplotlib. Just be careful to select the sequential colormap if your goal is to visualize the frequencies.
A bad example of visualizing frequencies is with a non-sequential colormap (so make sure you use a sequential colormap):
df.style.background_gradient(cmap="Spectral")
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
How To Save And Share your Machine Learning Models (Plus More), All With One File | by Victor Saenger | Towards Data Science

When dealing with Machine Learning models, it is usually recommended that you store them somewhere. At the private sector, you oftentimes train them and store them before production, while in research and for future model tuning it is a good idea to store them locally. I always use the amazing Python module pickle to do so.
I recently discovered a useful trick. You can store not only the model, but entire functions and variables all in the same file! This comes especially handy when you want to share your models with someone else, but you know that said person does not necessarily have all the required modules/functions installed or simply does not have the expertise to do so. They simply want to run the algorithm to see the results in a computer with a basic Python environment.
I will show you how do this simple trick here.
Suppose that in your local computer and for a classification analysis you first load these sklearn and numpy modules:
from sklearn.metrics import accuracy_score, f1_scorefrom sklearn import svmfrom numpy import average
to later test the accuracy of a model with cross validation. In the end, after you finish validating the accuracy of the model, you fit the final model with some data:
sv_t = svm.SVC()sv_t.fit(Features,Classes)
Now comes the interesting, but rather simple part. You can store the trained model plus any functions/modules into one single pickle to later distribute it elsewhere!
With this you can save the trained model sv_t plus for example the average function from numpy and the f1_score function from sklearn modules, all in one file. For this you simply do:
import picklepickle.dump([sv_t,average,f1_score], open('complete_ml.pkl', 'wb' ))
That’s it! The next time you (or someone else) load the pickle file complete_ml.pkl from any computer with:
sv_t,average,f1_score = pickle.load(open('complete_ml.pkl','rb'))
you will have access to the stored trained model as well as any functions and variables you wanted to pack together for future distribution. Why to do this? Well, as I said in the begging, many times you want to share, deploy and distribute your ML pipelines into other computers that might not have all required modules pre-installed. With this trick, the only required module is Pickle, which is part of Python’s standard library.
Hope this simple guide helps you in your ML journey, it made a difference in mine.
Thank you for reading!
How to add form validation for empty input fields with JavaScript?

To add form validation for empty input fields with JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head></head>
<h1>JavaScript empty input field validation example</h1>
<form
name="Form1"
onsubmit="return emptyValidation()"
required>
Name: <input type="text" name="firstName" />
<input type="submit" value="Submit" />
</form>
<h2>Submit the form empty to see the validation performed</h2>
<script>
   function emptyValidation() {
      var formField = document.forms["Form1"]["firstName"].value;
      if (formField == "" || x == null) {
         alert("Name must be filled out");
         return false;
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On submitting the form empty −
visudo - Unix, Linux Command

There is a hard-coded list of editors that visudo will use set
at compile-time that may be overridden via the editor sudoers
Default variable.  This list defaults to the path to vi(1) on
your system, as determined by the configure script.  Normally,
visudo does not honor the VISUAL or EDITOR environment
variables unless they contain an editor in the aforementioned editors
list.  However, if visudo is configured with the --with-enveditor
flag or the env_editor Default variable is set in sudoers,
visudo will use any the editor defines by VISUAL or EDITOR.
Note that this can be a security hole since it allows the user to
execute any program they wish simply by setting VISUAL or EDITOR.


visudo parses the sudoers file after the edit and will
not save the changes if there is a syntax error.  Upon finding
an error, visudo will print a message stating the line number(s)
where the error occurred and the user will receive the
What now? prompt.  At this point the user may enter e
to re-edit the sudoers file, x to exit without
saving the changes, or Q to quit and save changes.  The
Q option should be used with extreme care because if visudo
believes there to be a parse error, so will sudo and no one
will be able to sudo again until the error is fixed.
If e is typed to edit the  sudoers file after a parse error
has been detected, the cursor will be placed on the line where the
error occurred (if the editor supports this feature).




 Todd Miller


See the HISTORY file in the sudo distribution or visit
http://www.sudo.ws/sudo/history.html for more details.


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 we do date and time math in Python?

It is very easy to do date and time maths in Python using timedelta objects. Whenever you want to add or subtract to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the timedelta objects and dates −
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
This will give the output −
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the 2 datetimes.
t1 = datetime.datetime.now()
t2 = datetime.datetime.now()
print(t1 - t2)
print(type(t1 - t2))
This will give the output −
-1 day, 23:59:56.653627
<class 'datetime.timedelta'>
C# Program to display the number of days in a month

Use the DaysInMonth to display the number of days in a month.
Add the year and month as a parameter for the DaysInMonth() method −
DateTime.DaysInMonth(2018, 8);
The following is an example −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      Console.WriteLine("Today = {0}", DateTime.Today);
      int num_days = DateTime.DaysInMonth(2018, 8);
      Console.WriteLine("Days in August: "+num_days);
   }
}
Today = 9/4/2018 12:00:00 AM
Days in August: 31
MySQLi - Regexps

You have seen MySQL pattern matching with LIKE ...%. MySQL supports another type of pattern matching operation based on regular expressions and the REGEXP operator. If you are aware of PHP or PERL, then it's very simple for you to understand because this matching is very similar to those scripting regular expressions.
Following is the table of pattern, which can be used along with REGEXP operator.
Now based on above table, you can device various type of SQL queries to meet your requirements. Here, I'm listing few for your understanding. Consider we have a table called tutorials_inf and it's having a field called name −
Query to find all the names starting with 'sa'
mysql>  SELECT * FROM tutorials_inf WHERE name REGEXP '^sa';

The sample output should be like this −
+----+------+
| id | name |
+----+------+
|  1 | sai  |
+----+------+
1 row in set (0.00 sec)

Query to find all the names ending with 'ai'
mysql> SELECT * FROM tutorials_inf WHERE name REGEXP 'ai$';

The sample output should be like this −
+----+------+
| id | name |
+----+------+
|  1 | sai  |
+----+------+
1 row in set (0.00 sec)

Query to find all the names, which contain 'a'
mysql> SELECT * FROM tutorials_inf WHERE name REGEXP 'a';

The sample output should be like this −
+----+-------+
| id | name  |
+----+-------+
|  1 | sai   |
|  3 | ram   |
|  4 | johar |
+----+-------+
3 rows in set (0.00 sec)

Query to find all the names starting with a vowel
mysql>  SELECT * FROM tutorials_inf WHERE name REGEXP '^[aeiou]';


    14 Lectures 
     1.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to determine the row that have min and max values in an R data frame column?

In data analysis, often we require to determine the minimum and maximum values because these values help us to understand the limits of a column or variable under consideration. This can be done by using which.max for maximum and which.min for minimum with single square brackets to extract the rows.
Consider the below data frame −
 Live Demo
x1<-LETTERS[1:20]
x2<-rpois(20,5)
x3<-rexp(20,2)
x4<-rexp(20,5)
df1<-data.frame(x1,x2,x3,x4)
df1
 x1 x2     x3        x4
1 A 7 0.56888750 0.10767756
2 B 7 0.04138254 0.01507087
3 C 3 0.82145385 0.02568754
4 D 4 0.07945021 0.51976803
5 E 7 0.73930797 0.41403820
6 F 7 0.05651587 0.04107620
7 G 4 0.11206284 0.55322510
8 H 3 0.33525532 0.29126855
9 I 6 0.76841536 0.55258446
10 J 2 0.96441097 0.29656683
11 K 1 0.10678610 0.05482085
12 L 14 0.28394648 0.15006675
13 M 1 0.96666190 0.21007950
14 N 4 1.80137393 0.07231502
15 O 8 0.65978932 0.19218883
16 P 6 0.46538207 0.13262744
17 Q 4 0.15772843 0.31552748
18 R 6 0.07239103 0.38449618
19 S 7 0.46414726 0.04460063
20 T 4 0.12917123 0.76904118
Determining the rows that have maximum and minimum values for a particular column −
df1[which.max(df1$x2),]
   x1 x2     x3       x4
12 L 14 0.2839465 0.1500667
df1[which.min(df1$x2),]
   x1 x2       x3       x4
11 K  1    0.1067861 0.05482085
df1[which.min(df1$x3),]
 x1 x2       x3       x4
2 B 7    0.04138254 0.01507087
df1[which.min(df1$x4),]
  x1 x2     x3        x4
2 B  7  0.04138254 0.01507087
Let’s have a look at another example −
 Live Demo
y1<-sample(1:100,20)
y2<-sample(1:10,20,replace=TRUE)
y3<-sample(20:100,20,replace=TRUE)
y4<-sample(50:100,20,replace=TRUE)
y5<-rpois(20,15)
df2<-data.frame(y1,y2,y3,y4,y5)
df2
   y1 y2 y3 y4 y5
1  20 10 64 81 19
2 100 5  29 61 20
3  93 4  61 68 14
4  84 2  43 76 17
5  94 1  37 81 6
6  41 1 100 76 19
7  8  5 78 79 19
8  39 2 28 53 19
9  74 2 72 73 12
10 81 3 30 77 15
11 63 5 27 52 21
12 82 6 24 95 19
13 11 10 48 89 12
14 2  3 69 55 13
15 19 3 89 85 18
16 77 1 93 91 18
17 13 8 45 97 13
18 31 1 92 79 9
19 30 4 30 97 15
20 22 8 25 59 19
df2[which.min(df2$y1),]
y1 y2 y3 y4 y5
14 2 3 69 55 13
df2[which.min(df2$y2),]
  y1 y2 y3 y4 y5
5 94 1  37 81 6
df2[which.max(df2$y2),]
  y1 y2 y3 y4 y5
1 20 10 64 81 19
df2[which.min(df2$y3),]
   y1 y2 y3 y4 y5
12 82  6 24 95 19
df2[which.min(df2$y5),]
  y1 y2 y3 y4 y5
5 94 1  37 81 6
How to plot a function in R?

Plotting a function in R is not a difficult task. We can do it simply with curve function but if the function is very complex then it inside curve function might be difficult. It totally depends on the understand of the person who wants to plot the function, if he or she is well versed with the function then it won’t take much time, otherwise it becomes tedious.
> curve(exp(x),from=0, to=10)
> curve((x-1)/(x^2),from=0, to=20,ylab="y")
> curve(((exp(x))^2)/(x),from=20, to=100,ylab="y")
What is the difference between na.omit and na.rm in R?

The na.omit performs any calculation by considering the NA values but do not include them in the calculation, on the other hand, na.rm remove the NA values and then perform any calculation. For example, if a vector has one NA and 5 values in total then their sum using na.omit will be calculated by excluding NA and by using na.rm it will be calculated by removing NA.
Consider the below data frame −
 Live Demo
x1<-sample(c(NA,5,2),20,replace=TRUE)
x2<-sample(c(NA,rpois(5,1)),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
   x1  x2
1  5   2
2  2  0
3  5  0
4  5  0
5  5   0
6  2   0
7  2   0
8  NA  0
9  2   NA
10 2   0
11 2   0
12 NA  0
13 2   2
14 NA 0
15 2   2
16 5   0
17 NA  0
18 2   0
19 NA  NA
20 NA  NA
Finding row means using na.rm and na.omit −
rowMeans(df1,na.rm=TRUE)
[1] 3.5 1.0 2.5 2.5 2.5 1.0 1.0 0.0 2.0 1.0 1.0 0.0 2.0 0.0 2.0 2.5 0.0 1.0 NaN
[20] NaN
rowMeans(na.omit(df1))
1 2 3 4 5 6 7 10 11 13 15 16 18
3.5 1.0 2.5 2.5 2.5 1.0 1.0 1.0 1.0 2.0 2.0 2.5 1.0
 Live Demo
y1<-sample(c(NA,rnorm(5)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(5)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
        y1       y2
1   -1.8606647   NA
2   -0.2447069   NA
3   -1.8606647   -0.03428118
4   0.4729139    NA
5   0.4729139    1.37315226
6    NA           -0.03428118
7   -1.8606647   1.37315226
8   -0.2447069   -1.47198479
9   -0.7419227    NA
10  -0.2447069   -1.47198479
11  -0.2447069   -0.22281980
12  -0.7419227   -0.11284788
13  NA          -0.03428118
14  NA          -0.11284788
15  NA           1.37315226
16  NA           -0.03428118
17  -0.4378451  -0.22281980
18  -0.2447069  1.37315226
19  -0.2447069  -0.03428118
20  -0.4378451  -1.47198479
Finding row means using na.rm and na.omit −
rowMeans(df2,na.rm=TRUE)
[1] -1.86066467 -0.24470688 -0.94747292 0.47291388 0.92303307 -0.03428118
[7] -0.24375621 -0.85834583 -0.74192272 -0.85834583 -0.23376334 -0.42738530
[13] -0.03428118 -0.11284788 1.37315226 -0.03428118 -0.33033246 0.56422269
[19] -0.13949403 -0.95491495
rowMeans(na.omit(df2))
       3      5            7         8          10        11        12
-0.9474729 0.9230331 -0.2437562 -0.8583458 -0.8583458 -0.2337633 -0.4273853
      17      18         19        20
-0.3303325 0.5642227 -0.1394940 -0.9549149
Print "Hello World" in C/C++ without using any header file - GeeksforGeeks

02 Jun, 2017
Write a C/C++ program that prints Hello World without including any header file.
Conceptually it’s seems impractical to write a C/C++ program that print Hello World without using a header file of “stdio.h”. Since the declaration of printf() function contains in the “stdio.h” header file.
But we can easily achieve this by taking the advantage of C pre-processor directives. The fact is at the time of compiling a program, the first phase of C preprocessing expands all header files into a single file and after that compiler itself compiles the expanded file. Therefore we just need to extract the declaration of printf() function from header file and use it in our main program like that:-
C language: Just declare the printf() function taken from “stdio.h” header file.//Declare the printf() functionint printf(const char *format, ...);  int main(){  printf( "Hello World" );  return 0;}Output: Hello World
//Declare the printf() functionint printf(const char *format, ...);  int main(){  printf( "Hello World" );  return 0;}
Output: Hello World
C++ language: We can’t directly put the declaration of printf() function as in previous case due to the problem of Name mangling in C++. See this to know more about Name mangling. Therefore we just need to declare the printf() inside extern keyword like that:-//Declare the printf() function inside//extern "C" for C++ compilerextern "C"{int printf(const char *format, ...);}  int main(){  printf( "Hello World" );  return 0;}Output: Hello World
//Declare the printf() function inside//extern "C" for C++ compilerextern "C"{int printf(const char *format, ...);}  int main(){  printf( "Hello World" );  return 0;}
Output: Hello World
See this to know more about all phases of compilation of C program.
This blog is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
c-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
'this' pointer in C++
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
How to set opacity of a text canvas using Fabric.js ? - GeeksforGeeks

04 Sep, 2021
In this article, we are going to see how to set the opacity of a canvas-like text using FabricJS. The canvas means text written is movable, rotatable, resizable and can be stretched. Further, the text itself cannot be edited like a textbox.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the opacity property to set the opacity and render the Canvas on the Text as given in the example below. 
Syntax:  
 fabric.Text(text, opacity: number); 
Parameters: This function accepts two parameters as mentioned above and described below:  
text: It specifies the text to be written.
opacity: It specifies the opacity of our text.
Program: We can use FabricJS to set the opacity of a canvas-like text so that it is faded to half of it’s opacity as given below. 
html
<!DOCTYPE html><html> <head>    <title>        How to set the opacity of a text        canvas using Fabric.js ?    </title>     <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head> <body>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000;">    </canvas>     <script>         // Create a new instance of Canvas        var canvas = new fabric.Canvas("canvas");         // Create a new Text instance        var text = new fabric.Text('GeeksforGeeks', {            opacity: 0.5        });         // Render the text on Canvas        canvas.add(text);    </script></body> </html>
Output: 
sagartomar9927
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?