code-rag-bench/online-tutorials huggingface dataset:
numpy.around() in Python - GeeksforGeeks

29 Nov, 2018
numpy.around(arr, decimals = 0, out = None) : This mathematical function helps user to evenly round array elements to the given number of decimals.
Parameters :
array : [array_like] Input array.decimal : [int, optional] Decimal places we want to round off.
Default = 0. In case of -ve decimal, it specifies the n0. of positions to the left of the decimal point.
out : [optional] Output resulted array
Return :
An array with all array elements being rounded off,
having same type as input 
 Code #1 : Working
# Python program explaining# around() function  import numpy as np  in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array)  round_off_values = np.around(in_array)print ("\nRounded values : \n", round_off_values)    in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array)  round_off_values = np.around(in_array)print ("\nRounded values : \n", round_off_values)  in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array)  round_off_values = np.around(in_array, decimals = 3)print ("\nRounded values : \n", round_off_values)
Output :
Input array : 
 [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values : 
 [  0.   2.   2.   4.   4.  10.]

Input array : 
 [0.53, 1.54, 0.71]

Rounded values : 
 [ 1.  2.  1.]

Input array : 
 [0.5538, 1.33354, 0.71445]

Rounded values : 
 [ 0.554  1.334  0.714]
 Code 2 : Working
# Python program explaining# around() function  import numpy as np  in_array = [1 ,4, 7, 9, 12]print ("Input array : \n", in_array)  round_off_values = np.around(in_array)print ("\nRounded values : \n", round_off_values)    in_array = [133 ,344, 437, 449, 12]print ("\nInput array : \n", in_array)  round_off_values = np.around(in_array, decimals = -2)print ("\nRounded values upto 2: \n", round_off_values)  in_array = [133 ,344, 437, 449, 12]print ("\nInput array : \n", in_array)  round_off_values = np.around(in_array, decimals = -3)print ("\nRounded values upto 3: \n", round_off_values)
Output :
Input array : 
 [1, 4, 7, 9, 12]

Rounded values : 
 [ 1  4  7  9 12]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 2: 
 [100 300 400 400   0]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 3: 
 [0 0 0 0 0]

 References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.around.html#numpy.around.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert a String to Integer Array in C/C++

In this tutorial, we will be discussing a program to understand how to convert a string into integer array in C/C++.
For this we will create a new array. Traverse through the given string, if the character is a comma “,”, we move on to the next character else add it to the new array.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//converting string to integer array
void convert_array(string str){
   int str_length = str.length();
   int arr[str_length] = { 0 };
   int j = 0, i, sum = 0;
   //traversing the string
   for (i = 0; str[i] != '\0'; i++) {
      if (str[i] == ', ') {
         j++;
      }
      else {
         arr[j] = arr[j] * 10 + (str[i] - 48);
      }
   }
   cout << "arr[] = ";
   for (i = 0; i <= j; i++) {
      cout << arr[i] << " ";
      sum += arr[i];
   }
   cout << "\nSum of array is = " << sum << endl;
}
int main(){
   string str = "2, 6, 3, 14";
   convert_array(str);
   return 0;
}
arr[] = 1569522526
Sum of array is = 1569522526
ES6 - Array.find

This function returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
Given below is the syntax for the array method find(), where, thisArg is an optional object to use as this when executing the callback and callback is the function to execute on each value in the array, taking three arguments as follows −
element − The current element being processed in the array.
element − The current element being processed in the array.
index − This is optional; refers to the index of the current element being processed in the array.
index − This is optional; refers to the index of the current element being processed in the array.
array − This is optional; the array on which find was called.
array − This is optional; the array on which find was called.
arr.find(callback(element[, index[, array]])[, thisArg])

<script>
   //find
   const products = [{name:'Books',quantity:10},
      {name:'Pen',quantity:20},
      {name:"Books",quantity:30}
   ]
   console.log( products.find(p=>p.name==="Books"))
</script>
The output of the above code will be as mentioned below −
{name: "Books", quantity: 10}


    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
Backward iteration in Python

Sometimes we need to go through the elements of a list in backward order. To achieve this we need to read the last element first and then the last but one and so on till the element at index 0. Various python programming features can be used to achieve this.
We are using the range function but starting with the position -1. This value helps us read the list from the last index value also we iterate through steps of -1. In the below example we start at a position which is measured by taking the length of the list and then taking -1 steps starting from the last position.
list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in range( len(list) - 1, -1, -1) :
   print(list[i])
Running the above code gives us the following result −
Thu
Wed
Tue
Mon
This method involves slicing the list which starts from the position -1 and go backwards till the first position. We use a for loop with an iterator used as the index of the element in the list.
list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in list[::-1]:
   print(i)
Running the above code gives us the following result −
Thu
Wed
Tue
Mon
The reversed() function is very straight forward it's simply picks the elements and prints them in the reverse order.
list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in reversed(list) :
   print(i)
Running the above code gives us the following result −
Thu
Wed
Tue
Mon
Create a Data Frame of all the Combinations of Vectors passed as Argument in R Programming - expand.grid() Function - GeeksforGeeks

05 Jun, 2020
expand.grid() function in R Language is used to create a data frame with all the values that can be formed with the combinations of all the vectors or factors passed to the function as argument.
Syntax: expand.grid(...)
Parameters:...: Vector1, Vector2, Vector3, ...
Example 1:
# R program to create a dataframe# with combination of vectors  # Creating vectorsx1 <- c("abc", "cde", "def")x2 <- c(1, 2, 3)x3 <- c("M", "F")  # Calling expand.grid() Functionexpand.grid(x1, x2, x3)
Output:
   Var1 Var2 Var3
1   abc    1    M
2   cde    1    M
3   def    1    M
4   abc    2    M
5   cde    2    M
6   def    2    M
7   abc    3    M
8   cde    3    M
9   def    3    M
10  abc    1    F
11  cde    1    F
12  def    1    F
13  abc    2    F
14  cde    2    F
15  def    2    F
16  abc    3    F
17  cde    3    F
18  def    3    F

Example 2:
# R program to create a dataframe# with combination of vectors  # Creating vectorsx1 <- c("abc", "cde", "def")x2 <- c(1, 2, 3)x3 <- c("M", "F")  # Calling expand.grid() Functionexpand.grid(x1, x3)
Output:
  Var1 Var2
1  abc    M
2  cde    M
3  def    M
4  abc    F
5  cde    F
6  def    F

R DataFrame-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
Conversion constructor in C++?

In this section we will see what is the conversion constructor in C++ class. A
constructor is a special type of function of class. It has some unique property like, its
name will be same as class name, it will not return any value etc. The constructors
are used to construct objects of a class. Sometimes constructors may take some
arguments, or sometimes it does not take arguments.
When a constructor takes only one argument then this type of constructors
becomes conversion constructor. This type of constructor allows automatic
conversion to the class being constructed.
 Live Demo
#include<iostream>
using namespace std;
class my_class{
   private:
      int my_var;
   public:
      my_class(int x) {
         this->my_var = x; //set the value of my_var
         using parameterized constructor
      }
      void display() {
         cout << "The value of my_var is: " << my_var <<endl;
      }
};
int main() {
   my_class my_obj(10);
   my_obj.display();
   my_obj = 50; //here the conversion constructor is called
   my_obj.display();
}
The value of my_var is: 10
The value of my_var is: 50
How do we assign values to variables in a list using a loop in Python?

Python’s built-in list class has append() method. We can get user input and add it to list till user presses Enter key. An infinite while loop contains input() function and append() method
L=[]
while True:
  item=input("enter new item")
  if item=='':
    break
  L.append(item)
print ("List : ",L)
Is it possible to have multiple try blocks with only one catch block in java?

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: "+c);
   }
}
Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.
The following Java program tries to employ single catch block for multiple try blocks.
class ExceptionExample{
   public static void main(String args[]) {
      int a,b;
      try {
         a=Integer.parseInt(args[0]);
         b=Integer.parseInt(args[1]);
      }
      try {
         int c=a/b;
         System.out.println(c);
      }catch(Exception ex) {
         System.out.println("Please pass the args while running the program");
      }
   }
}
ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations
   try {
   ^
1 error
VBScript Class Objects

Class is a construct that is used to define a unique type. Like Object Oriented Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing COM objects with VB.
Class is simply the template for an object and we instantiate an object to access the properties and methods of it. Classes can contain variables, properties, methods or events.
VBScript classes are enclosed within Class .... End Class
'Defining the Class
Class classname 'Declare the object name
...
End Class

' Instantiation of the Class
Set objectname = new classname

Classes can contain variables, which can be of private or public. Variables within classes should follow VBScript naming conventions. By default, the variables in class are Public. That is why they can be accessed outside the class.
Dim var1 , var2.
Private var1 , var2.
Public var1 , var2.

Class properties, such as Property Let, which handles the process of data validation and assigning the new value to the private variable. Property set, which assigns the new property value to the private object variable.
Read-only properties have only a Property Get procedure while write-only properties (which are rare) have only a Property Let or a Property Set procedure.
In the below example, we are using Properties to wrap private variables.
Class Comp
   
   Private modStrType
   Private OS
 
   Public Property Let ComputerType(strType)
      modStrType = strType
   End Property
 
   Public Property Get ComputerType()
      ComputerType = modStrType
   End Property
 
   Public Property Set OperatingSystem(oObj)
      Set OS = oObj
   End Property
 
   Public Property Get OperatingSystem()
      Set OperatingSystem = OS
   End Property
 
End Class
Methods allow the class to perform the operation that the developer wants. The Methods are nothing but Functions or Subroutines.
In the below example, we are using Properties to wrap private variables.
Class Car
   
   Private Model
   Private Year
 
   Public Start()
      Fuel = 2.45
	   Pressure =  4.15
   End Function
 
End Class
There are two events that are automatically associated with every class by default. Class_Initialize and Class_Terminate.
Class_Initialize is triggered whenever you instantiate an object based on the class. Class_Terminate event is fired when the object goes out of scope or when the object is set to Nothing.
In the below example, we will make you understand how the events work in VBScript.
'Instantation of the Object
Set objectname = New classname 
   
Private Sub Class_Initialize(  )
	Initalization code goes here
End Sub

'When Object is Set to Nothing
Private Sub Class_Terminate(  )
	Termination code goes here
End Sub

    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Wrap Strings of Text in Bootstrap Navbar

To wrap strings of text in an element using the class .navbar-text.
You can try to run the following code to set text in Bootstrap Navbar −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class = "navbar navbar-default" role = "navigation">
         <div class = "navbar-header">
            <a class = "navbar-brand" href = "#">Demo</a>
         </div>
         <div>
            <p class = "navbar-text">Copyright © 2018</p>
         </div>
      </nav>
   </body>
</html>
How can we create a MySQL view by using data from multiple tables?

MySQL UNION operator can combine two or more result sets hence we can use UNION operator to create a view having data from multiple tables. To understand this concept we are using the base tables ‘Student_info’ and ‘Student_detail’ having the following data −
mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
+------+---------+------------+------------+
6 rows in set (0.00 sec)

mysql> Select * from Student_detail;
+-----------+-------------+------------+
| Studentid | StudentName | address    |
+-----------+-------------+------------+
|       100 | Gaurav      | Delhi      |
|       101 | Raman       | Shimla     |
|       103 | Rahul       | Jaipur     |
|       104 | Ram         | Chandigarh |
|       105 | Mohan       | Chandigarh |
+-----------+-------------+------------+
5 rows in set (0.00 sec)
The query below will create a view by using the data from both the above-mentioned tables −
mysql> Create or Replace View Info AS Select StudentName from Student_detail UNION Select Name From Student_info;
Query OK, 0 rows affected (0.10 sec)

mysql> select * from info;
+-------------+
| StudentName |
+-------------+
| Gaurav      |
| Raman       |
| Rahul       |
| Ram         |  
| Mohan       |
| YashPal     |
| Shyam       |
+-------------+
7 rows in set (0.00 sec)
The above result set has the combination of values from both the columns. If a value is repeating then it eliminates the duplicate values.
We can also stores all the values, duplicate one also by using the UNION ALL as in the following query −
mysql> Create or Replace View Info AS Select student name from Student_detail UNION ALL Select Name From Student_info;
Query OK, 0 rows affected (0.16 sec)

mysql> select * from info;
+-------------+
| StudentName |
+-------------+
| Gaurav      |
| Raman       |
| Rahul       |
| Ram         |
| Mohan       |
| YashPal     |
| Gaurav      |
| Raman       |
| Ram         |
| Shyam       |
| Mohan       |
+-------------+
11 rows in set (0.00 sec)
How to make a simple lollipop plot in Matplotlib?

To make a simple lollipop plot in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make an ordered dataframe, using sort_values().
Make an ordered dataframe, using sort_values().
Make a list in the range of dataframe index.
Make a list in the range of dataframe index.
Create a stem plot, using the ordered dataframe.
Create a stem plot, using the ordered dataframe.
Set xticks and labels using xticks() method.
Set xticks and labels using xticks() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd

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

df = pd.DataFrame({'group': list(map(chr, range(65, 85))), 'values': np.random.uniform(size=20)})

ordered_df = df.sort_values(by='values')

my_range = range(1, len(df.index) + 1)

plt.stem(ordered_df['values'])

plt.xticks(my_range, ordered_df['group'])

plt.show()
How you can get a true/false from a Python regular expressions?

When you use match and search methods of module re, if there is a match, it has bool value of True and if there is no match, you get None that has a bool value of False.
Match objects are always true, and None is returned if there is no match
>>> bool(re.search("def", "abcdefgh"))
True
>>> bool(re.search("rest", "pqrstuv"))
False
Blending two images with HTML5 canvas

To blend, you need to perform blending of two images in proportion 50-50.
Let us see how:
<img src="Tutorial1.jpg" id="Tutorial One">
<img src="Tutorial2.jpg" id="Tutorial Two">

<p>Blended image<br>
<canvas id="canvas"></canvas></p>

<script>
   window.onload = function () {
      var myImg1 = document.getElementById('myImg1');
      var myImg2 = document.getElementById('myImg2');
      var myCanvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");

      // width and height
      var w = img1.width;
      var h = img1.height;

      myCanvas.width = w;
      myCanvas.height = h;

      var pixels = 4 * w * h;
      ctx.drawImage(myImg1, 0, 0);

      var image1 = context.getImageData(0, 0, w, h);
      var imageData1 = image1.data;
      ctx.drawImage(myImg2, 0, 0);

      var image2 = context.getImageData(0, 0, w, h);
      var imageData2 = image2.data;

      while (pixels--) {
         imageData1[pixels] = imageData1[pixels] * 0.5 + imageData2[pixels] * 0.5;
      }
      image1.data = imageData1;
      ctx.putImageData(image1, 0, 0);
   };
</script>
How do I get the src of an image in Selenium?

We can get the source of an image in Selenium. An image in an html document has <img> tagname. Each image also has an attribute src which contains the source of image in the page.
To fetch any attribute in Selenium, we have to use the getAttribute() method. The method takes the attribute name as a parameter. So to get the src attribute, we have to write getAttribute("src").
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Imagesrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify image
      WebElement l =driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));
      //getAttribute() to get src of image
      System.out.println("Src attribute is: "+ l.getAttribute("src"));
      driver.quit();
   }
}
How to create a dynamic array of integers in C++ using the new keyword

