code-rag-bench/online-tutorials huggingface dataset:
Print common characters of two Strings in alphabetical order in C++

In this programming problem, we are given two strings. And we have to find all the characters of the string that are common in both the string and we have to print these common characters in alphabetical order. And print ‘NO COMMON CHARACTERS ’ found if no common letters arise. Given that the string does not contain all lower case alphabets.
Let’s take an example −
Input : string1 : adsfhslf
   string2 : fsrakf
Output : affs
Explanation − Between the two strings there are a, f, s. Hence the lexicographical output is ‘afs’.
Input : string1 : abcde
   string2 : glhyte
Output : No common characters
Explanation − There are no characters are in common.
To solve this problem, we need to find common characters in the string. And the output will be the lexicographical order of these string.
Algorithm to solve this problem is −
Step 1 : Create two arrays a1[] and a2[] of size 26 each for counting the number of alphabets in the strings string1 and string2.
Step 2 : traverse a1[] and a2[]. and in sequence print all those numbers that have values in the array.
Let's create a program based on this algorithm to illustrate the working −
 Live Demo
#include<bits/stdc++.h>
using namespace std;
int main(){
   string string1 = "adjfrdggs";
   string string2 = "gktressd";
   cout<<"The strings are "<<string1<<" and "<<string2;
   cout<<"\nThe common characters are : ";
   int a1[26] = {0};
   int a2[26] = {0};
   int i , j;
   char ch;
   char ch1 = 'a';
   int k = (int)ch1, m;
   for(i = 0 ; i < string1.length() ; i++){
      a1[(int)string1[i] - k]++;
   }
   for(i = 0 ; i < string2.length() ; i++){
      a2[(int)string2[i] - k]++;
   }
   for(i = 0 ; i < 26 ; i++){
      if (a1[i] != 0 and a2[i] != 0){
         for(j = 0 ; j < min(a1[i] , a2[i]) ; j++){
            m = k + i;
            ch = (char)(k + i);
            cout << ch;
         }
      }
   }
   return 0;
}
The strings are adjfrdggs and gktressd
The common characters are : dgrs
How to get this nodes’s parent in a JTree with Java?

Let’s say we want the parent of a node, then use the getParent() method -
node3.getFirstChild()
You can also get the parent of child node. Here, “nine” is the child node −
nine.getParent()
The output is as follows displaying this node’s parent on Console −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Products");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Clothing (Product1 - P66778)");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Accessories (Product2 - P66779)");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Home Decor (Product3 - P66780)");
      DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Electronics (Product4 - P66781)");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      node.add(node4);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("Shirt");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("T-shirt");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("Hoodie");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Sunglasses");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("Frames");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("Belts");
      DefaultMutableTreeNode seven = new DefaultMutableTreeNode("Showpieces & Figurines");
      DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Clocks");
      DefaultMutableTreeNode nine = new DefaultMutableTreeNode("Wall Shelves");
      DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Mobile Accessories");
      DefaultMutableTreeNode eleven = new DefaultMutableTreeNode("Smart Wearable Tech");
      DefaultMutableTreeNode twelve = new DefaultMutableTreeNode("Health Care Applicances");
      DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode("Smart Home Automation");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node2.add(six);
      node3.add(seven);
      node3.add(eight);
      node3.add(nine);
      node4.add(ten);
      node4.add(eleven);
      node4.add(twelve);
      node4.add(thirteen);
      JTree tree = new JTree(node);
      for (int i = 0; i < tree.getRowCount(); i++) {
         tree.expandRow(i);
      }
      tree.putClientProperty("JTree.lineStyle", "Angled");
      System.out.println("Node 3 = "+node.getChildAt(2));
      System.out.println("The last child of node 3 = "+node3.getLastChild());
      System.out.println("Parent of node3 = "+node3.getParent());
      System.out.println("Parent of child node nine = "+nine.getParent());
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(600,450);
      frame.setVisible(true);
   }
}
The output is as follows displaying this node’s parent −
The following is our JTree −
How to read the data from a properties file in Java?


