code-rag-bench/online-tutorials huggingface dataset:
reflect.FieldByName() Function in Golang with Examples

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByName() Function in Golang is used to get the struct field with the given name. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) FieldByName(name string) Value

Parameters: This function accept only single parameters.
name: This parameter is the string type.
Return Value: This function returns the struct field with the given name.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.FieldByName() Function    package main   import (    "fmt"    "reflect")  type Struct1 struct {    Var1       string    Var2       string    Var3       float64    Var4       float64}  // Main function func main() {    NewMap := make(map[string]*Struct1)    NewMap["abc"] = &Struct1{"abc", "def", 1.0, 2.0}    subvalMetric := "Var1"          for _, Value:= range NewMap {        s := reflect.ValueOf(&Value).Elem()        println(s.String())        println(s.Elem().String())                  // use of FieldByName() method        metric := s.Elem().FieldByName(subvalMetric).Interface()        fmt.Println(metric)    }      }     
Output:
<*main.Struct1 Value>
<main.Struct1 Value>
abc

Example 2:
// Golang program to illustrate// reflect.FieldByName() Function    package main   import (    "fmt"    "reflect")  // Main function func main() {    type t struct {            N int    }    var n = t{76}    fmt.Println(n.N)          // use of FieldByName() method    reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(4)    fmt.Println(n.N)    }
Output:
76
4

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.random.laplace() in Python

15 Jul, 2020
With the help of numpy.random.laplace() method, we can get the random samples of Laplace or double exponential distribution having specific mean and scale value and returns the random samples by using this method.
laplace distribution
Syntax : numpy.random.laplace(loc=0.0, scale=1.0, size=None)
Return : Return the random samples as numpy array.
Example #1 :
In this example we can see that by using numpy.random.laplace() method, we are able to get the random samples of laplace or double exponential distribution and return the random samples by using this method.
Python3
# import numpy import numpy as npimport matplotlib.pyplot as plt  # Using numpy.random.laplace() methodgfg = np.random.laplace(1.45, 15, 1000)  count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpy import numpy as npimport matplotlib.pyplot as plt  # Using numpy.random.laplace() methodgfg = np.random.laplace(0.5, 12.45, 1000)gfg1 = np.random.laplace(gfg, 12.45, 1000)  count, bins, ignored = plt.hist(gfg1, 40, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
Zoho Interview | Set 5 (On-Campus Drive)

22 Jul, 2019
Round 1:Questions based on aptitude (10) and c program output (20)Time 2hr.
Round 2:5 problem given we have to solve at least 3Program 1:Help john to find new friends in social networkInput:3Mani 3 ram raj gunaRam 2 kumar KishoreMughil 3 praveen Naveen Ramesh
Output:Raj guna kumar Kishore praveen Naveen Ramesh
Program 2:Input:With the starting and ending time of work given find the minimum no of workers needed
Start time         end time
1230            0130
1200            0100
1600            1700
Output:2
Program 3:Find the union intersection of two list and also find except (remove even elements from list1 and odd elements from list2)Input
List 1: 1,3,4,5,6,8,9
List 2: 1, 5,8,9,2

Union: 1, 3,4,5,6,8,9,2
Intersection: 1,5,8,9
Except: 1, 3, 5,9,8,2 
Program 4:
Rotate the matrix elements
For 3*3 matrix
Input
1    2    3
4    5    6
7    8    9

Output:
4    1    2
7    5    3
8    9    6

For 4*4 matrix
Input:
1    2    3    4    
5    6    7    8
9    10    11    12
13    14    15    16

Output:
5    1    2    3
9    10    6    4
13    11    7    8
14    15    16    12
Program 5:Find the largest possible prime number with given noInput54691Output:9461
Round 3:For one batch of peopleBasic programs like pattern printing1223334444And12 43 5 76 8 10 12
Others had app developmentScenario: text editorOnly 40 characters per line and words should be wrapped if they brakeAlso perform insert delete operations
Round 4:Tech hr: Topics revolved around OOPS and java thread and Ubuntu commands.
Round 5:General hr: As usual stuffs like personal info and about projects and why zoho?Good luck friendsThanks for geeks for geeks team it helped me a lot.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Volume and Surface Area of Cube in C++

