code-rag-bench/online-tutorials huggingface dataset:
Sankey Charts with Multiple levels

Following is an example of a SanKey Chart with multiple levels.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a SanKey Chart with multiple levels.
We've used Sankey class to show a Sankey chart with multiple levels.
type = 'Sankey';

app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = '';
   type = 'Sankey';
   data = [
      ["Brazil","Portugal",5],
      ["Brazil","France",1],
      ["Brazil","Spain",1],
      ["Brazil","England",1],
      ["Canada","Portugal",1],
      ["Canada","France",5],
      ["Canada","England",1],
      ["Mexico","Portugal",1], 
      ["Mexico","France",1],
      ["Mexico","Spain",5],
      ["Mexico","England",1], 
      ["USA","Portugal",1], 
      ["USA","France",1],
      ["USA","Spain",1],
      ["USA","England",5],
      ["Portugal","Angola",2], 
      ["Portugal","Senagal",1],
      ["Portugal","Morocco",1],
      ["Portugal","South Africa",3]
   ];
   columnNames = ['From', 'To','Weight'];
   options = {       
   };
   width = 550;
   height = 400;
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Change Gregorian Calendar to SimpleDateFormat in Java - GeeksforGeeks

24 Jan, 2022
Given a date in GregorianCalendar format change it into SimpleDateFormat.Examples: 
Input: Sat Apr 28 13:36:37 UTC 2018
Output: 28-Apr-2018

Input: Wed Apr 03 20:49:45 IST 2019
Output: 03-Apr-2019
Approach: 
Get the Gregorian Date to be converted.Create an object of SimpleDateFormat that will store the converted dateNow change the Gregorian Date into SimpleDateFormat using the format() method.This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method.
Get the Gregorian Date to be converted.
Create an object of SimpleDateFormat that will store the converted date
Now change the Gregorian Date into SimpleDateFormat using the format() method.
This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method.
Below is the implementation of the above approach:Example:  
Java
// Java program to convert// GregorianCalendar to SimpleDateFormat import java.text.SimpleDateFormat;import java.util.GregorianCalendar; public class GregorianCalendarToCalendar {     public static void convert(        GregorianCalendar gregorianCalendarDate)    {        // Creating an object of SimpleDateFormat        SimpleDateFormat formattedDate            = new SimpleDateFormat("dd-MMM-yyyy");         // Use format() method to change the format        // Using getTime() method,        // this required date is passed        // to format() method        String dateFormatted            = formattedDate.format(                gregorianCalendarDate.getTime());         // Displaying gregorian date ia SimpleDateFormat        System.out.print("SimpleDateFormat: "                         + dateFormatted);    }     // Driver code    public static void main(String[] args)    {         // Get the Gregorian Date to be converted.        GregorianCalendar gcal = new GregorianCalendar();        gcal.set(GregorianCalendar.YEAR, 2019);         // In gregorian calendar month is started from 0        // so for april month will be 03 not 04        gcal.set(GregorianCalendar.MONTH, 03);         gcal.set(GregorianCalendar.DATE, 03);         // Displaying Current Date        // using GregorianCalendar Class        System.out.println("Gregorian date: "                           + gcal.getTime());         // Function to convert this to SimpleDateFormat        convert(gcal);    }}
Gregorian date: Wed Apr 03 05:21:17 UTC 2019
SimpleDateFormat: 03-Apr-2019
 
clintra
sweetyty
Java - util package
Java-SimpleDateFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Check whether the bit at given position is set or unset in Python

Suppose we have a number n and another value k. We have to check whether the kth bit in n is set (1) or unset (0). The value of k is considered from right hand side.
So, if the input is like n = 18 k = 2, then the output will be Set as binary form of 18 is 10010 so the second last bit is 1 (set).
To solve this, we will follow these steps −
temp := n after shifting bits (k - 1) times to the right
if temp AND 1 is 1, thenreturn "Set"
return "Set"
return "Unset"
Let us see the following implementation to get better understanding −
Live Demo
def solve(n,k):
   temp = n >> (k - 1)
   if temp & 1:
      return "Set"
   return "Unset"

n = 18
k = 2
print(solve(n, k))
18

Set
How to calculate row means by excluding NA values in an R data frame?

To find the row means we can use rowMeans function but if we have some missing values in the data frame then na.rm=TRUE argument can be used in the same way as it is used while calculating the means for columns. For example, if we have a data frame df that contains two columns x and y each having some missing values then the row means can be calculated as rowMeans(df,na.rm=TRUE).
Consider the below data frame −
 Live Demo