The Properties is a subclass of Hashtable class and it represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. 
The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties.load() method of Properties class is convenient to load .properties file in the form of key-value
pairs.
public class Properties extends Hashtable
import java.io.*;
import java.util.*;
public class ReadPropertiesFileTest {
   public static void main(String args[]) throws IOException {
      Properties prop = readPropertiesFile("credentials.properties");
      System.out.println("username: "+ prop.getProperty("username"));
      System.out.println("password: "+ prop.getProperty("password"));
   }
   public static Properties readPropertiesFile(String fileName) throws IOException {
      FileInputStream fis = null;
      Properties prop = null;
      try {
         fis = new FileInputStream(fileName);
         prop = new Properties();
         prop.load(fis);
      } catch(FileNotFoundException fnfe) {
         fnfe.printStackTrace();
      } catch(IOException ioe) {
         ioe.printStackTrace();
      } finally {
         fis.close();
      }
      return prop;
   }
}
username: admin
password: admin@123
Redis - Sorted Set Zrank Command

Redis ZRANK command returns the rank of member in the sorted set stored at the key, with the scores ordered from low to high. The rank (or index) is 0-based, which means that the member with the lowest score has rank 0.
If the member exists in the sorted set, Integer reply: the rank of member.
If the member exists in the sorted set, Integer reply: the rank of member.
If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil.
If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil.
Following is the basic syntax of Redis ZRANK command.
redis 127.0.0.1:6379> ZRANK key member

redis 127.0.0.1:6379> ZADD myzset 0 a 1 b 2 c 3 d 4 e 
(integer) 5 
redis 127.0.0.1:6379> ZADD myzset 5 f 6 g 
(integer) 2 
redis 127.0.0.1:6379> ZRANK myzset b 
(integer) 1 
redis 127.0.0.1:6379> ZRANK myzset t 
nil 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How can we use a MySQL subquery with INSERT statement?

It can be understood with the help of an example in which we would copy the values of a table into other table. We are using the data from table ‘cars’ and copy its data to table ‘copy_cars’ −
mysql> CREATE TABLE copy_cars LIKE cars;
Query OK, 0 rows affected (0.86 sec)

mysql> SELECT * from copy_cars;
Empty set (0.08 sec)
The following query using the subquery will insert the values same as ‘cars’ to table ‘copy_cars’ −
mysql> INSERT INTO Copy_cars Select * from Cars;
Query OK, 8 rows affected (0.07 sec)

mysql> SELECT * from copy_cars;
+------+--------------+---------+
| ID   | Name         | Price   |
+------+--------------+---------+
| 1    | Nexa         | 750000  |
| 2    | Maruti Swift | 450000  |
| 3    | BMW          | 4450000 |
| 4    | VOLVO        | 2250000 |
| 5    | Alto         | 250000  |
| 6    | Skoda        | 1250000 |
| 7    | Toyota       | 2400000 |
| 8    | Ford         | 1100000 |
+------+--------------+---------+
8 rows in set (0.00 sec)
DAX Aggregation - SUM function

Returns the sum of all the numbers in a column.
SUM (<column>) 