Cube is a three-dimensional object with six faces of square shape which means it has sides of same length and breadth. Cube is the only regular hexahedron with following properties −
six faces
12 edges
8 vertices
Given below is the figure of cube
Given with the side, the task is to find the total surface area and volume of a cube where surface area is the space occupied by the faces and volume is the space that a shape can contain.
To calculate surface area and volume of a cube there is a formula −
Surface Area = 6*Side*side
Volume = Side*side*side
Input-: side=3
Output-: volume of cube is: 27
   Total surface area of cube is 54
Start
Step 1 -> declare function to find volume of cube
   double volume(double a)
      return (a*a*a)
Step 2 -> declare function to find area of cube
   double volume(double a)
      return (6*a*a)
Step 3 -> In main()
   Declare variable double a=3
   Print volume(a)
   Print area(a)
Stop
#include <bits/stdc++.h>
using namespace std;
// function for volume of cube
double volume(double a){
   return (a * a * a);
}
//function for surface area of cube
double area(double a){
   return (6 * a * a);
}
int main(){
   double a = 3;
   cout<< "volume of cube is: "<<volume(a)<<endl;
   cout<< "Total surface area of cube is "<<area(a);
   return 0;
}
volume of cube is: 27
Total surface area of cube is 54
How to get first and last elements from ArrayList in Java?

The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index.
Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.size()-1 you can get the last element.
 Live Demo
import java.util.ArrayList;
public class FirstandLastElemets{
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      System.out.println("First element of the array list: "+list.get(0));
      System.out.println("Last element of the array list: "+list.get(list.size()-1));
   }
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
First element of the array list: JavaFX
Last element of the array list: Impala
To get minimum and maximum values of an ArrayList −
Create an ArrayList object.
Create an ArrayList object.
Add elements to it.
Add elements to it.
Sort it using the sort() method of the Collections class.
Sort it using the sort() method of the Collections class.
Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.
Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class MinandMax{
   public static void main(String[] args){
      ArrayList<Integer> list = new ArrayList<Integer>();
      //Instantiating an ArrayList object
      list.add(1001);
      list.add(2015);
      list.add(4566);
      list.add(90012);
      list.add(100);
      list.add(21);
      list.add(43);
      list.add(2345);
      list.add(785);
      list.add(6665);
      list.add(6435);
      System.out.println("Contents of the Array List: \n"+list);
      //Sorting the array list
      Collections.sort(list);
      System.out.println("Minimum value: "+list.get(0));
      System.out.println("Maximum value: "+list.get(list.size()-1));
   }
}
Contents of the Array List:
[1001, 2015, 4566, 90012, 100, 21, 43, 2345, 785, 6665, 6435]
Minimum value: 21
Maximum value: 90012
Add perpendicular caps to error bars in Matplotlib - GeeksforGeeks

26 Dec, 2020
Prerequisites: Matplotlib
The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars. For our requirement we need to specifically focussing on capsize attribute of this function. Simply providing a value to it will produce our required functionality.
Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameters are the horizontal and vertical coordinates of the data points.
fmt: This parameter is an optional parameter and it contains the string value.
capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE.
barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False.
errorevery: This parameter is also an optional parameter. They contain integer values which is used to draw error bars on a subset of the data.
Import module
Create data
Provide error values
Pass all the values to errorbar() function along with capsize attribute and its value
Display plot
Example 1:
Python3
import matplotlib.pyplot as plt  x_values = [5, 4, 3, 2, 1]y_values = [8, 4, 9, 1, 0]  y_error = [0, 0.3, 1, 0.2, 0.75]  plt.errorbar(x_values, y_values,  yerr=y_error,             fmt='o', markersize=8, capsize=10)  plt.show()
Output: 
Example 2:
Python3
import matplotlib.pyplot as plt  x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5]  plt.plot(x_values, y_values)x_error = [0, 0.3, 1, 0.2, 0.75, 2]  plt.errorbar(x_values, y_values,  xerr=x_error,             fmt='o', markersize=8, capsize=6, color="r")  plt.show()
Output:
Example 3: 
Python3
import matplotlib.pyplot as plt  x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5]    x_error = [0, 0.3, 1, 0.2, 0.75, 2]y_error = [0.3, 0.3, 2, 0.5, 0.7, 0.6]  plt.errorbar(x_values, y_values,  xerr=x_error, yerr=y_error,             fmt='D', markersize=8, capsize=3, color="r")  plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
How do I run two python loops concurrently?

