code-rag-bench/online-tutorials huggingface dataset:
Difference between HashMap and ConcurrentHashMap in Java

Following are the notable differences between HashMap and ConcurrentHashMap classes in Java.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tester {
   public static void main(String[] args) {
      List<String> arrayList = new ArrayList<>();
      arrayList.add("A");
      arrayList.add("B");
      arrayList.add("C");
      Iterator<String> iterator = arrayList.iterator();
      System.out.println(arrayList);
      while (iterator.hasNext()) {
         if (iterator.next().equals("C")) {
            //removal is allowed.
            iterator.remove();
         }
      }
      System.out.println(arrayList);
      List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
      copyOnWriteArrayList.add("A");
      copyOnWriteArrayList.add("B");
      copyOnWriteArrayList.add("C");
      Iterator<String> iterator1 = copyOnWriteArrayList.iterator();
      System.out.println(copyOnWriteArrayList);
      while (iterator1.hasNext()) {
         if (iterator1.next().equals("C")) {
            try{
               iterator1.remove();
            }catch(UnsupportedOperationException e){
               System.out.println("Removal not allowed.");
            }
         }
      }
      System.out.println(copyOnWriteArrayList);
   }
}
[A, B, C]
[A, B]
[A, B, C]
Removal not allowed.
[A, B, C]
Constructors in C++ - GeeksQuiz

02 Dec, 2021
Predict output of the following program 
C
ew_c_questiongeeksforgeeks 
new_c_quesgeeksforgeeks 
geeksforgeeks 
Depends on terminal configuration
See http://stackoverflow.com/questions/17236242/usage-of-b-and-r-in-c
Output of following program?  
C++
Compiler Error
Constructor called
None of these
Runtime Error
By default all members of a class are private. Since no access specifier is there for Point(), it becomes private and it is called outside the class when t1 is constructed in main.  
Point *t1, *t2;   // No constructor call
t1 = new Point(10, 15);  // Normal constructor call
t2 = new Point(*t1);   // Copy constructor call 
Point t3 = *t1;  // Copy Constructor call
Point t4;   // Normal Constructor call
t4 = t3;   // Assignment operator call 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
HackWithInfy - A Coding Competition by Infosys
Can we synchronize abstract methods in Java?

An abstract method is the one that does not have a body. It contains only a method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();
To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract.
 Live Demo
import java.io.IOException;
abstract class MyClass {
   public abstract void display();
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}
subclass implementation of the display method
Synchronization − If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access the same resource an issue occurs.
To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access.
synchronized (Lock1) {
   System.out.println("Thread 1: Holding lock 1...");
}
No, you can’t synchronize abstract methods in Java. When you synchronize a method that implies that you are synchronizing the code in it, i.e. when one thread is accessing the code of a synchronized method no other thread is allowed to access it. So synchronizing abstract methods doesn’t make sense, if you still try to do so a compile-time error will be generated.
import java.io.IOException;
public abstract class MyClass {
   public abstract synchronized void display();
}
MyClass.java:3: error: illegal combination of modifiers: abstract and synchronized
   public abstract synchronized void display();
                                     ^
1 error
Merge Pandas dataframe with a common column and set NaN for unmatched values

To merge two Pandas DataFrame with common column, use the merge() function and set the ON parameter as the column name. To set NaN for unmatched values, use the “how” parameter and set it left or right. That would mean, merging left or right.
At first, let us import the pandas library with an alias −
import pandas as pd
Let us create DataFrame1 −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)
Let us create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)
Now, merge DataFrames with common column Car. The left" “displays all the values of the left DataFrame and sets NaN for unmatched values from 2nd DataFrame −
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left")
Following is the code
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

print("DataFrame1 ...\n",dataFrame1)

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print("\nDataFrame2 ...\n",dataFrame2)

# merge DataFrames with common column Car and "left" sets NaN for unmatched values from second DataFrame
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left")
print("\nMerged data frame with common column...\n", mergedRes)


Following is the code −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame2 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2     Tesla        5000
3   Mustang        8000
4  Mercedes        9000
5    Jaguar        6000

Merged data frame with common column...
       Car   Units   Reg_Price
0      BMW     100      7000.0
1    Lexus     150      1500.0
2     Audi     110         NaN
3  Mustang      80      8000.0
4  Bentley     110         NaN
5   Jaguar      90      6000.0
Finding frequency in list of tuples in Python