column
The column that contains the numbers to sum.
A decimal number.
If any rows contain non-numeric values, blanks are returned.
= SUM ([Sales Amount]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
GATE | GATE CS 2019 | Question 33 - GeeksforGeeks

05 Aug, 2021
Consider the following C program:
#include<stdio.h> int main(){  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4;    printf("%d\n", ip[1]);    return 0;}
The number that will be displayed on execution of the program is _________ .(A) 6(B) 5(C) 4(D) segmentation errorAnswer: (A)Explanation:
#include<stdio.h> int main(){  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4;    printf("%d\n", ip[1]);    return 0;}
Note that index of array always start from 0 in C.
Initially ip pointer is pointing at (arr+4) or skipping starting first 4 position.
Now in the printf system call, 1 more position is to skip, So it will point to (arr+5) or skip 5 position from starting:
Hence, printf will print value at 6th position, i.e., 6 will printed.
So, option (A) is correct.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:005:07 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1997 | Question 25
Heap Data Structures

Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If α has child node β then −
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types −
For Input → 35 33 42 10 14 19 27 44 26 31

Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.
We shall use the same example to demonstrate how a Max Heap is created. The procedure to create Min Heap is similar but we go for min values instead of max values.
We are going to derive an algorithm for max heap by inserting one element at a time. At any point of time, heap must maintain its property. While insertion, we also assume that we are inserting a node in an already heapified tree.
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Note − In Min Heap construction algorithm, we expect the value of the parent node to be less than that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same input sample that we used earlier.
Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap always happens at the root to remove the Maximum (or minimum) value.
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to query between two dates in MySQL?

You can query between dates with the help of BETWEEN statement. The syntax is as follows −
select *from yourTableName where yourColumnName between ‘yourStartingDate’ and curdate().
Use curdate() or now(), both these functions will work. To understand the above syntax, let us create a table −
mysql> create table BetweenDateDemo
   −> (
   −> StartDate datetime
   −> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table with the help of the following query −
mysql> insert into BetweenDateDemo values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.11 sec)

mysql> insert into BetweenDateDemo values(date_add(now(),interval -2 year));
Query OK, 1 row affected (0.13 sec)

mysql> insert into BetweenDateDemo values(date_add(now(),interval -3 year));
Query OK, 1 row affected (0.13 sec)

mysql> insert into BetweenDateDemo values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.12 sec)

mysql> insert into BetweenDateDemo values(date_add(now(),interval 2 year));
Query OK, 1 row affected (0.12 sec)

mysql> insert into BetweenDateDemo values(date_add(now(),interval 3 year));
Query OK, 1 row affected (0.16 sec)
Now you can display all records from the table with the help of select statement. The query is as follows −
mysql> select *from BetweenDateDemo;
The following is the output −
+---------------------+
| StartDate           |
+---------------------+
| 2017-12-08 11:45:47 |
| 2016-12-08 11:45:56 |
| 2015-12-08 11:46:01 |
| 2019-12-08 11:46:05 |
| 2020-12-08 11:46:11 |
| 2021-12-08 11:46:15 |
+---------------------+
6 rows in set (0.00 sec)
Now perform select between dates using the syntax discussed above −
mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate();
The following is the output −
+---------------------+
| StartDate           |
+---------------------+
| 2017-12-08 11:45:47 |
| 2016-12-08 11:45:56 |
| 2015-12-08 11:46:01 |
+---------------------+
3 rows in set (0.00 sec)
Use ORDER BY to get in a sorted order. The query is as follows −
mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate() order by StartDate;
The following is the output −
+---------------------+
| StartDate           |
+---------------------+
| 2015-12-08 11:46:01 |
| 2016-12-08 11:45:56 |
| 2017-12-08 11:45:47 |
+---------------------+
3 rows in set (0.00 sec)
Kubernetes - Secrets

Secrets can be defined as Kubernetes objects used to store sensitive data such as user name and passwords with encryption.
There are multiple ways of creating secrets in Kubernetes.
Creating from txt files.
Creating from yaml file.
In order to create secrets from a text file such as user name and password, we first need to store them in a txt file and use the following command.
$ kubectl create secret generic tomcat-passwd –-from-file = ./username.txt –fromfile = ./.
password.txt

apiVersion: v1
kind: Secret
metadata:
name: tomcat-pass
type: Opaque
data:
   password: <User Password>
   username: <User Name>

$ kubectl create –f Secret.yaml
secrets/tomcat-pass

Once we have created the secrets, it can be consumed in a pod or the replication controller as −
Environment Variable
Volume
In order to use the secret as environment variable, we will use env under the spec section of pod yaml file.
env:
- name: SECRET_USERNAME
   valueFrom:
      secretKeyRef:
         name: mysecret
         key: tomcat-pass

spec:
   volumes:
      - name: "secretstest"
         secret:
            secretName: tomcat-pass
   containers:
      - image: tomcat:7.0
         name: awebserver
         volumeMounts:
            - mountPath: "/tmp/mysec"
            name: "secretstest"