You will need to use a multiprocessing library. You will need to spawn a new process and provide the code to it as an argument. For example,
from multiprocessing import Process
def loop_a():
   for i in range(5):
      print("a")

def loop_b():
   for i in range(5):
      print("b")

Process(target=loop_a).start()
Process(target=loop_b).start()
This might process different outputs at different times. This is because we don't know which print will be executed when.
Wait until page is loaded with Selenium WebDriver for Python.

We can wait until the page is loaded with Selenium webdriver. There is a synchronization concept in Selenium which describes implicit and explicit wait. To wait until the page is loaded we shall use the explicit wait concept.
The explicit wait is designed such that it is dependent on the expected condition for a particular behavior of an element. For waiting until the page is loaded we shall use the expected condition presence_of_element_loaded for a particular element. Once the wait time is elapsed, the timeout error shall be thrown.
To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class. Let us check the presence of the element below on the page and verify if the page is loaded.
Code Implementation
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
// presence_of_element_located expected condition wait for 8 seconds
try:
   w = WebDriverWait(driver, 8)
   w.until(expected_conditions.presence_of_element_located((By.TA
   G_NAME,"h1")))
   print("Page load happened")
exception TimeException:
   print("Timeout happened no page load")
driver.close()
Queue.Enqueue() Method in C#

13 Apr, 2021
This method is used to add an object to the end of the Queue. This comes under the System.Collections namespace. The value can null and if the Count is less than the capacity of the internal array, this method is an O(1) operation. If the internal array needs to be reallocated to accommodate the new element, this method becomes an O(n) operation, where n is Count.Syntax :  
public virtual void Enqueue (object obj);
Here, obj is the object which is added to the Queue.Example: 
CSHARP
// C# code to illustrate the// Queue.Enqueue() Methodusing System;using System.Collections; class GFG {     // Driver code    public static void Main()    {         // Creating a Queue        Queue myQueue = new Queue();         // Inserting the elements into the Queue        myQueue.Enqueue("one");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);         myQueue.Enqueue("two");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);         myQueue.Enqueue("three");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);         myQueue.Enqueue("four");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);         myQueue.Enqueue("five");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);         myQueue.Enqueue("six");         // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");         Console.WriteLine(myQueue.Count);    }}
Total number of elements in the Queue are : 1
Total number of elements in the Queue are : 2
Total number of elements in the Queue are : 3
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 6
 
Reference: 
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.enqueue?view=netframework-4.7.2
 
simmytarika5
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install Keras in Windows?

21 Sep, 2021
Keras is a neural Network python library primarily used for image classification. In this article we will look into the process of installing Keras on a Windows machine.
The only thing that you need for installing Numpy on Windows are:
Python 
PIP or Conda (depending upon user preference)
The Keras library has the following dependencies:
Numpy
Pandas
Scikit-learn
Matplotlib
Scipy
Seaborn
Note: All these dependencies can be manually installed. But if you are missing one or all of these dependencies, they get installed when you run the command to install Keras automatically.
If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:
conda install -c conda-forge keras
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if Keras library has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list keras
You’ll get the below message if the installation is complete:
Users who prefer to use pip can use the below command to install the Keras library on Windows:
pip install keras
You will get a similar message once the installation is complete:
To verify if Keras library has been successfully installed in your system run the below command in your command prompt:
python -m pip show keras
You’ll get the below message if the installation is complete:
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Compute the Sum of Numbers in a List Using For-Loop

22 Dec, 2020
Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List.
Example:
Input : List = [1, 2, 3]
Output: Sum = 6

Input : List = [5, 1, 2, 3]
Output: Sum = 11
Approach 1:
Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum.
Create the sum variable of an integer data type.
Initialize sum with 0.
Start iterating the List using for-loop.
During iteration add each element with the sum variable.
After execution of the loop, print the sum.
Below is the implementation of the above approach:
Java
// Java Program to Compute the Sum of// Numbers in a List Using For-Loopimport java.util.*;import java.io.*;  class GFG {    public static void main(String[] args)    {        List<Integer> list = new ArrayList<>();        list.add(5);        list.add(6);        list.add(7);        list.add(10);        list.add(9);        int sum = 0;        for (int i = 0; i < list.size(); i++)            sum += list.get(i);          System.out.println("sum-> " + sum);    }}
sum-> 37
Time Complexity: O(n)
Approach 2:
Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using enhanced for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum.
Create the sum variable of an integer data type.
Initialize sum with 0.
Start iterating the List using enhanced for-loop.
During iteration add each element with the sum variable.
After execution of the loop, print the sum.
Below is the implementation of the above approach:
Java
// Java Program to Compute the Sum of// Numbers in a List Using Enhanced For-Loopimport java.util.*;import java.io.*;  class GFG {    public static void main(String[] args)    {        List<Integer> list = new ArrayList<>();        list.add(5);        list.add(6);        list.add(7);        list.add(10);        list.add(9);        int sum = 0;        for (Integer i : list)            sum += i;          System.out.println("sum-> " + sum);    }}
sum-> 37
Time Complexity: O(n)
java-list
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LocalDate minusYears() method in Java with Examples

07 May, 2019
The minusYears() method of a LocalDate class is used to subtract the number of specified years from this LocalDate and return a copy of LocalDate.
This method subtracts the years field in the following steps:
Firstly, it subtracts the years from the year field in this LocalDate.
Check if the date after subtracting years is valid or not.
If the date is invalid then method adjusts the day-of-month to the last valid day.
For example, 2016-02-29 (leap year) minus one year gives date 2015-02-29 but this is an invalid result, so the last valid day of the month, 2015-02-28, is returned. This instance is immutable and unaffected by this method call.
Syntax:
public LocalDate minusYears(long yearsToSubtract)

Parameters: This method accepts a single parameter yearsToSubtract which represents the years to subtract, may be negative.
Return Value: This method returns a LocalDate based on this date with the years subtracted, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the minusYears() method:
Program 1:
// Java program to demonstrate// LocalDate.minusYears() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2020-10-22");          // print instance        System.out.println("LocalDate before"                           + " subtracting years:" + date);          // subtract 30 years        LocalDate returnvalue            = date.minusYears(30);          // print result        System.out.println("LocalDate after "                           + " subtracting years:" + returnvalue);    }}
LocalDate before subtracting years:2020-10-22
LocalDate after  subtracting years:1990-10-22

Program 2:
// Java program to demonstrate// LocalDate.minusYears() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2020-02-29");          // print instance        System.out.println("LocalDate before"                           + " subtracting years: " + date);          // subtract -21 years        LocalDate returnvalue            = date.minusYears(-21);          // print result        System.out.println("LocalDate after "                           + " subtracting years: " + returnvalue);    }}
LocalDate before subtracting years: 2020-02-29
LocalDate after  subtracting years: 2041-02-28

Reference:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusYears(long)
Akanksha_Rai
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SVG Path Element

15 Jul, 2020
SVG stands for Scalable Vector Graphic. The SVG element path is used to define a path that starts from a position and ends to a particular position. SVG path can be used to create any basic shapes.
Syntax:
<path d="Shape of path using keyword like M, L, C etc."
      pathLength="Length of path"
      stroke="stroke color name"
      fill="color name">
</path>

Attributes: This element accepts four attributes as mentioned above and described below:
d: It is used to define the shape of the path.M: It is used for moving a point to a certain location.L: It is used for making a line to a point.C: It is used for making a curve to a point.
M: It is used for moving a point to a certain location.
L: It is used for making a line to a point.
C: It is used for making a curve to a point.
pathLength: It is used to define the total length of the path.
stroke: It is used to define the stroke color.
fill: It is used to define the filling color of the SVG.
Few examples are given below for better understanding of the <path> SVG element.
Example 1:
HTML
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width, initial-scale=1.0">  <title>Document</title></head><body>  <svg viewBox="500 500 ">    <!--Moving point to M10 10 200 200    making a line to 10 200 200 10 -->    <path d="M 10 10 200 200 L 10 200 L200 10">    </path>  </svg></body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"        content="width=device-width, initial-scale=1.0">  <title>Document</title></head><body>  <h1 style="color:green">GeeksforGeeks SVG Path</h1>  <svg viewBox="500 500">    // Creating a rectangle starting point is 10, 10    // Making a line to 10 100    // Moving point to 10 100    // Making line to  100 100    // Moving point to 100 100    // Making line to  100 10    // Moving point to 100 10    // Making line to  10 10 -->    <path d="M 10 10 L10 100 M10 100 L100 100 M100           100 L100 10 M100 10 L10 10" stroke="black">    </path>  </svg></body></html>
Output:
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
LocalDate getDayOfMonth() method in Java

28 Nov, 2018
The getDayOfMonth() method of LocalDate class in Java gets the day-of-month field.
Syntax:
public int getDayOfMonth()

Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the month which is in range 1-31.
Below programs illustrate the getDayOfMonth() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfMonth() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {          LocalDate dt = LocalDate.parse("2018-11-27");        System.out.println(dt.getDayOfMonth());    }}
27

Program 2:
// Program to illustrate the getDayOfMonth() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {          LocalDate dt = LocalDate.parse("2018-01-01");        System.out.println(dt.getDayOfMonth());    }}
1

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfMonth()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Python | Pandas Series.add()

01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Python Series.add() is used to add series or list like objects with same length to the caller series.
Syntax: Series.add(other, level=None, fill_value=None, axis=0)
Parameters:other: other series or list type to be added into caller seriesfill_value: Value to be replaced by NaN in series/list before addinglevel: integer value of level in case of multi index
Return type: Caller series with added values
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Adding List
In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and added to the salary column using .add() method
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # creating short data of 5 rowsshort_data = data.head()  # creating list with 5 valueslist =[1, 2, 3, 4, 5]  # adding list data# creating new columnshort_data["Added values"]= short_data["Salary"].add(list)  # displayshort_data
Output:As shown in the output image, it can be compared that the Added value column is having the added values of Salary column + list. Example #2: Adding series to series with null values
In this example, the Age column is added to the Salary column. Since the salary column contains null values too, by default it returns NaN no matter what is added. In this example, 5 is passed to replace null values with 5.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # age seriesage = data["Age"]  # na replacementna = 5  # adding values# storing to new columndata["Added values"]= data["Salary"].add(other = age, fill_value = na)  # displaydata
Output:As shown in the output image, the Added value column has added age column with 5 in case of Null values.
Python pandas-selection
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Type Assertions in Golang

22 Jun, 2020
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type. Basically, it is used to remove the ambiguity from the interface variables.
Syntax:
t := value.(typeName)

where value is a variable whose type must be an interface, typeName is the concrete type we want to check and underlying typeName value is assigned to variable t.
Example 1:
// Golang program to illustrate // the concept of type assertionspackage main  import (    "fmt")  // main functionfunc main() {          // an interface that has     // a string value    var value interface{} = "GeeksforGeeks"          // retrieving a value    // of type string and assigning    // it to value1 variable    var value1 string = value.(string)          // printing the concrete value    fmt.Println(value1)          // this will panic as interface    // does not have int type    var value2 int = value.(int)          fmt.Println(value2)}
Output:
GeeksforGeeks
panic: interface conversion: interface {} is string, not int

In the above code, since the value interface does not hold an int type, the statement triggered panic and the type assertion fails. To check whether an interface value holds a specific type, it is possible for type assertion to return two values, the variable with typeName value and a boolean value that reports whether the assertion was successful or not. This is shown in the following example:
Example 2:
// Golang program to show type// assertions with error checkingpackage main  import (    "fmt")  // main functionfunc main() {          // an interface that has     // an int value    var value interface{} = 20024          // retrieving a value    // of type int and assigning    // it to value1 variable    var value1 int = value.(int)          // printing the concrete value    fmt.Println(value1)          // this will test if interface    // has string type and    // return true if found or    // false otherwise    value2, test := value.(string)    if test {              fmt.Println("String Value found!")        fmt.Println(value2)    } else {              fmt.Println("String value not found!")    }}
Output:
20024
String value not found!

Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Go Variables
Strings in Golang
time.Parse() Function in Golang With Examples
Class and Object in Golang
Python | Blackman in numpy

22 Jul, 2021
Blackman window : It is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.
Parameters(numpy.blackman): 
M : int Number of points in the output window.
    If zero or less, an empty array is returned.

Returns: 
out : array
The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).
Example:
import numpy as np print(np.blackman(12))
Output:
[ -1.38777878e-17   3.26064346e-02   1.59903635e-01   4.14397981e-01
   7.36045180e-01   9.67046769e-01   9.67046769e-01   7.36045180e-01
   4.14397981e-01   1.59903635e-01   3.26064346e-02  -1.38777878e-17]