In C++, a dynamic array can be created using new keyword and can be deleted it by using delete keyword.
Let us consider a simple example of it.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int i,n;
   cout<<"Enter total number of elements:"<<"\n";
   cin>>n;
   int *a = new int(n);
   cout<<"Enter "<<n<<" elements"<<endl;
   for(i = 0;i<n;i++) {
      cin>>a[i];
   }
   cout<<"Entered elements are: ";
   for(i = 0;i<n;i++) {
      cout<<a[i]<<" ";
   }
   cout<<endl;
   delete (a);
   return 0;
}
Enter total number of elements:7
Enter 7 elements
1 2 3 4 5 6 7
Entered elements are: 1 2 3 4 5 6 7
In this program, memory is allocated by declaring, int *a=new int(n), using new keyword. The occupied memory can be retrieved by calling delete (a).
Find maximum (or minimum) in Binary Tree in C++

In this problem, we are given a binary tree. Our task is to Find maximum (or minimum) in Binary Tree. 
Problem Description: We need to find the nodes of the binary tree that have maximum and minimum value in the binary tree.
Let’s take an example to understand the problem, 
Input: 
Output: max = 9 , min = 1
We need to find the max node of the binary tree. We will do this by traversing the pointer until we reach the leaf node and then find the maximum node of the tree.
Live Demo
#include <iostream>
using namespace std;