apiVersion: v1
kind: ReplicationController
metadata:
   name: appname
spec:
replicas: replica_count
template:
   metadata:
      name: appname
   spec:
      nodeSelector:
         resource-group:
      containers:
         - name: appname
            image:
            imagePullPolicy: Always
            ports:
            - containerPort: 3000
            env: -----------------------------> 1
               - name: ENV
                  valueFrom:
                     configMapKeyRef:
                        name: appname
                        key: tomcat-secrets

In the above code, under the env definition, we are using secrets as environment variable in the replication controller.
apiVersion: v1
kind: pod
metadata:
   name: appname
spec:
   metadata:
      name: appname
   spec:
   volumes:
      - name: "secretstest"
         secret:
            secretName: tomcat-pass
   containers:
      - image: tomcat: 8.0
         name: awebserver
         volumeMounts:
            - mountPath: "/tmp/mysec"
            name: "secretstest"


    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Java program to round a number

The java.lang.Math.round(float a) returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Special cases −
If the argument is NaN, the result is 0.
If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
import java.util.Scanner;
public class RoundingDecimalPlaces {
   public static void main(String[] args) {
      System.out.println("Enter a string value ::");
      Scanner sc = new Scanner(System.in);
      float f = sc.nextFloat();
      System.out.println("Result of the given float after rounding:: " + Math.round(f));
   }
}
Enter a string value ::
44584.2257
Result of the given float after rounding:: 44584
Difference between the Ternary operator and Null coalescing operator in php

Ternary operator is used to replace if else statements into one statement.
(condition) ? expression1 : expression2;
if(condition) {
   return expression1;
}
else {
   return expression2;
}
If condition is true, then it returns result of expression1 else it returns result of expression2. void is not allowed in condition or expressions.
Null coalescing operator is used to provide not null value in case the variable is null.
(variable) ?? expression;
if(isset(variable)) {
   return variable;
}
else {
   return expression;
}
If variable is null, then it returns result of expression.
<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?php
      // fetch the value of $_GET['user'] and returns 'not passed'
      // if username is not passed
      $username = $_GET['username'] ?? 'not passed';
      print($username);
      print("<br/>");
      // Equivalent code using ternary operator
      $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
      print($username);
      print("<br/>");
   ?>
</body>
</html>
not passed
not passed
How to declare a variable inside a procedure in MySQL?

You can use the DECLARE command to declare a variable inside a MySQL procedure. Let us create a stored procedure in MySQL −
mysql> DELIMITER //
mysql> CREATE PROCEDURE DECLARE_VARIABLE_DEMO(IN value int)
   -> BEGIN
   -> DECLARE searchValue int;
   -> set searchValue=value;
   -> if searchValue=10 then
   ->    select searchValue+100;
   -> else
   ->    select searchValue;
   -> end if;
   -> END
   -> //
Query OK, 0 rows affected (0.17 sec)
mysql> DELIMITER ;
Above, we have declared a variable. Now, let us call the stored procedure using CALL command −
mysql> call DECLARE_VARIABLE_DEMO(10);
This will produce the following output −
+-----------------+
| searchValue+100 |
+-----------------+
|             110 |
+-----------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
C library function - bsearch()

The C library function void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to, by key. The size of each member of the array is  specified by size.
The contents of the array should be in ascending sorted order according to the comparison function referenced by compar.
Following is the declaration for bsearch() function.
void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))
key − This is the pointer to the object that serves as key for the search, type-casted as a void*.
key − This is the pointer to the object that serves as key for the search, type-casted as a void*.
base  − This is the pointer to the first object of the array where the search is performed, type-casted as a void*.
base  − This is the pointer to the first object of the array where the search is performed, type-casted as a void*.
nitems − This is the number of elements in the array pointed by base.
nitems − This is the number of elements in the array pointed by base.
size − This is the size in bytes of each element in the array.
size − This is the size in bytes of each element in the array.
compare − This is the function that compares two elements.
compare − This is the function that compares two elements.
This function returns a pointer to an entry in the array that matches the search key. If key is not found, a NULL pointer is returned.
The following example shows the usage of bsearch() function.
#include <stdio.h>
#include <stdlib.h>