Plotting the window and its frequency response (requires SciPy and matplotlib):
Code : For Window:
import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift   window = np.blackman(51)  plt.plot(window) plt.title("Blackman window")plt.ylabel("Amplitude") plt.xlabel("Sample") plt.show() 
Output:
Code : For frequency:
import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift   window = np.blackman(51)  plt.figure()  A = fft(window, 2048) / 25.5mag = np.abs(fftshift(A))freq = np.linspace(-0.5, 0.5, len(A))response = 20 * np.log10(mag)response = np.clip(response, -100, 100)  plt.plot(freq, response)plt.title("Frequency response of Blackman window")plt.ylabel("Magnitude [dB]")plt.xlabel("Normalized frequency [cycles per sample]")plt.axis('tight')plt.show()
Output:
Python-numpy
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 OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
How to Get Volume Mixer in Windows 10 ?

08 Feb, 2021
Windows 10 was released in 2015 almost everyone liked the new interface. However, it removed the volume mixer shortcut which was available earlier. Using that one could easily adjust the volume for each application directly from the volume level control icon in the taskbar.
Windows 10 moved the volume mixer feature to the settings menu (Shortcut: Windows Key + I).
Settings -> System -> Sound ->  Advanced Sound Options -> App volume and device preferences 
Settings Menu
Default Volume Mixer in Windows 10 
However, opening the settings menu every time to change the volume levels for different applications is quite cumbersome.
So, a better approach is to use the old legacy volume mixer which was available on the older versions.
It can be enabled in Windows 10 in some simple steps. Here we will be editing the Windows Registry and any unintended changes can cause your computer to stop functioning. So, please follow the steps very carefully.
1. Open the Registry Editor
Open the Run window (Windows Key + R). Type regedit there and press Enter to open the Registry Editor. 
Run -> regedit
 Search for ‘Registry Editor’ in the windows start menu. 
Open Registry Editor using the start menu
Select Yes, if any prompt asks for permission then run the application.
2. Navigate to the following directory:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
You can just paste it in the address box and press enter.
3. Right-click on CurrentVersion and then go to New -> Key and name it MTCUVC.
Create New Key
Name the Key
4. Right-click on MTCUVC and then click on New -> DWORD(32-bit) Value. Name it as EnableMtcUvc.
Create New DWORD
Name DWORD
5. Open it and ensure the default Value Data is 0.
Ensure Value Data is 0
6. Now just close the Registry Editor window and by clicking on the speaker icon on the taskbar, you get the older volume control. 
You get the old volume control
In case you want to revert the changes, simply delete the MTCUVC Key created in the Registry Editor.
An alternative approach is to use the open-source EarTrumpet application available on the Microsoft Store, which gives a better-looking UI for the same task.
EarTrumpet UI
Technical Scripter 2020
How To
Operating Systems
Technical Scripter
TechTips
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Permanently Disable Swap in Linux?
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
Matplotlib.pyplot.loglog() function in Python

06 Jul, 2021
Prerequisites: Matplotlib
Matplotlib is a comprehensive library for creating interactive, static and animated visualizations in python. Using general-purpose GUI toolkits like wxPython, SciPy, Tkinter or SciPy, it provides an object-oriented API for embedding plots into applications. Matplotlib.pyplot is a collection of functions that makes Matplotlib work like MATLAB.
Here, we will be exploring loglog() function of Matplotlib.pyplot. It is used to plot a log scale over both x and y-axis.
Syntax:
loglog(X,Y)
Where,
X and Y refer to x and y coordinates respectively.
Other function used is linespace(). It returns evenly spaced numbers over a specified interval.
Syntax:
np.linspace(start, stop, num, endpoint, retstep, dtype, axis)
Where,
Start : The starting value of sequence from where you want to show the line, or we can say starting point of line
Stop : It is the end value of the sequence at where the line stops, unless ‘endpoint’ is set to False.
Num : Number of samples to generate. Must be non-negative. By default, it is 50.
Endpoint : It works same as stop. If it is True then stop is the last sample else stop is excluded from the sequence.
Retstep : If True, return (‘samples’, ‘step’), where `step` is the spacing between samples.
Dtype : The type of the output array.
Axis : The axis in the result to store the samples and it is relevant only if start or stop are array-like
Example : Without loglog()
Python
# importing required modulesimport matplotlib.pyplot as pltimport numpy as np  # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using plot functionplt.plot(x_input, y_input)
Output: 
Example : With loglog()
Python3
# importing required modulesimport matplotlib.pyplot as pltimport numpy as np  # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using loglog plotplt.loglog(x_input, y_input)
Output:
ruhelaa48
Matplotlib Pyplot-class
Picked
Python-matplotlib
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
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
ReactJS componentDidMount() Method