set.seed(1515)
x1<-sample(c(NA,1,25,31),20,replace=TRUE)
x2<-sample(c(NA,5,12,27),20,replace=TRUE)
x3<-sample(c(NA,15),20,replace=TRUE)
x4<-sample(c(NA,15,9),20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4)
df1
  x1 x2 x3 x4
1 25 NA NA NA
2 25 12 15 NA
3 25 NA 15 NA
4 31 5 NA NA
5 31 27 15 15
6 NA 5 NA 9
7 25 12 15 NA
8 31 5 15 NA
9 1 5 15 15
10 1 27 NA NA
11 25 NA 15 NA
12 25 12 15 15
13 25 NA 15 9
14 31 NA 15 15
15 31 27 15 9
16 1 12 NA 15
17 1 NA NA 9
18 25 27 15 NA
19 31 5 15 9
20 NA 5 15 NA
Finding the row means of df1 −
rowMeans(df1,na.rm=TRUE)
[1]  25.000000 17.333333 20.000000 18.000000 22.000000 7.000000 17.333333
[8]  17.000000 9.000000 14.000000 20.000000 16.750000 16.333333 20.333333
[15] 20.500000 9.333333 5.000000 22.333333 15.000000 10.000000
Let’s have a look at another example −
 Live Demo
y1<-sample(c(NA,rnorm(5,1,0.003)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(10,50,2.47)),20,replace=TRUE)
y3<-sample(c(NA,runif(5,1,4)),20,replace=TRUE)
y4<-sample(c(NA,runif(5,2,10)),20,replace=TRUE)
y5<-sample(c(NA,rexp(5,3.5)),20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4,y5)
df2
y1 y2 y3 y4 y5
1 0.9965744 48.73434 2.097240 9.657755 0.32815971
2 1.0003618 44.83392 2.877004 9.735341 0.27053003
3 0.9974534 NA 2.097240 9.657755 0.64288668
4 0.9999057 54.12249 2.097240 NA 0.06486254
5 1.0003618 54.12249 2.877004 5.945301 NA
6 0.9965744 NA NA NA 0.27053003
7 1.0003618 54.12249 NA 5.945301 0.06486254
8 1.0022832 44.83392 1.065712 5.945301 0.64288668
9 1.0003618 54.34290 NA 9.735341 0.64288668
10 1.0003618 NA 2.323069 3.774950 NA
11 0.9999057 54.12249 1.834897 3.774950 0.64288668
12 0.9999057 53.84937 1.834897 NA 0.44797666
13 0.9974534 47.75855 1.065712 9.735341 0.44797666
14 1.0022832 NA 1.065712 3.774950 0.32815971
15 1.0003618 54.12249 2.877004 5.945301 0.27053003
16 0.9974534 54.34290 2.323069 9.657755 0.64288668
17 NA 44.83392 1.065712 3.774950 0.32815971
18 0.9965744 54.34290 NA NA 0.06486254
19 1.0022832 49.89409 2.323069 3.774950 0.06486254
20 1.0003618 49.89409 1.065712 4.078849 0.32815971
Finding the row means of df2 −
rowMeans(df2,na.rm=TRUE)
[1]  12.3628143 11.7434319 3.3488338 14.3211253 15.9862898 0.6335522
[7]  15.2832544 10.6980210 16.4303723 2.3661269 12.2750266 14.2830369
[13] 12.0010071 1.5427764 12.8431379 13.5928126 12.5006862 18.4681122
[19] 11.4118515 11.2734351
Tryit Editor v3.7

CSS Grid Item
Tryit: The grid-row property
How to update an existing document in MongoDB collection using Java?

The update() method updates the values in the existing document.
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
In Java, you can update a single document using the updateOne()method of the com.mongodb.client.MongoCollection interface. To this method, you need to pass the filter and values for the update.
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
public class UpdatingDocuments {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection object
      MongoCollection<Document>collection = database.getCollection("myCollection");
      //Preparing documents
      Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
      Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
      Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");
      //Inserting the created documents
      List<Document> list = new ArrayList<Document>();
      list.add(document1);
      list.add(document2);
      list.add(document3);
      collection.insertMany(list);
      //Updating a document
      collection.updateOne(Filters.eq("name", "Robert"), Updates.set("city", "Delhi"));
      System.out.println("Document update successfully...");
      FindIterable<Document> iterDoc = collection.find();
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
Document update successfully...
Document after update:
Document{{_id=5e86dd21e9b25f3460b1abe0, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e86dd21e9b25f3460b1abe1, name=Robert, age=27, city=Vishakhapatnam}}
Document{{_id=5e86dd21e9b25f3460b1abe2, name=Rhim, age=30, city=Delhi}}
How to add a Money field in Django?

Sometimes, we may have to add money-related data in a website, like salary, fees or income. Django provides an integer field but many a time, it doesn't work like we want. So, for handling money field, we can use a third-package library that will add the money field to our model.
Make a project and an app, I named it "MoneyFieldDemo" and "myapp".
Set the basic things like urls and INSTALLED_APPS.
And yes, install a library −
pip install django-money
Add the following line in settings.py −
INSTALLED_APPS+= ["djmoney"]
In app's, urls.py, add the following lines −
from django.urls import path
from . import views

urlpatterns = [
   path('', views.home,name="home"),
]
Here, we simply define our url endpoint which will render the html.
In the templates folder's home.html, add −
<!DOCTYPE html>
<html>
   <head>
      <title>
         TUT
      </title>
   </head>
   <body>
      <h2>Hi</h2>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
It is the html file that we are going to render as the frontend.
In models.py, add the following −
from django.db import models
from djmoney.models.fields import MoneyField

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   salary = MoneyField(max_digits=14, decimal_places=2, defa
ult_currency='USD') #This is money field
Here, we created a model which has two value employee names and his salary in USD.
In view.py, add the following −
from django.shortcuts import render
from django import forms
from .models import Data
# Create your views here.

class SalaryForm(forms.ModelForm):
   class Meta:
      model=Data
      fields="__all__"
def home(request):
   if request.method=='POST':
      form=SalaryForm(request.POST)
         if form.is_valid():
            form.save()

   else:
      form=SalaryForm()

   return render(request,'home.html',{'form':form})
There is nothing fancy in views.py. We made a form in it and then just render it and also handle post request.
SQL AND, OR, NOT Operators

The WHERE clause can be combined with 
AND, OR, and 
NOT operators.
The AND and OR operators are used to filter records based on more than one 
condition:
The AND operator displays a record if all the conditions separated by 
  AND 
  are TRUE.
The OR operator displays a record if any of the conditions separated by 
  OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
The table below shows the complete "Customers" table from the Northwind sample database:
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
You can also combine the AND, 
OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" 
OR "München" (use parenthesis to form complex expressions):
The following SQL statement selects all fields from "Customers" where country is 
NOT "Germany" and NOT "USA":
Select all records where the City column has the value 'Berlin' and the PostalCode column has the value 12209.
 * FROM Customers
 City = 'Berlin'
  = 12209;

Start the Exercise
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.
MongoDB find() to operate on recursive search?

Use find() with dot notation to perform recursive search. Let us first create a collection with documents −
> db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":101,"ClientName":"Chris"},{"ClientId":102,"ClientName":"Robert"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a118b50a6c6dd317ad99")
}
> db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":110,"ClientName":"David"},{"ClientId":112,"ClientName":"Mike"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a12fb50a6c6dd317ad9a")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findOperationDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd9a118b50a6c6dd317ad99"),
   "ClientDetails" : [
      {
         "ClientId" : 101,
         "ClientName" : "Chris"
      },
      {
         "ClientId" : 102,
         "ClientName" : "Robert"
      }
   ]
}
{
   "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"),
   "ClientDetails" : [
      {
         "ClientId" : 110,
         "ClientName" : "David"
      },
      {
         "ClientId" : 112,
         "ClientName" : "Mike"
      }
   ]
}
Following is the query to implement find() for recursive search using dot notation −
> db.findOperationDemo.find({"ClientDetails.ClientId":110});
This will produce the following output −
{ "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"), "ClientDetails" : [ { "ClientId" : 110, "ClientName" : "David" }, { "ClientId" : 112, "ClientName" : "Mike" } ] }
Python | Get positive elements from given list of lists - GeeksforGeeks

25 Apr, 2019
Given a list of list, the task is to get only positive element from given list. Below are some ways to solve the above problem.
Method #1: Using Iteration
# Python code to get positive # element from list of list  # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]]Output = []  # Using iterationfor elem in Input:    temp = []    for x in elem:        if x>0:            temp.append(x)    Output.append(temp)    # printing outputprint("Initial List is :", Input)print("Modified list is :", Output)
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]

 Method #2: Using map and list Comprehension
# Python code to get positive element # from list of list  # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]]  # Using list comprehension and maptemp = map(lambda elem: filter(lambda a: a>0, elem), Input)Output = [[a for a in elem if a>0] for elem in temp]  # printing outputprint("Initial List is :", Input)print("Modified list is :", Output)
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]

 Method #3: Using List Comprehension
# Python code to get positive element # from list of list  # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]]  # Using list comprehensionOutput = [ [b for b in a if b>0] for a in Input]  # printing outputprint("Initial List is :", Input)print("Modified list is :", Output)
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Analysis of test data using K-Means Clustering in Python - GeeksforGeeks

09 Feb, 2018
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library.
Pre-requisites: Numpy, OpenCV, matplot-libLet’s first visualize test data with Multiple Features using matplot-lib tool.
# importing required toolsimport numpy as npfrom matplotlib import pyplot as plt  # creating two test dataX = np.random.randint(10,35,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y))Z = Z.reshape((50,2))  # convert to np.float32Z = np.float32(Z)  plt.xlabel('Test Data')plt.ylabel('Z samples')  plt.hist(Z,256,[0,256])  plt.show()
Here ‘Z’ is an array of size 100, and values ranging from 0 to 255. Now, reshaped ‘z’ to a column vector. It will be more useful when more than one features are present. Then change the data to np.float32 type.
Output:
Now, apply the k-Means clustering algorithm to the same example as in the above test data and see its behavior.Steps Involved:1) First we need to set a test data.2) Define criteria and apply kmeans().3) Now separate the data.4) Finally Plot the data.
import numpy as npimport cv2from matplotlib import pyplot as plt  X = np.random.randint(10,45,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y))  # convert to np.float32Z = np.float32(Z)  # define criteria and apply kmeans()criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)ret,label,center = cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)  # Now separate the dataA = Z[label.ravel()==0]B = Z[label.ravel()==1]  # Plot the dataplt.scatter(A[:,0],A[:,1])plt.scatter(B[:,0],B[:,1],c = 'r')plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's')plt.xlabel('Test Data'),plt.ylabel('Z samples')plt.show()
Output:
This example is meant to illustrate where k-means will produce intuitively possible clusters.Applications:1) Identifying Cancerous Data.2) Prediction of Students’ Academic Performance.3) Drug Activity Prediction.
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Decision Tree Introduction with example
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Decision Tree
Agents in Artificial Intelligence
Activation functions in Neural Networks
Decision Tree Introduction with example
Support Vector Machine Algorithm
Example of Interfacing Seven Segments LED Display with 8085 - GeeksforGeeks

22 Jan, 2021
Seven segments LED display :
A seven-segment LED is a kind of LED(Light Emitting Diode) consisting of 7 small LEDs it usually comes with the microprocessor’s as we commonly need to interface them with microprocessors like 8085.
Structure of Seven Segments LED :
The LED in Seven Segment display are arranged as below
It can be used to represent numbers from 0 to 8 with a decimal point.
We have eight segments in a Seven Segment LED display consisting of 7 segments which include ‘.’.
The seven segments are denoted as “a, b, c, d, e, f, g, h” respectively, and ‘.’ is represented by “h”
Interfacing Seven Segment Display with 8085 :
We will see a program to Interfacing Seven Segment Display with 8085 assuming address decoders with an address of AE H.
Note logic needed for activation –
Common Anode – 0 will make an LED glow.
Common Cathode – 1 will make an LED glow.
Common Anode Method :
Here we are using a common anode display therefore 0 logic is needed to activate the segment. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated.
The instructions to execute it is given as,
MVI A,99
OUT AE
First, we are storing the 99H in the accumulator i.e. 10010000 by using MVI instruction.
By OUT instruction we are sending the data stored in the accumulator to the port AFH
Common Cathode Method :
Here we are using common cathode 1 logic is needed to activate the signal. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated.
The instructions to execute it is given as,
MVI A,6F 
OUT AE
First, we are storing the 6FH  in the accumulator i.e.01101111 by using MVI instruction.
By OUT instruction we are sending the data stored in the accumulator to the port AFH
microprocessor
Computer Organization and Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced RISC Machine (ARM) Processor
Difference between Cache Coherence and Memory Consistency
Basic Cache Optimization Techniques
Difference between Hardware and Peripherals
Advantages and disadvantages of Hard Disk
Factors affecting Cache Memory Performance
Representing Instructions in Computer
Simultaneous and Hierarchical Cache Accesses
8085 program to find 2's complement of the contents of Flag Register
Computer Organization and Architecture | Computer Organization and Architecture | Question 1
Boolean compareTo() method in Java with examples - GeeksforGeeks

08 Oct, 2018
The compareTo() method of Boolean class is a built in method in Java which is used to compare the given Boolean instance with the current instance.
Syntax:
BooleanObject.compareTo(Boolean a)
Parameters: It takes a Boolean value a as parameter which is to be compared with the current instance.
Return Type: The return type of the function is int. It returns:
0 if ‘a’ is equal to ‘b’,
a negative value if ‘a’is false and ‘b’ is true,
a positive value if ‘a’ is true and ‘b’ is false.
Below are programs to illustrate the compareTo() method of Boolean class:
Program 1:
// Java code to implement// compareTo() method of Boolean class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // Boolean object        Boolean a = new Boolean(true);          // Boolean object        Boolean b = new Boolean(true);          // compare method        System.out.println(a + " comparing with " + b                           + " = " + a.compareTo(b));    }}
true comparing with true = 0

Program 2:
// Java code to implement// compareTo() method of Java class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // Boolean object        Boolean a = new Boolean(true);          // Boolean object        Boolean b = new Boolean(false);          // compare method        System.out.println(a + " comparing with " + b                           + " = " + a.compareTo(b));    }}
true comparing with false = 1

Program 3:
// Java code to implement// compareTo() method of Java class  class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // Boolean object        Boolean a = new Boolean(false);          // Boolean object        Boolean b = new Boolean(true);          // compare method        System.out.println(a + " comparing with " + b                           + " = " + a.compareTo(b));    }}
false comparing with true = -1

Java - util package
Java-Byte
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
Difference between Firm Real-time Tasks and Soft Real-time Tasks - GeeksforGeeks

16 May, 2020
Real-time tasks are generally classified as – Hard and Soft but on a wide range, Real-time tasks are classified as:
Hard Real-time TasksFirm Real-time TasksSoft Real-time Tasks
Hard Real-time Tasks
Firm Real-time Tasks
Soft Real-time Tasks
1. Firm Real-time Tasks :Firm real-time tasks are such type of real-time tasks which are associated with time bound and the task need to produce the result within the deadline. Although firm real-time task is different from hard real-time task as in hard real-time once deadline is crossed and task is not completed, system fails but in case of firm real-time task even after the passing of deadline, system does not fail.
Example:
1. Video conferencing
2. Satellite based tracking 
2. Soft Real-time Tasks :Soft real-time tasks are such type of real-time tasks which are also associated with time bound but here timing constraints are not expressed as absolute values. In soft real-time tasks, even after the deadline result is not considered incorrect and system failure does not occur.
Example:
1. Web browsing
2. Railway Ticket Reservation 
Difference between Firm and Soft Real-time Tasks :
Difference Between
Operating Systems
Operating Systems
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 Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
Semaphores in Process Synchronization
ES6 - toLowerCase()

This method returns the calling string value converted to lowercase.
string.toLowerCase( )  

Returns the calling string value converted to lowercase.
var str = "Apples are round, and Apples are Juicy."; 
console.log(str.toLowerCase( ))   
apples are round, and apples are juicy. 


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How to find the length of the StringBuilder in C# - GeeksforGeeks

28 Jan, 2019
StringBuilder.Length Property is used to get or set the length of the current StringBuilder object.
Syntax: public int Length { get; set; }It returns the length of the current instance.
Exception: This property will give ArgumentOutOfRangeException if the value specified for a set operation is less than zero or greater than MaxCapacity.
Below programs illustrate the use of the above-discussed property:
Example 1:
// C# program to demonstrate// the Length() Propertyusing System;using System.Text;  class GFG {      // Main Method    public static void Main(String[] args)    {          // create a StringBuilder object        // with a String passed as parameter        StringBuilder str = new StringBuilder("WelcomeGeeks");          // print string        Console.WriteLine("String = "                   + str.ToString());          // get length of StringBuilder object        int length = str.Length;          // print length        Console.WriteLine("length of String = "                                     + length);    }}
String = WelcomeGeeks
length of String = 12

Example 2:
// C# program to demonstrate// the Length() Propertyusing System;using System.Text;  class GFG {    public static void Main(String[] args)    {          // create a StringBuilder object        // with a String passed as parameter        StringBuilder str = new StringBuilder("India is Great");          // print string        Console.WriteLine("String = "                   + str.ToString());          // get length of StringBuilder object        int length = str.Length;          // print length        Console.WriteLine("length of String = "                                     + length);    }}
String = India is Great
length of String = 14

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.length?view=netframework-4.7.2
CSharp-StringBuilder-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to calculate Electricity Bill
C# Dictionary with examples
C# | Method Overriding
Introduction to .NET Framework
HashSet in C# with Examples
C# | Replace() Method
How to find the length of an Array in C#
C# | Dictionary.Add() Method
C# Tutorial
C# | Class and Object
Print new line and tab in Arduino

In order to print a newline, you can either introduce the '\n' character in your text, or use Serial.println() instead of Serial.print()
An example code is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   Serial.print("This is line1\nThis is line2\n");
   Serial.println("This is line3");
   Serial.println("This is line4");
}
void loop() {
   // put your main code here, to run repeatedly:
   
}
The Serial Monitor output for the above code is −
In order to add a tab space, you can introduce '\t' in your code.
An example code is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   Serial.print("This is left half\tThis is right half\n");
}
void loop() {
   // put your main code here, to run repeatedly:
   
}
The corresponding Serial Monitor output is −
Palindrome program in Java.

Following is the required program.
Live Demo
public class Tester {
   public static void main(String args[]) {
      int r, sum = 0, temp;
      int m = 454;
      int n = m;
      temp = n;
      while (n > 0) {
         r = n % 10;
         sum = (sum * 10) + r;
         n = n / 10;
     }
     if (temp == sum) {
        System.out.println(m + " is a palindrome number.");
     } else {
        System.out.println(m + "is not a palindrome number.");
     }
   }
}
454 is a palindrome number.
Advanced Selectors in CSS

The Advanced Selectors in CSS includes Adjacent Sibling selector, attribute selector, direct child selector, nth-of-type selector, etc. It also includes General Sibling Selector, an example is shown below:
h1 ~ h3
Example of direct child selector −
div > span
Following is the code showing advanced selectors in CSS −
 Live Demo
<html>
<head>
<style>
#red {
   color: red;
}
.green {
   background: green;
}
ul:nth-of-type(1) {
   background: rgb(0, 174, 255);
}
ul + h3 {
   border: 4px solid rgb(19, 0, 128);
}
a[href="https://www.wikipedia.org"] {
   font-size: 25px;
}
h1 ~ h3 {
   font-size: 40px;
}
div > span {
   background-color: DodgerBlue;
}
</style>
</head>
<body>
<h1>Advanced Selectors Example</h1>
<ul>
<li>Cow</li>
<li>Dog</li>
<li>Cat</li>
</ul>
<ul>
<li>Puma</li>
<li>Leopard</li>
<li>Cheetah</li>
</ul>
<h3>Animals</h3>
<div>
<span>Text sample</span>
<p>
Paragraph Text
<span>span text</span>
</p>
<p class="green">Paragraph Text</p>
<p id="red">Paragraph Text.</p>
<p class="green">Paragraph Text</p>
</div>
<a href="https://www.google.com">www.google.com</a>
<a href="https://www.wikipedia.org" target="_blank">www.wikipedia.org</a>
</body>
</html>
The above code will produce the following output −
DLL - Tools

Several tools are available to help you troubleshoot DLL problems. Some of them are discussed below.
The Dependency Walker tool (depends.exe) can recursively scan for all the dependent DLLs that are used by a program. When you open a program in Dependency Walker, the Dependency Walker performs the following checks:
Checks for missing DLLs.
Checks for program files or DLLs that are not valid.
Checks that import functions and export functions match.
Checks for circular dependency errors.
Checks for modules that are not valid because the modules are for a different operating system.
By using Dependency Walker, you can document all the DLLs that a program uses. It may help prevent and correct DLL problems that may occur in the future. Dependency Walker is located in the following directory when you install Microsoft Visual Studio 6.0:
drive\Program Files\Microsoft Visual Studio\Common\Tools

The DLL Universal Problem Solver (DUPS) tool is used to audit, compare, document, and display DLL information. The following list describes the utilities that make up the DUPS tool:
Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file.
Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file.
Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences.
Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences.
Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database.
Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database.
DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility.
DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility.
 Print
 Add Notes
 Bookmark this page
How to retrieve the value from a table cell with TableModel in Java?

At first, create a table with DefaultTableModel −
String data[][] = {
   {"Australia","5","1"},
   {"US","10","2"},
   {"Canada","9","3"},
   {"India","7","4"},
   {"Poland","2","5"},
   {"SriLanka","5","6"}
};
String col [] = {"Team","Selected Players","Rank"};
DefaultTableModel tableModel = new DefaultTableModel(data,col);
JTable table = new JTable(tableModel);
Now, use the getModel() to retrieve the value from table cell −
Object ob = table.getModel().getValueAt(3, 2);
System.out.println("Value = "+ob);
The following is an example to retrieve the value from a table cell with TableModel −
package my;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      JFrame frame = new JFrame("Demo");
      JPanel panel = new JPanel();
      String data[][] = {
         {"Australia","5","1"},
         {"US","10","2"},
         {"Canada","9","3"},
         {"India","7","4"},
         {"Poland","2","5"},
         {"SriLanka","5","6"}
      };
      String col [] = {"Team","Selected Players","Rank"};
      DefaultTableModel tableModel = new DefaultTableModel(data,col);
      JTable table = new JTable(tableModel);
      table.getTableHeader().setResizingAllowed(false);
      Dimension dim = new Dimension(50,2);
      table.setIntercellSpacing(new Dimension(dim));
      Object ob = table.getModel().getValueAt(3, 2);
      System.out.println("Value = "+ob);
      JScrollPane scrollPane = new JScrollPane(table);
      panel.add(scrollPane);
      frame.add(panel);
      frame.setSize(600,400);
      frame.setUndecorated(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
      frame.setVisible(true);
   }
}
The value of the cell would be visible in the Console −
Find All Live Hosts IP Addresses Connected on Network in Linux - GeeksforGeeks

28 Jul, 2021
As network engineers or penetration testers, we need to find the live hosts on the networks. Today we are going to see how to find live hosts on the network. We are going to use the nmap tool to find the live hosts on the network.
Nmap (network mapper) is an open-source command-line tool for network exploration and security auditing. Nmap is used to scan the networks using the raw IP packets. In this article, we are using the nmap to find live hosts on the network.
Now let’s see how to install nmap on the different Linux Distros:
For Ubuntu/Debian/Kali Linux systems:
sudo apt-get install nmap
For Arch Linux:
sudo pacman -S nmap
For CentOS:
sudo yum install nmap
For Fedora:
sudo dnf install nmap
Now we have installed the nmap on the system. The syntax for nmap use is:
 nmap  <scan type...>  options  <target>
Here, scan type are the option provided by the nmap. And the target is the IP address or hostname of the network.
Now to find a live host first we need to find the IP address and the subnet mask of the target that means we need to find the IP address and its subnet mask of our network. We can find the IP address by following commands:
ifconfig
or 
ip addr show
Here in this case the IP of the network is 192.1.1.0 and the subnet mask is 255.255. 255.0 i.e. /24. Now we are going to use the following command of nmap to find the live host on our network.
Here -sn is an option: This option tells the nmap to do not scan port after host discovery of a live host. By default, the Nmap scans all ports on the discovered host.
192.168.1.0/24 is a target: We are going to scan the live host on this target.
 nmap -sn 192.168.1.0/24
In the above output, we can see there are two live hosts. To know more about we can use man command or help command like to follow
man nmap
and
nmap --help
This is how we can find the live host on our network.
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Generating OTP (One time Password) in PHP

10 Oct, 2018
Now these days, OTP (one time password) is mandatory in almost each and every service. A developer can generate OTP in many ways but the challenge is not to be predictive as any one can predict the OTP and can exploit the service.
Some of popular format of OTPs are:
4 or 6 digit Numeric OTP.
4 or 6 alphabetic (lowercase / uppercase) OTP.
4 or 6 digit alphanumeric OTP.
Examples for n-digit numeric OTP:
Input : n = 4
Output : 8723

Input : n = 8
Output : 23914072