int cmpfunc(const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int values[] = { 5, 20, 29, 32, 63 };

int main () {
   int *item;
   int key = 32;

   /* using bsearch() to find value 32 in the array */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) {
      printf("Found item = %d\n", *item);
   } else {
      printf("Item = %d could not be found\n", *item);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Found item = 32


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
jsoup - Set HTML

Following example will showcase use of method to set, prepend or append html to a dom element after parsing an HTML String into a Document object.
Document document = Jsoup.parse(html);
Element div = document.getElementById("sampleDiv");     
div.html("<p>This is a sample content.</p>");   
div.prepend("<p>Initial Text</p>");
div.append("<p>End Text</p>");   

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
Jsoup − main class to parse the given HTML String.
html − HTML String.
html − HTML String.
div − Element object represent the html node element representing anchor tag.
div − Element object represent the html node element representing anchor tag.
div.html() − html(content) method replaces the element's outer html with the corresponding value.
div.html() − html(content) method replaces the element's outer html with the corresponding value.
div.prepend() − prepend(content) method adds the content before the outer html.
div.prepend() − prepend(content) method adds the content before the outer html.
div.append() − append(content) method adds the content after the outer html.
div.append() − append(content) method adds the content after the outer html.
Element object represent a dom elment and provides various method to set, prepend or append html to a dom element.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      Element div = document.getElementById("sampleDiv");
      System.out.println("Outer HTML Before Modification :\n"  + div.outerHtml());
      div.html("<p>This is a sample content.</p>");
      System.out.println("Outer HTML After Modification :\n"  + div.outerHtml());
      div.prepend("<p>Initial Text</p>");
      System.out.println("After Prepend :\n"  + div.outerHtml());
      div.append("<p>End Text</p>");
      System.out.println("After Append :\n"  + div.outerHtml());          
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Outer HTML Before Modification :
<div id="sampleDiv">
 <a id="googleA" href="www.google.com">Google</a>
</div>
Outer HTML After Modification :
<div id="sampleDiv">
 <p>This is a sample content.</p>
</div>
After Prepend :
<div id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
</div>
After Append :
<div id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
 <p>End Text</p>
</div>
Outer HTML Before Modification :
<span>Sample Content</span>
Outer HTML After Modification :
<span>Sample Content</span>

 Print
 Add Notes
 Bookmark this page
BigDecimal toBigInteger() Method in Java - GeeksforGeeks

09 Nov, 2021
The java.math.BigDecimal.toBigInteger() is an inbuilt method in java that converts this BigDecimal to a BigInteger. This conversion is analogous to the narrowing primitive conversion from double to long. Any fractional part of this BigDecimal will be discarded. This conversion can lose information about the precision of the BigDecimal value.
Note: If an exception is thrown in the conversion inexact (in other words if a nonzero fractional part is discarded), use the toBigIntegerExact() method.
Syntax: 
public BigInteger toBigInteger()
Parameters: This method does not accepts any parameters.Return value: This method returns the value of BigDecimal object converted to a BigInteger.
Examples:  
Input: (BigDecimal) 123.321
Output: (BigInteger) 123

Input: (BigDecimal) 123.001
Output: (BigInteger) 123
Below programs illustrate the working of the above-mentioned method: 
Program 1:  
Java
// Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG {     public static void main(String[] args)    {         // Assigning the BigDecimal b        BigDecimal b = new BigDecimal("123.321");         // Assigning the BigInteger value of  BigDecimal b to  BigInteger i        BigInteger i = b.toBigInteger();         // Print i value        System.out.println("BigInteger value of " + b + " is " + i);    }}
BigInteger value of 123.321 is 123
 
Program 2: 
Java
// Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG {     public static void main(String[] args)    {         // Assigning the BigDecimal b        BigDecimal b = new BigDecimal("123.001");         // Assigning the BigInteger value of  BigDecimal b to  BigInteger i        BigInteger i = b.toBigInteger();         // Printing i value        System.out.println("BigInteger value of " + b + " is " + i);    }}
BigInteger value of 123.001 is 123
 
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toBigInteger() 
prachisoda1234
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
How to Zoom with Axes3D in Matplotlib?

To zoom with Axes3D, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Get 3D axes object using Axes3D(fig) method.
Plot x, y and z data points using scatter() method.
To display the figure, use show() method.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

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

fig = plt.figure()
ax = Axes3D(fig)
x = [2, 4, 6, 3, 1]
y = [1, 6, 8, 1, 3]
z = [3, 4, 10, 3, 1]

ax.scatter3D(x, y, z, c=z, alpha=1, marker='d', s=150)
plt.show()
C library function - malloc()

The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it.
Following is the declaration for malloc() function.
void *malloc(size_t size)
size − This is the size of the memory block, in bytes.
size − This is the size of the memory block, in bytes.
This function returns a pointer to the allocated memory, or NULL if the request fails.
The following example shows the usage of malloc() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to get the first day of the current month in MySQL?

With the help of following MySQL query, we can get the first day of the current month −
mysql> SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))-
1 DAY) AS 'FIRST DAY OF CURRENT MONTH';
+----------------------------+
| FIRST DAY OF CURRENT MONTH |
+----------------------------+
| 2017-10-01                 |
+----------------------------+
1 row in set (0.00 sec)
What is Syntax Tree?