Many different types of data container can get mixed up in python. A list can have elements each of which is a tuple. In this article we will take such a list and find the frequency of element in the tuples which are themselves elements of a list.
We apply a lambda function to count through each of the first element in the tuples present in the list. Then apply a map function to arrive at the total count of the element we are searching for.
 Live Demo
# initializing list of tuples
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]

# Given list
print("Given list of tuples : " ,listA)

# Frequency in list of tuples
Freq_res = list(map(lambda i: i[0], listA)).count('Apple')

# printing result
print("The frequency of element is : ",Freq_res)
Running the above code gives us the following result:
Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2
We can also implement Counter which will count the number of occurrences of an element. We use a for loop to go through each of the tuple present in the list.
 Live Demo
from collections import Counter

# initializing list of tuples
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]

# Given list
print("Given list of tuples : " ,listA)

# Frequency in list of tuples
Freq_res = Counter(i[0] for i in listA)['Apple']

# printing result
print("The frequency of element is : ",Freq_res)
Running the above code gives us the following result −
Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2
Delimiters in MySQL?

Delimiters can be used when you need to define the stored procedures, function as well as to create triggers. The default delimiter is semicolon.
You can change the delimiters to create procedures and so on. However, but if you are considering multiple statements, then you need to use different delimiters like $$ or //.
Here we have a table “GetRecordFromNow” wherein the following are the records −
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-12-07 22:30:18 |
| 2018-12-03 22:30:31 |
| 2018-12-02 22:30:41 |
| 2018-12-01 22:30:56 |
| 2018-12-03 22:31:04 |
+---------------------+
5 rows in set (0.00 sec)
The delimiter keyword is a type of function in MySQL client. Here is the demo of delimiter that calls the above table using delimiter −
mysql> delimiter //
mysql> create procedure DisplayALL()
   −> begin
   −> select *from GetRecordsFromNow;
   −> end
   −> //
Query OK, 0 rows affected (0.40 sec)

mysql> delimiter ;
mysql> call DisplayALL();
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-12-07 22:30:18 |
| 2018-12-03 22:30:31 |
| 2018-12-02 22:30:41 |
| 2018-12-01 22:30:56 |
| 2018-12-03 22:31:04 |
+---------------------+
5 rows in set (0.07 sec)

Query OK, 0 rows affected (0.10 sec)
Query deeply nested Objects in MongoDB

To query deeply nested objects, use dot(.) notation in MongoDB. Let us create a collection with documents −
> db.demo350.insertOne(
... {
...    id:101,
...    Name: "Chris",
...    details: [
...       {
...          _id: 1,
...          ClientNumber: "10001",
...          ClientDetails: [
.
...             {
...                Name:"David",
...                Age:29
...             },
...             {
...                Name:"Bob",
...                Age:31
...             }
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e553a68f8647eb59e5620b8")
}
> db.demo350.insertOne(
... {
...    id:102,
...    Name: "David",
...    details: [
...       {
...          _id: 2,
...          ClientNumber: "10002",
...          ClientDetails: [
...             {
...                Name:"Carol",
...                Age:42
...             },
...             {
...                Name:"John",
...                Age:37
...             }
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e553a8ff8647eb59e5620b9")
}
Display all documents from a collection with the help of find() method −
> db.demo350.find();
This will produce the following output −
{ "_id" : ObjectId("5e553a68f8647eb59e5620b8"), "id" : 101, "Name" : "Chris", "details" : [ { "_id" : 1, "ClientNumber" : "10001", "ClientDetails" : [ { "Name" : "David", "Age" : 29 }, { "Name" : "Bob", "Age" : 31 } ] } ] }
{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
Following is how to query deeply nested objects −
> db.demo350.find({"details.ClientDetails.Name":"John"});
This will produce the following output −
{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
Combine date and time column into a timestamp in MySQL?

To combine date and time column into a timestamp, you can use cast() function with concat().
The syntax is as follows −
select cast(concat(yourDateColumnName, ' ', yourTimeColumnName) as datetime) as anyVariableName from yourTableName;
In the above concept, you will use cast() when your date and time is in string format. The cast() function can be used only for datetime. To understand the above syntax, let us create a table.
The query to create a table is as follows −
mysql> create table DateAndTimeToTimestamp
   −> (
   −> Duedate date,
   −> DueTime time
   −> );
Query OK, 0 rows affected (0.51 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval 2 day),'10:30:02');
Query OK, 1 row affected (0.34 sec)

mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval -2 day),'12:20:45');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval 1 day),'01:32:42');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval -1 day),'14:25:58');
Query OK, 1 row affected (0.30 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from DateAndTimeToTimestamp;
The following is the output −
+------------+----------+
| Duedate    | DueTime  |
+------------+----------+
| 2018-12-16 | 10:30:02 |
| 2018-12-12 | 12:20:45 |
| 2018-12-15 | 01:32:42 |
| 2018-12-13 | 14:25:58 |
+------------+----------+
4 rows in set (0.00 sec)
Here is the query to combine date and time column into timestamp −
mysql> select concat(Duedate, ' ', DueTime) as timestampDemo from DateAndTimeToTimestamp;
The following is the output −
+---------------------+
| timestampDemo       |
+---------------------+
| 2018-12-16 10:30:02 |
| 2018-12-12 12:20:45 |
| 2018-12-15 01:32:42 |
| 2018-12-13 14:25:58 |
+---------------------+
4 rows in set (0.00 sec)
Assignment Operators in C

The following table lists the assignment operators supported by the C language −
Try the following example to understand all the assignment operators available in C −
#include <stdio.h>

main() {

   int a = 21;
   int c ;

   c =  a;
   printf("Line 1 - =  Operator Example, Value of c = %d\n", c );

   c +=  a;
   printf("Line 2 - += Operator Example, Value of c = %d\n", c );

   c -=  a;
   printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

   c *=  a;
   printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

   c /=  a;
   printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

   c  = 200;
   c %=  a;
   printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

   c <<=  2;
   printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

   c >>=  2;
   printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

   c &=  2;
   printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

   c ^=  2;
   printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

   c |=  2;
   printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - =  Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2

 Print
 Add Notes
 Bookmark this page
Python Program to Count the Number of Occurrences of an Element in the Linked List without using Recursion

When it is required to count the number of occurrences of a specific element in a linked list without using recursion, a method to add elements to the linked list, a method to display the elements of the linked list, and a method to count the occurrences of a value are defined.
Below is a demonstration for the same −
 Live Demo
class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class my_linked_list:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_value(self, my_data):
      if self.last_node is None:
         self.head = Node(my_data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(my_data)
         self.last_node = self.last_node.next

   def print_it(self):
      curr = self.head
      while curr:
         print(curr.data)
         curr = curr.next

   def count_val(self, key):
      curr = self.head
      my_count = 0
      while curr:
         if curr.data == key:
            my_count = my_count + 1
         curr = curr.next
      return my_count

my_instance = my_linked_list()
my_list = [56, 43, 70, 67, 89, 91, 70, 23, 46, 70]
for elem in my_list:
   my_instance.add_value(elem)
print("The linked list contains the below elements:")
my_instance.print_it()

key_val = int(input('Enter the data item: '))
count_val = my_instance.count_val(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))
The linked list contains the below elements:
56
43
70
67
89
91
70
23
46
70
Enter the data item: 70
70 occurs 3 time(s) in the list.
The ‘Node’ class is created.
The ‘Node’ class is created.
Another ‘my_linked_list’ class with required attributes is created.
Another ‘my_linked_list’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.
Another method named ‘add_value’ is defined, that is used to add data to the linked list.
Another method named ‘add_value’ is defined, that is used to add data to the linked list.
Another method named ‘print_it’ is defined, that iterates over the list, and prints the elements.
Another method named ‘print_it’ is defined, that iterates over the list, and prints the elements.
Another method named ‘count_val’ is defined that is used to find the frequency of occurrence of a specific element in the linked list.
Another method named ‘count_val’ is defined that is used to find the frequency of occurrence of a specific element in the linked list.
An object of the ‘my_linked_list’ class is created.
An object of the ‘my_linked_list’ class is created.
The count_val method is called, to find the frequency of a specific element.
The count_val method is called, to find the frequency of a specific element.
This output is displayed on the console.
This output is displayed on the console.
C++ | Inheritance | Question 7 - GeeksforGeeks

28 Jun, 2021
#include<iostream>using namespace std;  class Base{public:    void show()    {        cout<<" In Base ";    }};  class Derived: public Base{public:    int x;    void show()    {        cout<<"In Derived ";    }    Derived()    {        x = 10;    }};  int main(void){    Base *bp, b;    Derived d;    bp = &d;    bp->show();    cout << bp->x;        return 0;}
(A) Compiler Error in line ” bp->show()”(B) Compiler Error in line ” cout <x”(C) In Base 10(D) In Derived 10Answer: (B)Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object. Additional attributes of a derived class object are sliced off to form the base class object.Quiz of this Question
Pallabi Mondal
C++-Inheritance
Inheritance
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
C++ | Exception Handling | Question 3
C++ | const keyword | Question 2
C++ | Operator Overloading | Question 5
C++ | new and delete | Question 4
C++ | Virtual Functions | Question 4
Math.Atan2() Method in C#

The Math.Atan2() method in C# is used to return the angle whose tangent is the quotient of two specified numbers.
Following is the syntax −
public static double Atan2 (double val1, double val2);
Above, val1 is the y coordinate, whereas val2 is the x coordinate.
Let us now see an example to implement Math.Atan2() method −
using System;
public class Demo {
   public static void Main(){
      double val1 = 3.0;
      double val2 = 1.0;
      double angle, radians;
      radians = Math.Atan2(val1, val2);
      angle = radians * (180/Math.PI);
      Console.WriteLine("Result = "+angle);
   }
}
This will produce the following output −
Result = 71.565051177078
Let us see another example to implement Math.Atan2() method −
using System;
public class Demo {
   public static void Main(){
      double val1 = 0;
      double val2 = 5;
      double angle, radians;
      radians = Math.Atan2(val1, val2);
      angle = radians * (180/Math.PI);
      Console.WriteLine("Result = "+angle);
   }
}
This will produce the following output −
Result = 0
How to convert an array to Set and vice versa in Java?

Array is a container which can hold a fix number of entities, which are of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index.
import java.util.Arrays;
public class ArrayExample {
   public static void main(String args[]) {
      Number integerArray[] = new Integer[3];
      integerArray[0] = 25;
      integerArray[1] = 32;
      integerArray[2] = 56;
      System.out.println(Arrays.toString(integerArray));
   }
}
[25, 32, 56]
Whereas a Set object is a collection (object) stores another objects, it does not allow duplicate elements and allows at most null value.
The Arrays class of the java.util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArrayToSet {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array to be created ::");
      int size = sc.nextInt();
      String [] myArray = new String[size];
      for(int i=0; i<myArray.length; i++){
         System.out.println("Enter the element "+(i+1)+" (String) :: ");
         myArray[i]=sc.next();
      }
      Set<String> set = new HashSet<>(Arrays.asList(myArray));
      System.out.println("Given array is converted to a Set");
      System.out.println("Contents of set ::"+set);
   }
}
Enter the size of the array to be created ::
4
Enter the element 1 (String) ::
Ram
Enter the element 2 (String) ::
Rahim
Enter the element 3 (String) ::
Robert
Enter the element 4 (String) ::
Rajeev
Given array is converted to a Set
Contents of set ::[Robert, Rahim, Rajeev, Ram]
The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. Use this method to convert a Set object to an array.
import java.util.HashSet;
import java.util.Set;
public class SetToArray {
   public static void main(String args[]){
      Set<String> set = new HashSet<String>();
      set.add("Apple");
      set.add("Orange");
      set.add("Banana");
      System.out.println("Contents of Set ::"+set);
      String[] myArray = new String[set.size()];
      set.toArray(myArray);
      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]);
      }
   }
}
Contents of Set ::[Apple, Orange, Banana]
Element at the index 1 is ::Apple
Element at the index 2 is ::Orange
Element at the index 3 is ::Banana
Tryit Editor v3.7

Tryit: Using the var() function
JavaScript | Text Formatting - GeeksforGeeks

05 Jun, 2020
JavaScript has many inbuilt features to format the text. Texts are the strings in javascript. There are many formatting styles like making text uppercase, lowercase, bold, italic. Each formatting style is given below with the example.
Making text UpperCase: It is used to convert the string to uppercase.
Javascript
let text = "geeks for geeks"console.log("text before formatting is " + text);text.toUpperCase()console.log("text after formatting is " + text);
Output:
Making text LowerCase: It is used to convert the string to lowercase.
Javascript
let text = "GEEKS FOR GEEKS"console.log("text before formatting is " + text);text.toLowerCase()console.log("text after formatting is " + text);
Output:
Use of Substr: It is used to take the substring from the string. The first parameter is the index from which the string has to start and the second parameter is the length of substring.
Note: Please note that the second parameter is not the index.
Javascript
let text = "GEEKS FOR GEEKS"text = text.substr(10, 5)console.log("substring is " + text);
Output:
Use of repeat: Use of repeat is done when we need to repeat a particular string or substring to be printed in a particular number of times.
Javascript
let text = 'geeks for geeks ';console.log(`string is repeated 2 times: ${text.repeat(2)}`);
Output:
Use of trim: It is used to remove the extra spaces around the string.
Note: It does not remove the spaces from between the text and words.
Javascript
let txt = '                  geeks for geeks            ';console.log(`string with no trailing spaces, ${txt.trim()}`);
Output:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Cells with Odd Values in a Matrix in C++

Suppose there are n and m which are the dimensions of a matrix. These are initialized by zeros. And indices are given where indices[i] = [ri, ci]. For each pair of [ri, ci] we have to increment all cells in row ri and column ci by 1. The output will be the number of cells with odd values in the matrix after applying the increment to all indices.
To solve this, we will follow these steps −
Initialize odd := 0, and x := row count of the matrix
create a matrix mat
for i in range 0 to xr = input[i, 0], c = input[i, 1],for j in range 0 to m – 1mat[r, j] := mat[r, j] + 1for j in range 0 to n – 1mat[j, c] := mat[j, c] + 1
r = input[i, 0], c = input[i, 1],
for j in range 0 to m – 1mat[r, j] := mat[r, j] + 1
mat[r, j] := mat[r, j] + 1
for j in range 0 to n – 1mat[j, c] := mat[j, c] + 1
mat[j, c] := mat[j, c] + 1
for i in range 0 to n – 1for j := 0 to m – 1odd := odd + mat[i, j] bitwise or with 1
for j := 0 to m – 1odd := odd + mat[i, j] bitwise or with 1
odd := odd + mat[i, j] bitwise or with 1
return odd
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
      int oddCells(int n, int m, vector<vector<int>>& in) {
      int odd = 0;
      int x = in.size();
      vector < vector <int> > mat(n, vector <int>(m));
      for(int i = 0; i < x ;i++){
         int r = in[i][0];
         int c = in[i][1];
         for(int j = 0; j < m; j++){
            mat[r][j]++;
         }
         for(int j = 0; j < n; j++){
            mat[j][c]++;
         }
      }
      for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++)odd += mat[i][j] & 1;
      }
      return odd;
   }
};
main(){
   Solution ob;
   vector<vector<int>> c = {{0,1},{1,1}};
   cout << ob.oddCells(2,3,c);
}
2
3
{{0,1},{1,1}}
6
What is the difference between MySQL TINYINT(2) vs TINYINT(1)?

The number 2 and 1 in TINYINT(2) vs TINYINT(1) indicate the display width. There is no difference between tinyint(1) and tinyint(2) except the width.
If you use tinyint(2) or even tinyint(1), the difference is the same. You can understand the above concept using zerofill option.
tinyint(1) zerofill
tinyint(2) zerofill
Let us create a table. The query to create a table is as follows −
mysql> create table tinyIntDemo
   -> (
   -> Number1 tinyint(1) zerofill,
   -> Number2 tinyint(2) zerofill
   -> );
Query OK, 0 rows affected (0.62 sec)
Insert record in the table using insert command. The query is as follows −
mysql> insert into tinyIntDemo values(1,1);
Query OK, 1 row affected (0.12 sec)
Display records from the table using select command. The query is as follows −
mysql> select *from tinyIntDemo;
The following is the output. Spot the difference between both in the below result −
+---------+---------+
| Number1 | Number2 |
+---------+---------+
|       1 |      01 |
+---------+---------+
1 row in set (0.00 sec)
Tryit Editor v3.7

Tryit: HTML table headers
C/C++ Program for Maximum height when coins are arranged in a triangle?

In this section, we will see one interesting problem. There are N coins. we have to find what is the max height we can make if we arrange the coins as pyramid. In this fashion, the first row will hold 1 coin, second will hold 2 coins and so on.
In the given diagram, we can see to make a pyramid of height three we need minimum 6 coins. We cannot make height 4 until we have 10 coins. Now let us see how to check the maximum height.
We can get the height by using this formula.
 Live Demo
#include<iostream>
#include<cmath>
using namespace std;
int getMaxHeight(int n) {
   int height = (-1 + sqrt(1 + 8 * n)) / 2;
   return height;
}
main() {
   int N;
   cout << "Enter number of coins: " ;
   cin >> N;
   cout << "Height of pyramid: " << getMaxHeight(N);
}
Enter number of coins: 13
Height of pyramid: 4
Java Regex - Example - Character \\ Match

The character \\ matches the backslash character present in a text.
The following example shows the usage of character matching.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\";
   private static final String INPUT = "dbca\\bcabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(Pattern.quote(REGEX));
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}
Let us compile and run the above program, this will produce the following result −
Match String start(): 4

 Print
 Add Notes
 Bookmark this page
Boolean Indexing in Pandas

Boolean indexing helps us to select the data from the DataFrames using a boolean vector. We need a DataFrame with a boolean index to use the boolean indexing. Let's see how to achieve the boolean indexing.
Create a dictionary of data.
Convert it into a DataFrame object with a boolean index as a vector.
Now, access the data using boolean indexing.
See the example below to get an idea.
import pandas as pd
# data
data = {
   'Name': ['Hafeez', 'Srikanth', 'Rakesh'],
   'Age': [19, 20, 19]
}
# creating a DataFrame with boolean index vector
data_frame = pd.DataFrame(data, index = [True, False, True])
print(data_frame)
If you run the above program, you will get the following results.
          Name   Age
True    Hafeez   19
False Srikanth   20
True    Rakesh   19
Now, we can access the DataFrame by passing booleans to the methods loc[], iloc[], ix[]. Let's see them all.
# accessing using .loc()
print(data_frame.loc[True])
If run the above code, you will get the following results.
       Name  Age
True Hafeez   19
True Rakesh   19
# accessing using .iloc()
print(data_frame.iloc[1]) # iloc methods takes only integers so, we are passing 1 i
nsted of True. Both are same.
If run the above code, you will get the following results.
Name Srikanth
Age 20
dtype: object
# accessing using .ix[]
# we can pass both boolean or integer values to .ix[]
print(data_frame.ix[True])
print()
print(data_frame.ix[1])
If run the above code, you will get the following results.
         Name Age
True   Hafeez 19
True   Rakesh 19

Name   Srikanth
Age       20
dtype: object
Another way to use the boolean index is to directly pass the boolean vector to the DataFrame. It will print all the rows with the value True. Let's see one example.
import pandas as pd
# data
data = {
   'Name': ['Hafeez', 'Srikanth', 'Rakesh'],
   'Age': [19, 20, 19]
}
# creating a DataFrame with boolean index vector
data_frame = pd.DataFrame(data)
print(data_frame)
If run the above code, you will get the following results.
      Name    Age
0   Hafeez    19
1 Srikanth    20
2   Rakesh    19
Now, we can pass the boolean vector to the DataFrame to access the data.
# passing boolean vector to data_frame index
print(data_frame[[True, True, False]])
If run the above code, you will get the following results. We got the row only that is True.
      Name Age
0   Hafeez 19
1 Srikanth 20
If you have any doubts about the Boolean index, let me know in the comment section.
Finding sum of digits of a number until sum becomes single digit in C++

In this tutorial, we are going to write a program that sums digits of the given number until it becomes a single digit. Let's see an example.
Input −4543
Output −7
Let's see the steps to solve the problem.
Initialize a number.
Initialize a number.
Initialize the sum to 0.
Initialize the sum to 0.
Iterate until the sum is less than 9.Add each digit of the number to the sum using modulo operator
Iterate until the sum is less than 9.
Add each digit of the number to the sum using modulo operator
Add each digit of the number to the sum using modulo operator
Print the sum
Print the sum
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void findTheSingleDigit(int n) {
   int sum = 0;
   while(n > 0 || sum > 9) {
      if(n == 0) {
         n = sum;
         sum = 0;
      }
      sum += n % 10;
      n /= 10;
   }
   cout << sum << endl;
}
int main() {
   int n = 4543;
   findTheSingleDigit(n);
   return 0;
}
you execute the above program, then you will get the following result.
7
We have another simple method to solve the problem. If the given number is divisible by 9, then the answer is 9. Else the number if n % 9.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void findTheSingleDigit(int n) {
   if (n == 0) {
      cout << 0;
   }
   else if (n % 9 == 0) {
      cout << 9 << endl;
   }
   else {
      cout << n % 9 << endl;
   }
}
int main() {
   int n = 4543;
   findTheSingleDigit(n);
   return 0;
}
If you run the above code, then you will get the following result.
7
If you have any queries in the tutorial, mention them in the comment section.
Java Program to create a new list with values from existing list with Lambda Expressions

To create a new list with values from existing list with Lambda Expressions, the following is an example.
Here, we are displaying the name of Employees. Therefore, we have created an Employee class as well −
List<Employee>emp = Arrays.asList(new Employee("Jack", 29, "South"), new Employee("Tom", 24, "North"), new Employee("Harry", 35, "West"),new Employee("Katie", 32, "East"));
Use Lambda to crate anew list from existing list with Lambda Expressions −
List<String>res = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList());
Let us see the complete example −
 Live Demo
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String args[]) {
      List<Employee>emp = Arrays.asList(new Employee("Jack", 29, "South"), new Employee("Tom", 24, "North"),
          new Employee("Harry", 35, "West"),new Employee("Katie", 32, "East"));
      List<String>res = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList());
      System.out.println("Employee Names = "+res);
   }
}
class Employee {
   private String emp_name;
   private int emp_age;
   private String emp_zone;
   public Employee(String emp_name, int emp_age, String emp_zone) {
      this.emp_name = emp_name;
      this.emp_age = emp_age;
      this.emp_zone = emp_zone;
   }
   public String displayEmpName() {
      return this.emp_name;
   }
}
Employee Names = [Jack, Tom, Harry, Katie]
VBA - Time Serial Function

The TimeSerial function returns the time for the specified hour, minute, and second values.
TimeSerial(hour,minute,second) 

Hour − A required parameter, which is an integer between 0 and 23 or any numeric expression.
Hour − A required parameter, which is an integer between 0 and 23 or any numeric expression.
Minute − A required parameter, which is an integer between 0 and 59 or any numeric expression.
Minute − A required parameter, which is an integer between 0 and 59 or any numeric expression.
Second − A required parameter, which is an integer between 0 and 59 or any numeric expression.
Second − A required parameter, which is an integer between 0 and 59 or any numeric expression.
Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox(TimeSerial(20,1,2))
   msgbox(TimeSerial(0,59,59))
   msgbox(TimeSerial(7*2,60/3,15+3))
End Sub
When you execute the above function, it produces the following output.
8:01:02 PM
12:59:59 AM
2:20:18 PM


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
HTML | <frameset> rows Attribute - GeeksforGeeks

28 May, 2019
The HTML <frameset> rows Attribute is used to specify the size and the number of rows in a frameset. The height of each frame is separated by a comma.
Syntax:
<frameset rows="pixels|%|*">
Attribute Values:
pixels: The height of row is set in terms of pixels. Example: “50px” or “50”.
%: The height of row is set in terms of percentage. Example “70%”.
*: The height of row is set to all available space.
Note: The <frameset> rows Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML frameset rows Attribute</title></head>  <!-- frameset attribute starts here --><frameset rows="20%, 60%, 20%">    <frame name="top" src="attr1.png" />    <frame name="main" src="gradient3.png" />    <frame name="bottom" src="col_last.png" /></frameset><!-- frameset attribute ends here -->  </html>
Output:
Supported Browsers: The browser supported by HTML <frameset> rows Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
Perl foreach Loop

The foreach loop iterates over a list value and sets the control variable (var) to be each element of the list in turn −
The syntax of a foreach loop in Perl programming language is −
foreach var (list) {
...
}

#!/usr/local/bin/perl
 
@list = (2, 20, 30, 40, 50);

# foreach loop execution
foreach $a (@list) {
   print "value of a: $a\n";
}
When the above code is executed, it produces the following result −
value of a: 2
value of a: 20
value of a: 30
value of a: 40
value of a: 50


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
SQLSERVER Tryit Editor v1.0

SELECT CAST('2017-08-25' AS datetime);
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to make a text italic using JavaScript?

To make text italic using JavaScript, use the italics() method. This method causes a string to be italic as if it were in an <i> tag.
You can try to run the following code to make a text italic with JavaScript −
Live Demo
<html>
   <head>
      <title>JavaScript String italics() Method</title>
   </head>

   <body>
      <script>
         var str = new String("Demo Text");
         document.write(str.italics());
         alert(str.italics());
      </script>
   </body>