Note: The output of program will be different in every execution.
One of the best way to generate OTP is to use random function. But using random function directly can be dangerous. So here is an method which uses random function and some algorithm for generating the n-digit numeric OTP.
Program:
<?php  // Function to generate OTPfunction generateNumericOTP($n) {          // Take a generator string which consist of    // all numeric digits    $generator = "1357902468";      // Iterate for n-times and pick a single character    // from generator and append it to $result          // Login for generating a random character from generator    //     ---generate a random number    //     ---take modulus of same with length of generator (say i)    //     ---append the character at place (i) from generator to result      $result = "";      for ($i = 1; $i <= $n; $i++) {        $result .= substr($generator, (rand()%(strlen($generator))), 1);    }      // Return result    return $result;}  // Main program$n = 6;print_r(generateNumericOTP($n));  ?>
561862

Algorithms
PHP
PHP Programs
Randomized
Algorithms
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript String toUpperCase() Method

23 Dec, 2021
Below is the example of the String toUpperCase() Method.
Example:  
JavaScript
<script>function func() {    var str = 'geeksforgeeks';    var string = str.toUpperCase();    document.write(string);}func();</script>
Output:  
GEEKSFORGEEKS
str.toUpperCase() method converts the entire string to Upper case. This method does not affect any of the special characters, digits, and the alphabets that are already in the upper case. Syntax:  
str.toUpperCase()
Return value: This method returns a new string in which all the lower case letters are converted to upper case.Examples for the above method are provided below:Example 1:  
var str = 'It iS a Great Day.';
var string = str.toUpperCase();
print(string);
Output:  
IT IS A GREAT DAY.
In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Example 2:  
var str = 'It iS a 5r&e@@t Day.'
var string = str.toUpperCase();
print(string);
Output:  
IT IS A 5R&AMP;E@@T DAY.
In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Codes for the above method are provided below:Program 1: 
JavaScript
<script>// JavaScript to illustrate .toUpperCase()   function func() {          // Original string    var str = 'It iS a Great Day.';          // String converted to Upper Case    var string = str.toUpperCase();    document.write(string);}  func();</script>
Output:  
IT IS A GREAT DAY.
Program 2: 
JavaScript
<script>// JavaScript to illustrate .toUpperCase() function func() {          //Original string    var str = 'It iS a 5r&:ampe@@t Day.'          //String converted to Upper Case    var string = str.toUpperCase();    document.write(string);}  func();</script>
Output:  
IT IS A 5R&:AMPE@@T DAY.
 
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
deque::push_back() in C++ STL

06 Oct, 2021
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. 
push_back() function is used to push elements into a deque from the back. The new value is inserted into the deque at the end, before the current last element and the container size is increased by 1.Syntax :  
dequename.push_back(value)
Parameters :
The value to be added in the back is 
passed as the parameter
Result :
Adds the value mentioned as the parameter 
to the back of the deque named as dequename
Examples: 
Input : deque{1, 2, 3, 4, 5};
        deque.push_back(6);
Output : 1, 2, 3, 4, 5, 6

Input : deque{5, 4, 3, 2, 1};
        deque.push_back(6);
Output : 5, 4, 3, 2, 1, 6
Errors and Exceptions1. Strong exception guarantee – if an exception is thrown, there are no changes in the container. 2. If the value passed as argument is not supported by the deque, it shows undefined behavior. 
CPP
// CPP program to illustrate// push_back() function#include <iostream>#include <deque>using namespace std; int main(){    deque<int> mydeque{ 1, 2, 3, 4, 5 };    mydeque.push_back(6);     // deque becomes 1, 2, 3, 4, 5, 6     for (auto it = mydeque.begin();              it != mydeque.end(); ++it)        cout << ' ' << *it;}
Output: 
1 2 3 4 5 6
Time Complexity : O(1)Application Given an empty deque, add integers to it using push_back() function and then calculate sum of all its elements. 
Input  : 11, 2, 5, 3, 7, 1
Output : 29
Algorithm 1. Add elements to the deque using push_back() function. 2. Check if the size of the deque is 0, if not, add the front element to the sum variable initialized as 0, and pop the front element. 3. Repeat this step until the size of the deque becomes 0. 4. Print the final value of the variable. 
CPP
// CPP program to illustrate// Application of push_back() function#include <iostream>#include <deque>using namespace std; int main(){    int sum = 0;    deque<int> mydeque;    mydeque.push_back(11);    mydeque.push_back(2);    mydeque.push_back(5);    mydeque.push_back(3);    mydeque.push_back(7);    mydeque.push_back(1);    while (!mydeque.empty()) {        sum = sum + mydeque.front();        mydeque.pop_front();    }    cout << sum;    return 0;}
Output:  
29
 
akshaydharsey
hritikbhatnagar2182
cpp-deque
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.