tree in which each leaf node describes an operand & each interior node an operator. The syntax tree is shortened form of the Parse Tree.
Example1 − Draw Syntax Tree for the string a + b ∗ c − d.
Rules for constructing a syntax tree
Each node in a syntax tree can be executed as data with multiple fields. In the node for an operator, one field recognizes the operator and the remaining field includes a pointer to the nodes for the operands. The operator is known as the label of the node. The following functions are used to create the nodes of the syntax tree for the expressions with binary operators. Each function returns a pointer to the recently generated node.
mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right.
mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right.
mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier.
mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier.
mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively.
mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively.
p1− mkleaf (id, entry a);
p2− mkleaf (num, 4);
p3− mknode ( ′−′, p1, p2)
p4− mkleaf(id, entry c)
p5− mknode(′+′, p3, p4);
The tree is generated in a bottom-up fashion. The function calls mkleaf (id, entry a) and mkleaf (num 4) construct the leaves for a and 4. The pointers to these nodes are stored using p1and p2. The call mknodes (′−′, p1, p2 ) then make the interior node with the leaves for a and 4 as children. The syntax tree will be
Syntax Directed Translation of Syntax Trees
Node (+, E(1), VAL, E(2). VAL) will create a node labeled +.
E(1). VAL &E(2). VAL are left & right children of this node.
Similarly, Node (∗, E(1). VAL, E(2). VAL) will make the syntax as −
Function UNARY (−, E(1). VAL)will make a node – (unary minus) & E(1). VAL will be the only child of it.
Function LEAF (id) will create a Leaf node with label id.
Example2 − Construct a syntax tree for the expression.
a = b ∗ −c + d
Solution
Example3 − Construct a syntax tree for a statement.
If a = b then b = 2 * c
Solution
Example4 − Consider the following code. Draw its syntax Tree
If x > 0 then x = 2 * (a + 1) else x = x + 1.
Example5 − Draw syntax tree for following arithmetic expression a * (b + c) – d /2. Also, write given expression in postfix form.
Postfix Notation
a b c + * d 2 / -
What are literals in Java?

A literal is a source code representation of a fixed value. They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these number systems for literals. For example −
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are −
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";
Binary Search


When the list is sorted we can use the binary search technique to find items on the list. In this procedure, the entire list is divided into two sub-lists. If the item is found in the middle position, it returns the location, otherwise jumps to either left or right sub-list and do the same process again until finding the item or exceed the range.
Time Complexity: O(1) for the best case. O(log2 n) for average or worst case.
Space Complexity: O(1) 
Input: 
A sorted list of data: 12 25 48 52 67 79 88 93
The search key 79
Output:
Item found at location: 5
binarySearch(array, start, end, key)
Input − An sorted array, start and end location, and the search key
Output − location of the key (if found), otherwise wrong location.
Begin
   if start <= end then
      mid := start + (end - start) /2
      if array[mid] = key then
         return mid location
      if array[mid] > key then
         call binarySearch(array, mid+1, end, key)
      else when array[mid] < key then
         call binarySearch(array, start, mid-1, key)
   else
      return invalid location