</html>
C++ Memory Library - auto_ptr

It an automatic Pointer and it provides a limited garbage collection facility for pointers, by allowing pointers to have the elements they point to automatically destroyed when the auto_ptr object is itself destroyed.
Following is the declaration for std::auto_ptr function.
template <class X> class auto_ptr;
template <class X> class auto_ptr;
X − It is a managed object.
 Print
 Add Notes
 Bookmark this page
How to add padding to a tkinter widget only on one side?

Let us suppose that we want to add padding on one side (either top/bottom or left/right) of a particular widget. We can achieve this in Tkinter by using its pack() and grid() methods.
In pack() method, we have to define the value for “padx” and “pady”. On the other
hand, the grid method requires only two tuples, i.e., x and y for adding padding
around either of X-axis or Y-axis.
#import the required library
from tkinter import *

#Create an instance of window or frame
win= Tk()
win.geometry("700x400")

#Create two buttons
#Add padding in x and y axis

b1= Button(win, text= "Button1", font=('Poppins bold', 15))
b1.pack(padx=10)

b2= Button(win, text= "Button2", font=('Poppins bold', 15))
b2.pack(pady=50)

b3= Button(win, text= "Button3", font= ('Poppins bold', 15))
b3.pack(padx=50, pady=50)

#Keep running the window
win.mainloop()
Running the above code will create a window containing three buttons that will
have some padding around either of X, Y, or both axes.
Python program to remove all duplicates word from a given sentence.

Given a sentence. Remove all duplicates words from a given sentence.
Input: I am a peaceful soul and blissful soul.
Output: I am a peaceful soul and blissful.
Step 1: Split input sentence separated by space into words.
Step 2: So to get all those strings together first we will join each string in a given list of strings.
Step 3: now create a dictionary using the counter method which will have strings as key and their Frequencies as value.
Step 4: Join each words are unique to form single string.
from collections import Counter
def remov_duplicates(st):
   st = st.split(" ")
   for i in range(0, len(st)):
      st[i] = "".join(st[i])
      dupli = Counter(st)
      s = " ".join(dupli.keys())
      print ("After removing the sentence is ::>",s)
      # Driver program
   if __name__ == "__main__":
      st = input("Enter the sentence")
remov_duplicates(st)
Enter the sentence ::> i am a peaceful soul and blissful soul
After removing the sentence is ::> i am a peaceful soul and blissful
C++ Program to Generate Random Numbers Using Probability Distribution Function

Probability Density Function (pdf), is a function that describes the relative likelihood for this random variable to take on a given value. It is also called as density of a continuous random variable.
The probability of the random variable fall within a particular range of values is given by the integral of this variable’s density over that range, So, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range. Probability Distribution is based upon this probability density function.
Begin
   Declare n
   Assign pdf=0
   For i =0 to n , do
      pdf = rand() mod 200
      If pdf greater than 360
         Print 1
      Else if pdf less than 0
         Print 0
      Else
         Print pdf * 0.1 / 360
      Done
   Done
end
#include <iostream>
using namespace std;
int n = 6;
int main(int argc, char **argv) {
   int pdf = 0;
   for (int i = 0; i < n; i++) {
      pdf = rand() % 200;
      if (pdf > 360)
         cout << 1 << " ";
      else if (pdf < 0)
         cout << 0 << " ";
      else
         cout << pdf * 0.1 / 360 << " ";
   }
   cout << "...";
}
0.0508333 0.0238889 0.0491667 0.0319444 0.0536111 0.0375 ...
SQL Tryit Editor v1.6

WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How do you properly ignore Exceptions in Python?

This can be done by following codes
try:
x,y =7,0
z = x/y
except:
pass
OR
try:
x,y =7,0
z = x/y
except Exception:
pass
These codes bypass the exception in the try statement and ignore the except clause and don’t raise any exception.
The difference in the above codes is that the first one will also catch KeyboardInterrupt, SystemExit etc, which are derived directly from exceptions.BaseException, not exceptions.Exception.
It is known that the last thrown exception is remembered in Python, some of the objects involved in the exception-throwing statement are kept live until the next exception. We might want to do the following instead of just pass:
try:
x,y =7,0
z = x/y
except Exception:
sys.exc_clear()
This clears the last thrown exception