20 Dec, 2020
The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
All the AJAX requests and the DOM or state updation should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method.
Syntax:
componentDidMount()
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree. 
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';class App extends React.Component {  constructor(props) {    super(props);      // Initializing the state     this.state = { color: 'lightgreen' };  }  componentDidMount() {      // Changing the state after 2 sec    // from the time when the component    // is rendered    setTimeout(() => {      this.setState({ color: 'wheat' });    }, 2000);  }  render() {    return (      <div>        <p          style={{            color: this.state.color,            backgroundColor: 'rgba(0,0,0,0.88)',            textAlign: 'center',            paddingTop: 20,            width: 400,            height: 80,            margin: 'auto'          }}        >          GeeksForGeeks        </p>        </div>    );  }}export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
return statement vs exit() in main()

28 May, 2017
In C++, what is the difference between exit(0) and return 0 ?
When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.
Program 1 – – uses exit(0) to exit
#include<iostream>#include<stdio.h>#include<stdlib.h>  using namespace std;  class Test {public:  Test() {    printf("Inside Test's Constructor\n");  }    ~Test(){    printf("Inside Test's Destructor");    getchar();  }};  int main() {  Test t1;    // using exit(0) to exit from main  exit(0);}
Output:Inside Test’s Constructor
Program 2 – uses return 0 to exit
#include<iostream>#include<stdio.h>#include<stdlib.h>  using namespace std;  class Test {public:  Test() {    printf("Inside Test's Constructor\n");  }    ~Test(){    printf("Inside Test's Destructor");  }};  int main() {  Test t1;     // using return 0 to exit from main  return 0;}
Output:Inside Test’s ConstructorInside Test’s Destructor
Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.
Note that static objects will be cleaned up even if we call exit(). For example, see following program.
#include<iostream>#include<stdio.h>#include<stdlib.h>  using namespace std;  class Test {public:  Test() {    printf("Inside Test's Constructor\n");  }    ~Test(){    printf("Inside Test's Destructor");    getchar();  }};  int main() {  static Test t1;  // Note that t1 is static    exit(0);}
Output:Inside Test’s ConstructorInside Test’s Destructor
Contributed by indiarox. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Functions
exit
main
return
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction
Google Internship Interview Experience | Off-Campus 2022

19 Oct, 2021
Applications for Google Summer Internship 2022 were open and I applied. I did not expect to hear back from them as my application was off-campus, without referrals, from a tier 3 college. But I did hear back from Google with an interview offer around 3 weeks later. We also had an interviews preparation session.
I have undergone 2 rounds of technical interviews 45 min each.
Round 1: Interview 1
Warm-up problem – Given an array, create a new array that will have arr[i] and 2 * arr[i] from I iterating from 0 to array size. Return any shuffled version of this newly created array.
For example – input – >[1,2,3] —- new array -> [1,2,2,4,3,6] —— any shuffled version -> [2,3,4,6,2,1] 
The main problem – You are given the output of the previous question as an input in this question, You have to output the array which might have created this input.
For example – input ->[2,3,4,6,2,1] output – [1,2,3] 
Round 2: Interview 2
Tree problem – A tree node can either be an internal node or a leaf node.
If it is an internal node then it stores the sum of lengths of strings present in its left and right child.
If it is a leaf node then it stores string as well as its length.
Below is the tree node structure
Case 1)Only 1 node i.e. root node present
Root(length = 5,data = ABCDE) 
Case 2)Multiple nodes presents
Root(length = 21) 
left child(length = 5, data = ABCDE)
right child(length = 16)
left child of right child(length = 10, data = FGHIJKLMNO )
right child of right child(length = 6, data = PQRSTU )
Given input is above tree and N when You have to return the Nth character present in the tree.
 
Google
Marketing
Off-Campus
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021
Microsoft Interview Experience for SWE Intern
Zoho Interview Experience (Off-Campus ) 2022
Google STEP Interview Experience Internship 2022
Microsoft Interview Experience for SWE Intern (On-Campus)
Amazon Interview Questions
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1