End
#include<iostream>
using namespace std;

int binarySearch(int array[], int start, int end, int key) {
   if(start <= end) {
      int mid = (start + (end - start) /2); //mid location of the list
      if(array[mid] == key)
         return mid;
      if(array[mid] > key)
         return binarySearch(array, start, mid-1, key);
         return binarySearch(array, mid+1, end, key);
   }
   return -1;
}

int main() {
   int n, searchKey, loc;
   cout << "Enter number of items: ";
   cin >> n;

   int arr[n]; //create an array of size n
   cout << "Enter items: " << endl;

   for(int i = 0; i< n; i++) {
      cin >> arr[i];
   }

   cout << "Enter search key to search in the list: ";
   cin >> searchKey;

   if((loc = binarySearch(arr, 0, n, searchKey)) >= 0)
      cout << "Item found at location: " << loc << endl;
   else
      cout << "Item is not found in the list." << endl;
}
Enter number of items: 8
Enter items:
12 25 48 52 67 79 88 93
Enter search key to search in the list: 79
Item found at location: 5
tar - Unix, Linux Command

Operations: 
[-]A --catenate --concatenate 
[-]c --create 
[-]d --diff --compare 
[-]r --append 
[-]t --list 
[-]u --update 
[-]x --extract --get 
--delete 


Common Options: 
-C, --directory DIR 
-f, --file F 
-j, --bzip2 
-p, --preserve-permissions 
-v, --verbose 
-z, --gzip 


All Options: 
[
--atime-preserve ]
[
-b, --blocking-factor N ]
[
-B, --read-full-records ]
[
--backup BACKUP-TYPE ]
[
--block-compress ]
[
-C, --directory DIR ]
[
--check-links ]
[
--checkpoint ]
[
-f, --file [HOSTNAME:]F ]
[
-F, --info-script F --new-volume-script F ]
[
--force-local ]
[
--format FORMAT ]
[
-g, --listed-incremental F ]
[
-G, --incremental ]
[
--group GROUP ]
[
-h, --dereference ]
[
--help ]
[
-i, --ignore-zeros ]
[
--ignore-case ]
[
--ignore-failed-read ]
[
--index-file FILE ]
[
-j, --bzip2 ]
[
-k, --keep-old-files ]
[
-K, --starting-file F ]
[
--keep-newer-files ]
[
-l, --one-file-system ]
[
-L, --tape-length N ]
[
-m, --touch, --modification-time ]
[
-M, --multi-volume ]
[
--mode PERMISSIONS ]
[
-N, --after-date DATE, --newer DATE ]
[
--newer-mtime DATE ]
[
--no-anchored ]
[
--no-ignore-case ]
[
--no-recursion ]
[
--no-same-permissions ]
[
--no-wildcards ]
[
--no-wildcards-match-slash ]
[
--null ]
[
--numeric-owner ]
[
-o, --old-archive, --portability, --no-same-owner ]
[
-O, --to-stdout ]
[
--occurrence[=NUMBER] ]
[
--overwrite ]
[
--overwrite-dir ]
[
--owner USER ]
[
-p, --same-permissions, --preserve-permissions ]
[
-P, --absolute-names ]
[
--pax-option KEYWORD-LIST ]
[
--posix ]
[
--preserve ]
[
--acls ]
[
--selinux ]
[
--xattrs ]
[
--no-acls ]
[
--no-selinux ]
[
--no-xattrs ]
[
-R, --block-number ]
[
--record-size SIZE ]
[
--recursion ]
[
--recursive-unlink ]
[
--remove-files ]
[
--rmt-command CMD ]
[
--rsh-command CMD ]
[
-s, --same-order, --preserve-order ]
[
-S, --sparse ]
[
--same-owner ]
[
--show-defaults ]
[
--show-omitted-dirs ]
[
--strip-components NUMBER, --strip-path NUMBER (1) ]
[
--suffix SUFFIX ]
[
-T, --files-from F ]
[
--totals ]
[
-U, --unlink-first ]
[
--use-compress-program PROG ]
[
--utc ]
[
-v, --verbose ]
[
-V, --label NAME ]
[
--version ]
[
--volno-file F ]
[
-w, --interactive, --confirmation ]
[
-W, --verify ]
[
--wildcards ]
[
--wildcards-match-slash ]
[
--exclude PATTERN ]
[
-X, --exclude-from FILE ]
[
-Z, --compress, --uncompress ]
[
-z, --gzip, --gunzip, --ungzip ]
[
-[0-7][lmh] ]


