code-rag-bench/online-tutorials huggingface dataset:
HTML <hr> color Attribute

05 May, 2021
The HTML <hr> color Attribute is used to specify the color of a Horizontal rule. It is not supported by HTML 5.Syntax:  
<Hr color= "color_name | hex_number | rgb_number"> 
Attribute Values:  
color_name: It sets the Text color by using the color name. For example “red”.
hex_number: It sets the text color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)”.
Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML hr color Attribute    </title></head> <body style="text-align:center;">    <h1>GeeksforGeeks</h1>    <h2> Hr color  attribute</h2>    <hr width="500px;" color="red"        size="10">     <p>Computer science portal</p>      <hr width="70%"        size="20" color="blue"        noshade></body> </html>
Output 
 
 
hritikbhatnagar2182
HTML-Attributes
HTML-Basics
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to access a collection in MongoDB using Python?

30 May, 2022
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
1) Getting a list of collection: For getting a list of a MongoDB database’s collections list_collection_names() method is used. This method returns a list of collections.Syntax:
list_collection_names()
 Example: 
Sample Database:
Python3
from pymongo import MongoClient  # create an client instance of the# MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # get a list of a MongoDB database's# collectionscollections = db.list_collection_names()print ("collections:", collections, "\n")
Output:
collections: ['Geeks'] 
2) Check if the collection exist or not: To check if the collection attribute exists for the database use hasattr() method. It returns true if the collection is in database otherwise returns false. 
Syntax: hasattr(db, ‘collectionname’)
Parameters:db: It is database object. collectionname: It is the name of the collection. 
Example:
Python3
from pymongo import MongoClient  # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # check collection is exists or notprint(hasattr(db, 'Geeks'))
Output:
True
3) Accessing a Collection: To access a MongoDB collection name use the below syntax.  
Syntax:
database_object.Collectionname
or
database_object["Collectionname"]
Note: Database_object[“Collectioname”] can be useful in the case where the name of the collection contains a space in between them i.e. in cases like database_object[“Collection name”].Example:
Python3
from pymongo import MongoClient  # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG col1 = db["gfg"] print ("Collection:", col1)
 Output: 
Collection: Collection(Database(MongoClient(host=[‘localhost:27017’], document_class=dict, tz_aware=False, connect=True), ‘GFG’), ‘gfg’)
Code_r
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
C++ Queue Library - push() Function

The C++ function std::queue::push() inserts new element at the end of queue and assigns val to newly inserted element. This member function increases size of queue by one.
This member function effectively calls the push_back() member function of the underlying container.
Following is the declaration for std::queue::push() function form std::queue header.
void push (const value_type& val);

void push (const value_type& val);

val − Value to be assigned to newly inserted element.
None
Constant i.e. O(1)
The following example shows the usage of std::queue::push() function.
#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   queue<int> q;

   for (int i = 0; i < 5; ++i)
      q.push(i + 1);

   cout << "Contents of queue" << endl;
   while (!q.empty()) {
      cout << q.front() << endl;
      q.pop();
   }

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Contents of queue
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
Calendar Functions in Java

The java.util.calendar class provides the calendar functions in Java. Is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
Following are the calendar functions in Java −
Let us now see an example of the equals() method.
The java.util.Calendar.equals() method compares this Calendar to the specified Object −
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      // create two calendars
      Calendar cal = Calendar.getInstance();
      // specify a date for one of them
      Calendar cal2 = new GregorianCalendar(2011, 04, 29);
      // compare the two calendars.
      boolean b = cal.equals(cal2);
      // print result
      System.out.println("Calendars are equal :" + b);
   }
}
Calendars are equal :false
Let us see another example wherein we are getting the first day of week. The java.util.Calendar.getFirstDayOfWeek() method returns the first day of the week.
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      // create a new calendar
      Calendar cal = Calendar.getInstance();
      // print the first day of the week
      System.out.println("First day is :" + cal.getFirstDayOfWeek());
      int day = cal.getFirstDayOfWeek();
      switch (day) {
         case (1):
            System.out.println("Sunday");
            break;
         case (2):
            System.out.println("Monday");
            break;
         case 3:
            System.out.println("Tuesday");
            break;
         case 4:
            System.out.println("Wednesday");
            break;
         case 5:
            System.out.println("Thrusday");
            break;
         case 6:
            System.out.println("Friday");
            break;
         case 7:
            System.out.println("Saturday");
            break;
      }
   }
}
First day is :1
Sunday
BabylonJS - Video Texture

To display video in the scene, babylonjs has the video texture feature. videotexture takes an array of videos as input.
For video texture, we are going to use mp4 file. Please download an mp4 of your choice and use it in the demo below.
video.material.diffuseTexture = new BABYLON.VideoTexture("video",
["mp4 file", "webm file"], scene, true);

<!doctype html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>BabylonJs - Basic Element-Creating Scene</title>
      <script src = "babylon.js"></script>
      <style>
         canvas {width: 100%; height: 100%;}
      </style>
   </head>
   
   <body>
      <canvas id = "renderCanvas"></canvas>
      <script type = "text/javascript">
         var canvas = document.getElementById("renderCanvas");
         var engine = new BABYLON.Engine(canvas, true);
         
         var createScene  = function() {
            var scene = new BABYLON.Scene(engine);

            //Adding an Arc Rotate Camera
            var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene);
            camera.attachControl(canvas, false);

            // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
            var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);

            // Default intensity is 1. Let's dim the light a small amount
            light.intensity = 0.7;

            // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
            var ground = BABYLON.Mesh.CreateGround("ground1", 100, 50, 2, scene);

            // Move the sphere upward 1/2 its height
            ground.position.y = 1;

            var mat = new BABYLON.StandardMaterial("mat", scene);

            var videoTexture = new BABYLON.VideoTexture("video", ["sounds/video.mp4"], scene, true, true);

            mat.diffuseTexture = videoTexture;
            ground.material = mat;

            scene.onPointerUp = function () {
               videoTexture.video.play();
            }
            return scene;
         };
         var scene = createScene();
         engine.runRenderLoop(function() {
            scene.render();
         });
      </script>
   </body>
</html>
The above line of code will generate the following output −
 Print
 Add Notes
 Bookmark this page
How do I hide an element when printing a web page?

To hide the element, add “display:none” to the element with CSS.
<style>
@media print {
   .noprint {
      visibility: hidden;
   }
}
</style>
In addition, add the element, which you want to hide inside the <div>−
<div id="noprint">
   Add here the element, which you want to hide.
</div>
When should I use a semicolon after curly braces in JavaScript?

In JavaScript, Semicolons are optional. Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements is placed on a separate line. It is a good programming practice to use semicolons.
In JavaScript, use a semi-colon after a statement. Let’s see an example of a variable assignment:
var s = function() {
   alert("Hello World!");
};
However, semicolons aren’t necessary for the following function declarations:
function() {
   alert("Hello World!");
};
Slice Composite Literal in Go - GeeksforGeeks

22 Jul, 2019
There are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array.Composite literals are used to construct the values for arrays, structs, slices, and maps. Each time they are evaluated, it will create new value. They consist of the type of the literal followed by a brace-bound list of elements. (Did you get this point!) Well, after this read you will get to know what is a composite literal and you will be shocked that you know it already !!!!
Let’s see how to create a slice and make the use of composite literal:
// Go program to show the slice // - composite literalpackage main  import "fmt"  func main() {      // Slice with composite literal    // Slice allows you to group together    // the values of the same type     // here type of values is int    s1 := []int{23, 56, 89, 34}          // displaying the values    fmt.Println(s1)}
Output:
[23 56 89 34]

Hope you understand the term what exactly a composite literal. So basically assigning the values or initialization of arrays, slice, etc. are done using composite literals. These are generally used to compose a bunch of values of similar types.
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
Time Formatting in Golang
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
How to compare times in Golang?
Different Ways to Find the Type of Variable in Golang
Calculate time of operation in Arduino

Often, you need to measure the time your microcontroller takes to perform a particular task. You can use the millis() function of Arduino to measure the time. This function returns the number of milliseconds passed since your board started running the current program. Therefore, to calculate the time taken by an operation, you can call millis() before and after your operation, and take the difference of the two values.
An example implementation is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   long int t1 = millis();
   task_whose_time_is_to_be_measured();
   long int t2 = millis();
   Serial.print("Time taken by the task: "); Serial.print(t2-t1); Serial.println(" milliseconds");
}
void loop() {
   // put your main code here, to run repeatedly:
}
As you can see, this will give the execution time of the task in milliseconds. But what if you want the execution time to be in microseconds? You guessed it! You can use micros() instead of millis().
C# Program to check if a number is prime or not

To calculate whether a number is prime or not, we have used a for a loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0, between the number itself.
for (int i = 1; i <= n; i++) {
   if (n % i == 0) {
      a++;
   }
}
A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime. 
Let us see the complete example to check if a number is prime or not
Live Demo
using System;
namespace Demo {
   class MyApplication {
      public static void Main() {
         int n = 5, a = 0;
         for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
               a++;
            }
         }
         if (a == 2) {
            Console.WriteLine("{0} is a Prime Number", n);
         } else {
            Console.WriteLine("Not a Prime Number");
         }
         Console.ReadLine();
      }
   }
}
5 is a Prime Number
TypeScript - Nested if statement

The else...if ladder is useful to test multiple conditions. Its syntax is given below −
if (boolean_expression1) { 
   //statements if the expression1 evaluates to true 
} else if (boolean_expression2) { 
   //statements if the expression2 evaluates to true 
} else { 
   //statements if both expression1 and expression2 result to false 
}

When using if...else...if and else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else..if's.
An if can have zero or one else's and it must come after any else..if's.
An if can have zero to many else..if's and they must come before the else.
An if can have zero to many else..if's and they must come before the else.
Once an else..if succeeds, none of the remaining else..if's or else's will be tested.
Once an else..if succeeds, none of the remaining else..if's or else's will be tested.
var num:number = 2 
if(num > 0) { 
   console.log(num+" is positive") 
} else if(num < 0) { 
   console.log(num+" is negative") 
} else { 
   console.log(num+" is neither positive nor negative") 
}

The snippet displays whether the value is positive, negative or zero.
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var num = 2;
if (num > 0) {
   console.log(num + " is positive");
} else if (num < 0) {
   console.log(num + " is negative");
} else {
   console.log(num + " is neither positive nor negative");
}

Here is the output of the above code −
2 is positive


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Modified version of summing an array with recursion in JavaScript

Let’s say, we are required to write a recursive function that sums all the elements of an array of
Numbers but with a twist and the twist is that the recursive function we write cannot initialize any
extra variable (memory).
Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all
has to be using what we already have.
Here’s the solution −
We already have an array and can use its first element (i.e., the element at zeroth index to hold
the recursive sum).
The approach is that we repeatedly pop one element from the array and add it to the first
element of the array until we are left with only one element.
When we are left with only one element, it will be the cumulative sum of the array and we return
that. The code for this approach will be −
const recursiveSum = arr => {
   if(arr.length > 1){
      arr[0] += arr.pop();
      return recursiveSum(arr);
   };
   return arr[0];
};
console.log(recursiveSum([1,2,3,4]));
console.log(recursiveSum([1,2,3,4,3,6,3,32,7,9,5]));
console.log(recursiveSum([]));
The output in the console will be −
10
75
undefined
How to wrap the text in text flow layout in JavaFX?

To create rich text contents in our applications JavaFX provides a special layout called text flow represented by the javafx.scene.layout.TextFlow class. Using this you can layout multiple text nodes in a single text flow.
Since they are separate nodes, you can set different fonts to them. If you try to add nodes other than text to this layout, they will be treated as embedded objects and are simply inserted between the text.
Unlike Label and the Text nodes, TextFLow doesn’t provide any method to wrap the text. But it does have a property named prefWidth specifying the desired width of the TextFlow layout. You can set values to this property using the setPrefWidth() method.
In short, you can wrap the text at a desired width or height using the setPrefWidth() or, setPrefHeight() methods.
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class TextFlow_Wrap extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      Text text1 = new Text("Welcome To Tutorialspoint");
      Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 50);
      text1.setFont(font1);
      //Setting the color of the text
      text1.setFill(Color.BLUEVIOLET);
      text1.setStrokeWidth(1);
      text1.setStroke(Color.CORAL);
      Text text2 = new Text(" We provide free tutorials for readers in various technologies ");
      text2.setFont(new Font("Algerian", 30));
      text2.setFill(Color.ORANGERED);
      Text text3 = new Text("We believe in easy learning");
      //Setting font to the text
      Font font2 = Font.font("Ink Free", FontWeight.BOLD, 35);
      text3.setFont(font2);
      text3.setFill(Color.DIMGRAY);
      //Creating the text flow
      TextFlow textFlow = new TextFlow();
      //Wrapping the content of the text flow
      textFlow.setPrefWidth(595);
      textFlow.getChildren().addAll(text1, text2, text3);
      //Setting padding to the text flow
      textFlow.setPadding(new Insets(15, 15, 15, 15));
      //Setting the stage
      Group root = new Group(textFlow);
      Scene scene = new Scene(root, 595, 250, Color.BEIGE);
      stage.setTitle("Text Flow");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
What is the difference between compile time polymorphism and runtime polymorphism in java?

If we perform (achieve) method overriding and method overloading using instance methods, it is run time (dynamic) polymorphism.
In dynamic polymorphism the binding between the method call an the method body happens at the time of execution and, this binding is known as dynamic binding or late binding.
 Live Demo
class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class RuntimePolymorphism extends SuperClass {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass obj1 = new RuntimePolymorphism();
      RuntimePolymorphism obj2 = new RuntimePolymorphism();
      obj1.sample();
      obj2.sample();
   }
}
Method of the super class
Method of the sub class

If we perform (achieve) method overriding and method overloading using static, private, final methods, it is compile time (static) polymorphism.
In static polymorphism the binding between the method call an the method body happens at the time of compilation and, this binding is known as static binding or early binding.
class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class SubClass extends SuperClas {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass.sample();
      SubClass.sample();
   }
}
Method of the super class
Method of the sub class
Sorting in C++

In this section we will see how to perform sorting algorithm in C++. A sorted array is
an array in which each of the elements are sorted in some order such as numerical,
alphabetical etc. There are many algorithms to sort a numerical array such as bubble
sort, insertion sort, selection sort, merge sort, quick sort, heap sort etc. More details
about sorting the array using selection sort are given below.
The selection sort is a sorting method that yields a sorted array. It does so by
repeatedly finding the smallest element in the array and interchanging it with the
element at the starting of the unsorted part.
A program that implements a sorted array using selection sort is given as follows.
 Live Demo
#include<iostream>
using namespace std;
void selectionSort(int a[], int n) {
   int i, j, min, temp;
   for (i = 0; i < n - 1; i++) {
      min = i;
      for (j = i + 1; j < n; j++)
         if (a[j] < a[min])
            min = j;
            temp = a[i];
            a[i] = a[min];
            a[min] = temp;
   }
}
int main() {
   int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };
   int n = sizeof(a)/ sizeof(a[0]);
   int i;
   cout<<"Given array is:"<<endl;
   for (i = 0; i < n; i++)
      cout<< a[i] <<" ";
      cout<<endl;
      selectionSort(a, n);
      printf("\nSorted array is: \n");
      for (i = 0; i < n; i++)
         cout<< a[i] <<" ";
      return 0;
}
Given array is:
22 91 35 78 10 8 75 99 1 67
Sorted array is:
1 8 10 22 35 67 75 78 91 99
In the above program, selectionSort() is a function that sorts the array a[] using
selection sort. There are two for loops in selectionSort(). In each iteration of the
outer for loop, the minimum element in the remaining array after i is found and then
interchanged with the element currently at i. This is repeated until the array is
sorted. This is shown below.
void selectionSort(int a[], int n) {
   int i, j, min, temp;
   for (i = 0; i < n - 1; i++) {
      min = i;
      for (j = i + 1; j < n; j++)
         if (a[j] < a[min])
            min = j;
            temp = a[i];
            a[i] = a[min];
            a[min] = temp;
   }
}
In the main() function, the array a[] is defined. Then the function selectionSort() is
called with the array a[] and its size n. Finally, the sorted array is displayed. This is
shown below.
int main() {
   int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };
   int n = sizeof(a)/ sizeof(a[0]);
   int i;
   cout<<"Given array is:"<<endl;
   for (i = 0; i < n; i++)
      cout<< a[i] <<" ";
      cout<<endl;
      selectionSort(a, n);
      printf("\nSorted array is: \n");
   for (i = 0; i < n; i++)
      cout<< a[i] <<" ";
   return 0;
}
Append Operation on Vectors in R Programming - GeeksforGeeks

11 Jun, 2021
Vectors in R programming is a basic object consisting sequence of homogeneous elements. It can be integer, logical, double, character, complex or raw. In this article, let us discuss different methods to concatenate/append values to a vector in R programming. Values can be appended/concatenated in a vector using 2 methods:  
c() function
append() function
 
c() function is a generic function that combines data into a vector or a list. 
Syntax: c(...)Parameters: ...: represents objects to be concatenated  
To know about more optional parameters, use below command in console:  
help("c")
Example 1:  
r
# Create a vectorx <- 1:5n <- 6:10 # Append using c() functiony <- c(x, n) # Print resultant vectorprint(y)
Output:  
 [1]  1  2  3  4  5  6  7  8  9 10
Example 2:  
r
# Create vectorx <- 1:5n <- letters[1:5] # Appendy <- c(x, n) # Print resultant vectorprint(y) # Print type of resultant vectortypeof(y) # Print type of other vectorstypeof(x)typeof(n)
Output:  
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
[1] "character"
[1] "integer"
[1] "character"
 
append() function in R is used for merging vectors or adding more elements to a vector. 
Syntax: append(x, values)Parameters: x: represents a vector to which values has to be appended to values: represents the values which has to be appended in the vector  
Example 1:  
r
# Create a vectorx <- 1:5 # Append using append() functionx <- append(x, 6:10) # Print resultant vectorprint(x)
Output:  
[1]  1  2  3  4  5  6  7  8  9 10
Example 2:  
r
# Create a vectorx <- 1:5y <- letters[1:5] # Append using append() functionx <- append(x, values = y) # Print resultant vectorprint(x)
Output:  
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
 
ruhelaa48
Picked
R-Vectors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
How to change the order of bars in bar chart in R ?
Google Interview Experience for Software Engineer 2021 New Grad - GeeksforGeeks

17 Dec, 2020
I was contacted by a Google recruiter a few months ago, that my resume has been shortlisted for the Software Engineer 2021 New Grad Role. I was provided with the next action steps of how to proceed with the next round of interviews – Technical Phone Interview which is generally 45 minutes.
I wasn’t able to grab the offer, but I really hope that my experience and feedback about this whole process would help you as much as it helped me.
Usually, the recruiter asks about your preferable date and time for the interview, also they furnish you with some beneficial extra tips and information that you should know.
Round 1(Technical Phone Interview): I was asked about my recent project mentioned in the CV , there was a good discussion about it, for say 5 minutes. After that I was given a coding question to solve : 
Given an N-ary Tree, find out the average width of each of the nodes present in that tree.
Note: A node can have ‘N’ number of children
Explanation: Consider the above tree, for node 1 , the average width would be the total no. of nodes under that node ie. 7 (including the target node) divided by the total number of levels under the parent node (7/3) .
The format of the answer should be: [node number : average width of that node ] that is ,for the given tree the answer is :
[ 1 : 2.5 , 2 : 1.5 , 3 : 1.5 , 4 : 1 , 5 : 1 , 6 : 1 , 7 : 1 ]
I was able to come up with a brute-force approach ONLY within that remaining time.
The interviewer was quite polite, interactive, and helped me with my initial queries against the given problem statement. One thing to note over here is while your interviewer is helping you clear the doubts and landing on a meaningful solution, it also means that you are getting a penalty for not being selected. It’s a fact ! 
Good luck to you, if you are appearing/preparing for interviews! Sometimes it’s your day, sometimes it isn’t. 
Do not give up
Google
Marketing
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Zoho Interview | Set 3 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience (Off-Campus) 2022
Directi Interview | Set 7 (Programming Questions)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1(Off-Campus)
Combinations of sum with tuples in tuple list in Python

If it is required to get the combinations of sum with respect to tuples in a list of tuples, the 'combinations' method and the list comprehension can be used.
The 'combinations' method returns 'r' length subsequence of elements from the iterable that is passed as input. The combinations are shown in lexicographic sort order. The combination tuples are displayed in a sorted order.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same −
Live Demo
from itertools import combinations
my_list = [( 67, 45), (34, 56), (99, 123), (10, 56)]

print ("The list of tuple is : " )
print(my_list)

my_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)]

print("The summation combination result is : ")
print(my_result)
The list of tuple is :
[(67, 45), (34, 56), (99, 123), (10, 56)]
The summation combination result is :
[(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]
A list of tuples is defined, and is displayed on the console.
The combinations method is used to return subsequence of length 2, as mentioned in the method.
The list of tuple is iterated, and the elements from every tuple in the list of tuple is added to the element from the next tuple.
This value is assigned a variable.
This variable is the output that is displayed on the console.
Difference between mutable and immutable in python?

Python defines variety of data types of objects. These objects are stored in memory and object mutability depends upon the type, like Lists and Dictionaries are mutable it means that we can change their content without changing their identity. Other objects like Integers, Floats, Strings and Tuples have no provision to change there assigned value for an index.
List is mutable: Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. Lists are mutable, and hence, they can be altered even after their creation.
#Write a python program to print list of a number?
list=[1,2,3,4,5]
print(list)
[1,2,3,4,5]
List is a collection which is ordered and changeable. Allows duplicate members.
list=[1,2,3,4,5]
list[0] ='a'
print(list)
['a', 2, 3, 4, 5]
While running the program, assigning the zero based index with the value of '1' can be assigned a value of 'a' which is mutable(can be modified)
Tuple is immutable: A tuple is a collection which is ordered and unchangeable, does not allow duplicate members. In Python tuples ar written with round or inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.
#Write a python program to print tuple of a number?
Tuple=(10,20,30)
print(tuple)
(10,20,30)
Tuple is ordered and unchangeable(cannot be modified).
tuple=(10,20,30)
tuple[0]=50
print(tuple)
TypeError Traceback (most recent call last)
in
1 my_yuple = (10, 20, 30)
----> 2 my_yuple[0] = 50
3 print(my_yuple)

TypeError: 'tuple' object does not support item assignment
While assigning the zero based index with the value of '50' throws an exception, because it is already assigned a value of '10' which is immutable(cannot be modified).
Jython - Installation

Before installation of Jython 2.7, ensure that the system has JDK 7 or more installed. Jython is available in the form of an executable jar file. Download it from - http://www.jython.org/downloads.html and either double click on its icon or run the following command −
java -jar jython_installer-2.7.0.jar

An installation wizard will commence with which installation options have to be given. Here is the systematic installation procedure.
The first step in the wizard asks you to select the language.
The second step prompts you to accept the licence agreement.
In the next step, choose the installation type. It is recommended to choose the Standard installation.
The next screen asks your confirmation about your options and proceeds to complete the installation.
The installation procedure might take some time to complete.
After the installation is complete, invoke jython.exe from the bin directory inside the destination directory. Assuming that Jython is installed in C:\jython27, execute the following from the command line.
C:\jython27\bin\jython

A Python prompt (>>>) will appear, in front of which any Python statement or Python script can be executed.
 Print
 Add Notes
 Bookmark this page
GATE | Gate IT 2008 | Question 40 - GeeksforGeeks

29 Mar, 2018
The two numbers given below are multiplied using the Booth’s algorithm.
Multiplicand : 0101 1010 1110 1110Multiplier: 0111 0111 1011 1101
How many additions/Subtractions are required for the multiplication of the above two numbers?(A) 6(B) 8(C) 10(D) 12Answer: (B)Explanation: Booth’s algorithm: first take 2’s complement of given number if number is negative, then append 0 into LSB.
Then, for each pair from LSB to MSB (add 1 bit at a time):
00 = 0, 01 = +1, 10 = -1, 11 = 0
Booth’s algorithm is based on Multiplier which is already given in binary representation: 0111 0111 1011 1101
= Now, append 0 into LSB of (0111 0111 1011 1101) = 0111 0111 1011 1101 0
Now Booth's code (add 1 bit at a time, from LSB to MSB):
= 01, 11, 11, 10, 01, 11, 11, 11, 10, 01, 11, 11, 11, 10, 01, 10
= +1 0 0 -1 +1 0 0 0 -1 +1 0 0 0 -1 +1 -1
Therefore, 4 subtractions and 4 additions, total 8 additions/Subtractions are required.
So, option (B) is correct.Quiz of this Question
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Rust - Switch Case - GeeksforGeeks

19 Jul, 2021
Switch statement is basically nested if statement, though it does not support expression, it matches an int, string, or boolean data type variable with a given set of cases that are provided by the programmer. It is mainly used in a menu-driven program where the user selects which function they want to run. A switch case in Rust is achieved by the keyword match. Let’s see a few examples to see how it works.
Unlike C or Java, only the case corresponding to the match is executed, so we need not worry about fall through. Thereby saving our effort to write a break statement after each case. Default case, where no match is found, is handled by the case ‘_’ (underscore). There is something special in Rust, the cases can have more than one value. 
Example:
Rust
fn main() {  let num=3;  match num{  1=>println!("One"),  2=>println!("Two"),  3=>println!("Three"),  _=>println!("Rest of the number"),  }
Output
Three
Several values can be included in a single case by separating them via ‘|’.
Example:
Rust
fn main() {  let num=2;  match num{  1|3|5|7|9=>println!("Odd"),  2|4|6|8=>println!("Even"),  _=>println!("Only one  digit allowed"),  }  }
Output
Even
 It’s not the end we can also include a range of values in each case. 
 A range is inclusive in this case that means both the ends are also included.
Example:
Rust
fn main() {  let num=19;  match num{  13..=19=>println!("Teenage"),  _=>println!("Not Teenage"),  }  }
Output
Teenage
As stated in the beginning we can also use boolean values to match cases, we will now go for it. One more thing is that match can be used in an expression.
Example:
Rust
fn main() {  let head = false;    let coin_side = match head{        false => "tail",        true => "head",    };    println!("Coin Side={}", coin_side)}
Output
Coin Side=tail
At last, we will see how strings are used in matches.
Example:
Rust
fn main() {  let coin = "head";    match coin{        "head" =>println!("head"),        "tail"=> println!("tail"),        _=>println!("False coin"),    };}
Output
head
rust-control-flow
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Generate Random Numbers in Rust Language?
Rust - Casting
Rust - For and Range
Rust - Generic Function
Rust - Creating a Library
Rust - References & Borrowing
Rust - Concept of Structures
Rust - Box Smart Pointer
Rust - Concept of Smart Pointers
Rust - While Loop
Pulling a random word or string from a line in a text file in Python - GeeksforGeeks

11 Dec, 2020
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python’s random module to pick a random word. 
There are various ways to perform this operation:
This is the text file we will read from:
Method 1: Using random.choice()
Steps:
Using with function, open the file in read mode. The with function takes care of closing the file automatically.Read all the text from the file and store in a stringSplit the string into words separated by space.Use random.choice() to pick a word or string.
Using with function, open the file in read mode. The with function takes care of closing the file automatically.
Read all the text from the file and store in a string
Split the string into words separated by space.
Use random.choice() to pick a word or string.
Python
# Python code to pick a random# word from a text fileimport random  # Open the file in read modewith open("MyFile.txt", "r") as file:    allText = file.read()    words = list(map(str, allText.split()))      # print random string    print(random.choice(words))
Note: The split() function, by default, splits by white space. If you want any other delimiter like newline character you can specify that as an argument.
Output:
Output for two sample runs
The above can be achieved with just a single line of code like this : 
Python
# import required moduleimport random  # print random wordprint(random.choice(open("myFile.txt","r").readline().split()))
Method 2: Using random.randint() 
Steps:
Open the file in read mode using with functionStore all data from the file in a string and split the string into words.Count the total number of words.Use random.randint() to generate a random number between 0 and the word_count.Print the word at that position.
Open the file in read mode using with function
Store all data from the file in a string and split the string into words.
Count the total number of words.
Use random.randint() to generate a random number between 0 and the word_count.
Print the word at that position.
Python
# using randint()import random  # open filewith open("myFile.txt", "r") as file:    data = file.read()    words = data.split()          # Generating a random number for word position    word_pos = random.randint(0, len(words)-1)    print("Position:", word_pos)    print("Word at position:", words[word_pos])
Output:
Output for two sample runs
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python program to print current year, month and day - GeeksforGeeks

29 Dec, 2020
In this article, the task is to write a Python Program to print the current year, month, and day.
Approach:
In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date class
Create an object of the date class
Call the today( ) function of date class to fetch todays date.
By using the object created, we can print the year, month, day(attribute of date class) of today.
Python3
# importing date class from datetime modulefrom datetime import date  # creating the date object of today's datetodays_date = date.today()  # printing todays dateprint("Current date: ", todays_date)  # fetching the current year, month and day of todayprint("Current year:", todays_date.year)print("Current month:", todays_date.month)print("Current day:", todays_date.day)
Output:
Current date:  2020-12-10
Current year: 2020
Current month: 12
Current day: 10
Python datetime-program
Python-datetime
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to create Grouped box plot in Plotly? - GeeksforGeeks

05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. 
A grouped box plot is a box plot where categorized are organized in groups and sub-groups. Origin supports plotting grouped Box charts from both Indexed Data or Raw Data. The group box plot is more understandable and efficient in presentation and take less space in the layout.
It can be created using the add_trace() method of figure class. The add_trace() method allow us to add multiple traces in a single graph. Let’s see the below examples
Example 1: Vertical grouping of the box plot
Python3
import plotly.graph_objects as go    fig = go.Figure()  # Defining x axisx = ['a', 'a', 'a', 'b', 'b', 'b']  fig.add_trace(go.Box(      # defining y axis in corresponding    # to x-axis    y=[1, 2, 6, 4, 5, 6],    x=x,    name='A',    marker_color='green'))  fig.add_trace(go.Box(    y=[2, 3, 4, 1, 2, 6],    x=x,    name='B',    marker_color='yellow'))  fig.add_trace(go.Box(    y=[2, 5, 6, 7, 8, 1],    x=x,    name='C',    marker_color='blue'))  fig.update_layout(      # group together boxes of the different    # traces for each value of x    boxmode='group')fig.show()
Output:
Example 2: Horizontal grouping of the box plot
Python3
import plotly.graph_objects as go    fig = go.Figure()  # Defining y axisy = ['a', 'a', 'a', 'b', 'b', 'b']  fig.add_trace(go.Box(      # defining x axis in corresponding    # to y-axis    y=y,    x=[1, 2, 6, 4, 5, 6],    name='A',    marker_color='green'))  fig.add_trace(go.Box(    y=y,    x=[2, 3, 4, 1, 2, 6],    name='B',    marker_color='yellow'))  fig.add_trace(go.Box(    y=y,    x=[2, 5, 6, 7, 8, 1],    name='C',    marker_color='blue'))  fig.update_layout(      # group together boxes of the different    # traces for each value of y    boxmode='group')  # changing the orientation to horizontalfig.update_traces(orientation='h')  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python time.perf_counter_ns() Function - GeeksforGeeks

05 Nov, 2021
Python time.perf_counter_ns() function gives the integer value of time in nanoseconds.
Syntax:
from time import perf_counter_ns
We can find the elapsed time by using start and stop functions. We can also find the elapsed time during the whole program by subtracting stoptime and starttime
Example 1:
Python3
# import  perf_counter_ns()from time import perf_counter_ns  # integer input from user, 2 input in single linen, m = map(int, input().split())  # Start the stopwatch / counterstart = perf_counter_ns()  for i in range(n):    t = int(input())  # user gave input n times    if t % m == 0:        print(t)  # Stop the stopwatch / counterstop = perf_counter_ns()  print("Elapsed time:", stop, 'ns', start, 'ns')  print("Elapsed time during the whole program",      stop-start, 'ns')
Output:
Example 2:
Python3
# import  perf_counter_ns()from time import perf_counter_ns  # integer input from user, 2 input in single linen, m = map(int, input().split())  # Start the stopwatch / counterstart = perf_counter_ns()  for i in range(n):    t = int(input())  # user gave input n times    if t % m == 0:        print(t)  # Stop the stopwatch / counterstop = perf_counter_ns()  print("Elapsed time:", stop, 'ns', start, 'ns')  print("Elapsed time during the whole program",      stop-start, 'ns')
Output:
Picked
Python time-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
PostgreSQL - TRUNCATE TABLE - GeeksforGeeks

28 Aug, 2020
PostgreSQL supports the TRUNCATE TABLE statement to remove all data from large tables quickly. To remove all data from a table, you use the DELETE statement. However, for a large table, it is more efficient to use the TRUNCATE TABLE statement. The TRUNCATE TABLE statement removes all rows from a table without scanning it. This is the reason why it is faster than the DELETE statement. In addition, the TRUNCATE TABLE statement reclaims the storage right away so the user does not have to perform a subsequent VACUUM operation, which is useful in case of large tables.
Syntax: TRUNCATE TABLE table_name;
Example 1:In our database, we already have a table with data called animals. Let’s check if it has any data using the below statement:
SELECT * FROM animals;
It shows the following result:Now we will delete all the data from the table using the below statement:
TRUNCATE TABLE animals;
Now we verify whether the deletion is complete using the below statement:
SELECT * FROM animals;
Output:
Example 2:In our database, we already have a table with data called galaxy. Let’s check if it has any data using the below statement:
SELECT * FROM galaxy;
It shows the following result:Now we will delete all the data from the table using the below statement:
TRUNCATE TABLE galaxy;
Now we verify whether the deletion is complete using the below statement:
SELECT * FROM galaxy;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column