class Node {
   public:
      int data;
      Node *left, *right;
   
      Node(int data) {
         this->data = data;
         this->left = NULL;
         this->right = NULL;
      }
};

int findMaxNode(Node* root) {
   
   if (root == NULL)
      return -100;

   int maxVal = root->data;
   int leftMaxVal = findMaxNode(root->left);
   int rightMaxVal = findMaxNode(root->right);
   if (leftMaxVal > maxVal)
      maxVal = leftMaxVal;
   if (rightMaxVal > maxVal)
      maxVal = rightMaxVal;
   return maxVal;
}

int main() {
   
   Node* NewRoot = NULL;
   Node* root = new Node(5);
   root->left = new Node(3);
   root->right = new Node(2);
   root->left->left = new Node(1);
   root->left->right = new Node(8);
   root->right->left = new Node(6);
   root->right->right = new Node(9);
   cout<<"The Maximum element of Binary Tree is "<<findMaxNode(root) << endl;
   return 0;
}
The Maximum element of Binary Tree is 9
Fetching rows updated at timestamp older than 1 day in MySQL?

For this,yYou can use from_unixtime() along with now().
Let us create a table with some data type −
mysql> create table demo75
   -> (
   -> due_date int(11)
   -> );
Query OK, 0 rows affected, 1 warning (2.87
Insert some records into the table with the help of insert command −
mysql> insert into demo75 values(unix_timestamp("2020-01-10"));
Query OK, 1 row affected (0.46

mysql> insert into demo75 values(unix_timestamp("2020-11-19"));
Query OK, 1 row affected (0.59

mysql> insert into demo75 values(unix_timestamp("2020-12-18"));
Query OK, 1 row affected (0.44

mysql> insert into demo75 values(unix_timestamp("2020-11-10"));
Query OK, 1 row affected (0.70
Display records from the table using select statement −
mysql> select *from demo75;
This will produce the following output −
+------------+| due_date   |+------------+| 1578594600 |
| 1605724200 || 1608229800 |
| 1604946600 |+------------+
4 rows in set (0.00 sec)
+------------+
| due_date   |
+------------+
| 1605724200 |
| 1604946600 |
4 rows in set (0.00 sec)
Following is the query to fetch rows updated at a timestamp older than 1 day in MySQL −
mysql> select * from demo75
   -> where from_unixtime(due_date) < now() - interval 1 day;
This will produce the following output −
+------------+| due_date   |
+------------+| 1578594600 |
| 1604946600 |+------------+2 rows in set (0.00 sec)
+------------+
+------------+
| 1604946600 |
+------------+
2 rows in set (0.00 sec)
Tryit Editor v3.7

Tryit: HTML basic table
Java - String contentEquals() Method

This method returns true if and only if this String represents the same sequence of characters as specified in StringBuffer.
Here is the syntax of this method −
public boolean contentEquals(StringBuffer sb)

Here is the detail of parameters −
sb − the StringBuffer to compare.
sb − the StringBuffer to compare.
This method returns true if and only if this String represents the same sequence of characters as the specified in StringBuffer, otherwise false.
This method returns true if and only if this String represents the same sequence of characters as the specified in StringBuffer, otherwise false.
public class Test {

   public static void main(String args[]) {
      String str1 = "Not immutable";
      String str2 = "Strings are immutable";
      StringBuffer str3 = new StringBuffer( "Not immutable");

      boolean  result = str1.contentEquals( str3 );
      System.out.println(result);
	  
      result = str2.contentEquals( str3 );
      System.out.println(result);
   }
}
This will produce the following result −
true
false


    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
Declare variable as constant in C

Variables can be declared as constant using the const keyword or the #define preprocessor directive. Details about these are given as follows.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.
 Live Demo
#include <stdio.h>
int main() {
   const int a;
   const int b = 12;
   printf("The default value of variable a : %d", a);
   printf("\nThe value of variable b : %d", b);
   return 0;
}
The output of the above program is as follows.
The default value of variable a : 0
The value of variable b : 12
Variables can be declared as constants by using the #define preprocessor directive as it declares an alias for any value.
A program that demonstrates the declaration of constant variables in C using #define preprocessor directive is given as follows.
 Live Demo
#include <stdio.h>
#define num 25
int main() {
   printf("The value of num is: %d", num);
   return 0;
}
The output of the above program is as follows.
The value of num is: 25
Python - Filter Duplicate Words

Many times, we have a need of analysing the text only for the unique words present in the file. So, we need to eliminate the duplicate words from the text. This is achieved by using the word tokenization and set functions available in nltk. 
In the below example we first tokenize the sentence into words. Then we apply set() function which creates an unordered collection of unique elements. The result has unique words which are not ordered. 
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour." 

# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)

# Applying Set
no_order = list(set(nltk_tokens))

print no_order
When we run the above program, we get the following output −
['blue', 'Rainbow', 'is', 'Sky', 'colour', 'ocean', 'also', 'a', '.', 'The', 'has', 'the']

 To get the words after removing the duplicates but still preserving the order of the words in the sentence, we read the words and add it to list by appending it.
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour." 
# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)

ordered_tokens = set()
result = []
for word in nltk_tokens:
    if word not in ordered_tokens:
        ordered_tokens.add(word)
        result.append(word)
     
print result        

When we run the above program, we get the following output −
['The', 'Sky', 'is', 'blue', 'also', 'the', 'ocean', 'Rainbow', 'has', 'a', 'colour', '.']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
ISRO | ISRO CS 2018 | Question 53 - GeeksforGeeks

08 Jun, 2019
Consider the following C code segment
int f (int x)
{
      if (x < 1)  return 1;
      else return (f(x-1) + g(x))
}

int g (int x)
{
      if (x < 2) return 2;
      else return (f(x-1) + g(x/2));
}

Of the following, which best describes the growth of f(x) as a function of x?
(A) Linear(B) Exponential(C) Quadratic(D) CubicAnswer: (B)Explanation: f(n) = f(n-1) + g(n) ---- 1g(n) = f(n-1) + g(n/2) ---- 2
Putting the value of g(n) in equation 1,f(n) = 2*f(n-1) + g(n/2)
So, we can derive the below equation,f(n) > 2f(n-1)=> f(n) > 2*2*f(n-2) ---- because f(n) > 2*f(n-1), so, f(n-1) > 2*2*f(n-2).... so on=> f(n) > (2^n)f(1) --- here '^' denotes the exponent.So, f(n) > Theta(2^n)
So, option B is true, exponential growth for f(x).Quiz of this Question
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert dictionary object into string

21 Jul, 2021
Dictionary is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.Let’s see the different ways of changing dictionary into string.Methods #1: Using json.dumps() json.dumps() is an inbuilt function in json library.It has advantage over pickle because it has cross-platform support. 
Python3
# Python code to demonstrate# to convert dictionary into string# using json.dumps()  import json  # initialising dictionarytest1 = { "testname" : "akshat",          "test2name" : "manjeet",          "test3name" : "nikhil"}  # print original dictionaryprint (type(test1))print ("initial dictionary = ", test1)  # convert dictionary into string# using json.dumps()result = json.dumps(test1)  # printing result as stringprint ("\n", type(result))print ("final string = ", result)
 
initial dictionary = {‘testname’: ‘akshat’, ‘test2name’: ‘manjeet’, ‘test3name’: ‘nikhil’}
 
final string = {“testname”: “akshat”, “test2name”: “manjeet”, “test3name”: “nikhil”} 
  Methods #2: Using str() The str() function converts the specified value into a string.  
Python3
# Python code to demonstrate# to convert dictionary into string# using str()  # initialising dictionarytest1 = { "testname" : "akshat",          "test2name" : "manjeet",          "test3name" : "nikhil"}  # print original dictionaryprint (type(test1))print ("initial dictionary = ", test1)  # convert dictionary into string# using strresult = str(test1)  # print resulting stringprint ("\n", type(result))print ("final string = ", result)
 
initial dictionary = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’}
 
final string = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’} 
nidhi_biet
simmytarika5
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.idxmin()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.idxmin() function returns index of first occurrence of minimum over requested axis. While finding the index of the minimum value across any index, all NA/null values are excluded.
Syntax: DataFrame.idxmin(axis=0, skipna=True)
Parameters :axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiseskipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns : idxmin : Series
Example #1: Use idxmin() function to function to find the index of the minimum value along the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, 6],                   "B":[11, 2, 5, 8],                   "C":[1, 8, 66, 4]})  # Print the dataframedf
Now apply the idxmin() function along the index axis.
# applying idxmin() function.df.idxmin(axis = 0)
Output :
If we look at the values in the dataframe, we can verify the result returned by the function. The function returned a pandas series object containing the index of minimum value in each column.
 Example #2: Use idxmin() function to find the index of the minimum value along the column axis. The dataframe contains NA values.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, None],                    "B":[11, 2, None, 8],                    "C":[1, 8, 66, 4]})  # Skipna = True will skip all the Na values# find minimum along column axisdf.idxmin(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time.process_time() function in Python

18 Apr, 2019
time.process_time() function always returns the float value of time in seconds. Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
As time module provides various time-related functions. So it is necessary to import the time module otherwise it will through error because of the definition of time.process_time() is present in time module.
Example: Understand the usage of the process_time().
# Python program to show time by process_time() from time import process_time  # assigning n = 50 n = 50   # Start the stopwatch / counter t1_start = process_time()    for i in range(n):    print(i, end =' ')  print()   # Stop the stopwatch / countert1_stop = process_time()   print("Elapsed time:", t1_stop, t1_start)    print("Elapsed time during the whole program in seconds:",                                         t1_stop-t1_start) 
Output: 
process_time_ns():It always gives the integer value of time in nanoseconds. Similar to process_time() but return time as nanoseconds.This is only the basic difference.
Example: Understand the usage of the process_time_ns().
# Python program to show time by process_time_ns() from time import process_time_ns   n = 50   # Start the stopwatch / countert1_start = process_time_ns()    for i in range(n):    print(i, end =' ')   print()   # Stop the stopwatch / countert1_stop = process_time_ns()   print("Elapsed time:", t1_stop, t1_start)   print("Elapsed time during the whole program in nanoseconds:",                                            t1_stop-t1_start) 
Output:
Note: process_time() is very different from pref_counter(), as perf_counter() calculates the program time with sleep time and if any interrupt is there but process_counter only calculates the system and the CPU time during the process it not includes the sleep time.
Advantages of process_time() :1. process_time() provides the system and user CPU time of the current process.2. We can calculate float and integer both values of time in seconds and nanoseconds.3. Used whenever there is a need to calculate the time taken by the CPU for the particular process.
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Remove Duplicates From Array Using VBA in Excel?

09 Nov, 2021
Excel VBA code to remove duplicates from a given range of cells. In the below data set we have given a list of 15 numbers in “Column A” range A1:A15.  Need to remove duplicates and place unique numbers in column B.
Sample Data: Cells A1:A15
Sample Data
Final Output:
VBA Code to remove duplicates and place into next column (B)
Declare Variables:
'Variable Declarations
Dim nonDuplicate As Boolean, uNo As Integer, colA As Integer, colB As Integer
Always first value will be unique, So A1 place to cell B1
'Place first value to B1
Cells(1, 2).Value = Cells(1, 1).Value
Initialize variables:
'Initialize uNo = 1 since first number is already placed in column B; Assign True to the variable nonDuplicate

uNo = 1

nonDuplicate= True
Since the first number is already placed in cell B1, Loop starts from A2 to A15.  Take each number from Column A and check with Column B (unique range)
'Use for loop to check each number from A2 to A15 
For colA = 2 To 15
    For colB = 1 To uNo
if the number is already placed in column B.  Assign False to the “nonDuplicate” variable.
        If Cells(colA, 1).Value = Cells(colB, 2).Value Then
            nonDuplicate= False
        End If
“nonDuplicate” is True then place to column B and increase uNo by 1
    'if nonDuplicate is true, place cell value in column B and increase uNo = uNo + 1
    If nonDuplicate = True Then
        Cells(uNo + 1, 2).Value = Cells(colA, 1).Value
        uNo = uNo + 1
    End If
Reset “nonDuplicate” variable 
'reset nonDuplicate to True
nonDuplicate = True
Close for loop
Next colA
Follow the below steps to remove duplicates using Excel VBA:
Step 1: Add a shape (VBA Remove Duplicates) to your worksheet  
Step 2: Right-click on “VBA Remove Duplicates” and “Assign Macro..”
Step 3: Select “removeDuplicates”, you can see a list of macros available in your workbook
Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm
Step 5: Click “VBA Remove Duplicates” to execute VBA code and see the output
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Use Solver in Excel?
Macros in Excel
How to Find the Last Used Row and Column in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
Python Pandas – get_dummies() method

13 Oct, 2020
pandas.get_dummies() is used for data manipulation. It converts categorical data into dummy or indicator variables.
syntax:  pandas.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)
Parameters:
data: whose data is to be manipulated.
prefix: String to append DataFrame column names. Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame. Default value is None.
prefix_sep: Separator/delimiter to use if appending any prefix. Default is ‘_’
dummy_na: It adds a column to indicate NaN values, default value is false, If false NaNs are ignored.
columns: Column names in the DataFrame that needs to be encoded. Default value is None, If columns is None then all the columns with object or category dtype will be converted.
sparse: It  specify whether the dummy-encoded columns should be backed by a SparseArray (True) or a regular NumPy array (False). default value is False.
drop_first: Remove first level to get k-1 dummies out of k categorical levels.
dtype: Data type for new columns. Only a single dtype is allowed. Default value is np.uint8.
Returns: Dataframe (Dummy-coded data)
Example 1:
Python3
import pandas as pd con = pd.Series(list('abcba'))print(pd.get_dummies(con))
  Output:
Output 
 Example 2:
Python
import pandas as pdimport numpy as np  # listli = ['s', 'a', 't', np.nan]print(pd.get_dummies(li))
Output:
Nan column is not there as dummy_na is False by default
Example 3: (To get NaN column)
Python
import pandas as pdimport numpy as np  # listli = ['s', 'a', 't', np.nan]print(pd.get_dummies(li, dummy_na=True))
Output:
Example 4:
Python3
import pandas as pdimport numpy as np  # dictionarydiff = pd.DataFrame({'R': ['a', 'c', 'd'],                     'T': ['d', 'a', 'c'],                     'S_': [1, 2, 3]}) print(pd.get_dummies(diff, prefix=['column1', 'column2']))
Output:
arorakashish0911
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.expm1() in Python

29 Nov, 2018
numpy.expm1(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate exponential of all the elements subtracting 1 from all the input array elements.
Parameters :
array    : [array_like]Input array or object whose elements, we need to test.
out      : [ndarray, optional]Output array with same dimensions as Input array, 
           placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function. 
           It is used when we want to handle named argument in a function.
where    : [array_like, optional]True value means to calculate the universal 
           functions(ufunc) at that position, False value means to leave the 
           value in the output alone.

Return :
An array with exponential(all elements of input array) - 1. 

Code 1 : Working
# Python program explaining# expm1() function  import numpy as np  in_array = [1, 3, 5]print ("Input array : \n", in_array)  exp_values = np.exp(in_array)print ("\nExponential value of array element : "       "\n", exp_values)  expm1_values = np.expm1(in_array)print ("\n(Exponential value of array element) - (1) "       ": \n", expm1_values)
Output :
Input array : 
 [1, 3, 5]

Exponential value of array element : 
 [   2.71828183   20.08553692  148.4131591 ]

(Exponential value of array element) - (1) : 
 [   1.71828183   19.08553692  147.4131591 ]

 Code 2 : Graphical representation
# Python program showing# Graphical representation of # expm1() function  import numpy as npimport matplotlib.pyplot as plt  in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.expm1(in_array)  print("out_array : ", out_array)  y = [1, 1.2, 1.4, 1.6, 1.8, 2]plt.plot(in_array, y, color = 'blue', marker = "*")  # red for numpy.expm1()plt.plot(out_array, y, color = 'red', marker = "o")plt.title("numpy.expm1()")plt.xlabel("X")plt.ylabel("Y")plt.show()  
Output :out_array : [ 1.71828183 2.32011692 3.05519997 3.95303242 5.04964746 6.3890561 ]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.expm1.html#numpy.expm1.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Barchart with vertical labels in Python/Matplotlib

First, we can create bars using plt.bar and using xticks. Then, we can align the labels by setting the “vertical” or “horizontal” attributes in the “rotation” key.
Make lists, bars_heights, and bars_label, with numbers.
Make lists, bars_heights, and bars_label, with numbers.
Make a bar plot using bar() method, with bars_heights and length of bars_label.
Make a bar plot using bar() method, with bars_heights and length of bars_label.
Get or set the current tick locations and labels of the X-axis, using xticks() with rotation='vertical' and bars_label.
Get or set the current tick locations and labels of the X-axis, using xticks() with rotation='vertical' and bars_label.
To show the plot, use plt.show() method.
To show the plot, use plt.show() method.
from matplotlib import pyplot as plt

bars_heights = [14, 8, 10]
bars_label = ["A label", "B label", "C label"]

plt.bar(range(len(bars_label)), bars_heights)
plt.xticks(range(len(bars_label)), bars_label, rotation='vertical')
plt.show()
How to Install Matplotlib on Linux? - GeeksforGeeks

08 Sep, 2021
Matploptib is a low-level library of Python which is used for data visualization. It is easy to use and emulates MATLAB like graphs and visualization. This library is built on the top of NumPy arrays and consist of several plots like line chart, bar chart, histogram, etc. It provides a lot of flexibility but at the cost of writing more code.
Matplotlib is an overall package for creating static, animated, and interactive visualizations in Python. It literally opens up a whole new world of possibilities for you! Especially when it is used with Numpy or Pandas library, one can do unimaginable things. The plots give may give a new insight altogether. Now, the question arises i.e. How to make it running on your computer? But a more primary question would be, what are its pre-requisites or as we call it, dependencies for the software to run on your computer?
Dependencies:
Python (>= 3.6)
FreeType (>= 2.3)
libpng (>= 1.2)
NumPy (>= 1.11)
setuptools
cycler (>= 0.10.0)
dateutil (>= 2.1)
kiwisolver (>= 1.0.0)
pyparsing
We will use the pip command to install this module. If you do not have pip installed then refer to the article, Download and install pip Latest Version.
To install Matplotlib type the below command in the terminal:
pip install matplotlib
You will get the following message once the installation is complete:
Let’s see some examples of using matplotlib:
Example 1: Creating Line plots
Python3
# importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.plot(x,y) # function to show the plotplt.show()
 
 
Output:
 
 
Example 2: Creating Bar plots
 
Python3
# importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot the barplt.bar(x,y) # function to show the plotplt.show()
Output:
Example 3: Creating Scatter plots
Python3
# importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot scatterplt.scatter(x, y) # function to show the plotplt.show()
Output:
RajuKumar19
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to parse JSON Data into React Table Component ?
How to Install Selenium on MacOS?
How to Install Tkinter on MacOS?
How to write comments in ReactJS ?
Explain the purpose of render() in ReactJS
How to Find the Wi-Fi Password Using CMD in Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?