(1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components

v7 - Unix V7
oldgnu - GNU tar <=1.12
gnu - GNU tar 1.13
ustar - POSIX.1-1988
posix - POSIX.1-2001


(1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components

Debian Linux http://www.debian.org/
Mike Frysinger <vapier@gentoo.org>


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
exit(), abort() and assert() in C/C++

The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It is declared in “stdlib.h” header file. It does not return anything.
Here is the syntax of exit() in C language,
void exit(int status_value);
Here,
status_value − The value which is returned to parent process.
Here is an example of exit() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int x = 10;
   printf("The value of x : %d\n", x);
   exit(0);
   printf("Calling of exit()");
   return 0;
}
The value of x : 10
In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the printf(). The calling of exit() is as follows −
int x = 10;
printf("The value of x : %d\n", x);
exit(0)
The function abort() terminates the execution abnormally. It is suggested to not to use this function for termination. It is declared in “stdlib.h” header file.
Here is the syntax of abort() in C language,
void abort(void);
Here is an example of abort() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int a = 15;
   printf("The value of a : %d\n", a);
   abort();
   printf("Calling of abort()");
   return 0;
}
Here is the output,
The value of a : 15
In the above program, a variable ‘a’ is initialized with the value and printed. As the abort() is called, it terminates the execution immediately but abnormally. The calling of abort() is as follows.
int a = 15;
printf("The value of a : %d\n", a);
abort();
The function assert() is declared in “assert.h” header file. It evaluates the expressions given as argument. If expression is true, it does nothing. If expression is false, it abort the execution.
Here is the syntax of assert() in C language,
void assert(int exp);
Here.
exp − The expression you want to evaluate.
Here is an example of assert() in C language,
 Live Demo
#include <stdio.h>
#include <assert.h>
int main() {
   int a = 15;
   printf("The value of a : %d\n", a);
   assert(a!=15);
   printf("Calling of assert()");
   return 0;
}
The value of a : 15
main: main.c:9: main: Assertion `a!=15' failed.
In the above program, a variable ‘a’ is initialized with a value. The value of variable is printed and assert() function is called. As assert() is called, it evaluates the expression that ‘a’ is not equal to 15 which is false that is why it aborts the execution and shows an error.
int a = 15;
printf("The value of a : %d\n", a);
assert(a!=15);
Java - atan2() Method

The method converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
double atan2(double y, double x)

Here is the detail of parameters −
X − X co-ordinate in double data type.
X − X co-ordinate in double data type.
Y − Y co-ordinate in double data type.
Y − Y co-ordinate in double data type.
This method returns theta from  polar coordinate (r, theta).
This method returns theta from  polar coordinate (r, theta).
public class Test { 

   public static void main(String args[]) {
      double x = 45.0;
      double y = 30.0;

      System.out.println( Math.atan2(x, y) );
   }
}
This will produce the following result −
0.982793723247329


    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
How to disable the back button in android while logging out the application using Kotlin?

This example demonstrates how to disable the back button in android while logging out the application using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   android:padding="16dp"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:src="@drawable/image" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
   }
   override fun onBackPressed() {
      Toast.makeText(applicationContext, "Disabled Back Press", Toast.LENGTH_SHORT).show()
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen