code-rag-bench/online-tutorials huggingface dataset:
Integer decode() Method in Java - GeeksforGeeks

05 Dec, 2018
It is often seen that any integer within (” “) is also considered as string, then it is needed to decode that into the integer. The main function of java.lang.Integer.decode() method is to decode a String into an Integer. The method also accepts decimal, hexadecimal, and octal numbers.
Syntax :
public static Integer decode(String str)
Parameters: The method takes one parameter str of String data type and refers to the string needed to decode.
Return Value: This method returns an Integer object which holds the int value represented by the string str.
Exception: The method throws NumberFormatException, when the String contains an integer that cannot be parsed.
Examples:
Input: str_value = "50"
Output: 50

Input: str_value = "GFG"
Output: NumberFormatException
Below programs illustrate the java.lang.Integer.decode() method.Program 1:
// Java program to demonstrate working// of java.lang.Integer.decode() methodimport java.lang.*;  public class Gfg {      public static void main(String[] args)    {          Integer int1 = new Integer(22);        // string here given the value of 65        String nstr = "65";          // Returns an Integer object holding the int value        System.out.println("Actual Integral Number = "+        int1.decode(nstr));    }}
Actual Integral Number = 65

Program 2: When string value is passed a NumberFormatException is thrown.
// Java program to demonstrate working// of java.lang.Integer.decode() methodimport java.lang.*;  public class Gfg {      public static void main(String[] args)    {          Integer int1 = new Integer(22);          // String here passed as "geeksforgeeks"        String nstr = "geeksforgeeks";          System.out.println("Actual Integral Number = ");        System.out.println(int1.decode(nstr));    }}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "geeksforgeeks"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.valueOf(Integer.java:740)
    at java.lang.Integer.decode(Integer.java:1197)
    at Gfg.main(Gfg.java:15)

Java-Functions
Java-Integer
Java-lang 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
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
reflect.Select() Function in Golang with Examples - GeeksforGeeks

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.Select() Function in Golang is used to executes a select operation described by the list of cases. To access this function, one needs to imports the reflect package in the program.
Syntax:
func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)

Parameters: This function takes the following parameters:
cases : This parameter is the list of cases.
Return Value: This function returns the index of the chosen case.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Select() Function    package main   import (     "fmt"     "reflect" )  func main() {    c := make(chan int, 1)    vc := reflect.ValueOf(c)    succeeded := vc.TrySend(reflect.ValueOf(123))    fmt.Println(succeeded, vc.Len(), vc.Cap())      vSend, vZero := reflect.ValueOf(789), reflect.Value{}    branches := []reflect.SelectCase{        {Dir: reflect.SelectDefault, Chan: vZero, Send: vZero},        {Dir: reflect.SelectRecv, Chan: vc, Send: vZero},        {Dir: reflect.SelectSend, Chan: vc, Send: vSend},    }          // use of Select() method    selIndex, vRecv, sentBeforeClosed := reflect.Select(branches)    fmt.Println(selIndex)           fmt.Println(sentBeforeClosed)    fmt.Println(vRecv.Int())       vc.Close()    // Remove the send case branch this time,    // for it may cause panic.    selIndex, _, sentBeforeClosed = reflect.Select(branches[:2])    fmt.Println(selIndex, sentBeforeClosed) }        
Output:
true 1 1
1
true
123
1 false

Example 2:
// Golang program to illustrate// reflect.Select() Function    package main   import (     "fmt"     "reflect" )   func main() {     var sendCh = make(chan int)            var increaseInt = func(c chan int) {         for i := 0; i < 8; i++ {             c <- i         }         close(c)     }       go increaseInt(sendCh)       var selectCase = make([]reflect.SelectCase, 1)     selectCase[0].Dir = reflect.SelectRecv     selectCase[0].Chan = reflect.ValueOf(sendCh)       counter := 0     for counter < 1 {                      // use of Select() method         chosen, recv, recvOk := reflect.Select(selectCase)        if recvOk {             fmt.Println(chosen, recv.Int(), recvOk)           } else {             counter++         }     } }
Output:
0 0 true
0 1 true
0 2 true
0 3 true
0 4 true
0 5 true
0 6 true
0 7 true

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang
SDH Full Form - GeeksforGeeks

27 Jul, 2020
SDH stands for Synchronous Digital Hierarchy and it refers to a multiplex technology used in the telecommunication. Synchronous Optical Network is internationally used and is taken equal to SDH. Both technologies provide quite fast and low-priced network interconnection than PDH which stands for Plesiochronous Digital Hierarchy.
SDH allows the data stream to pass having low bit rates to be combined into high rate data streams. As the entire network is synchronous, individual bitstreams can be embedded into and are extracted from high rate data streams quiet easily. Initially, it was developed back in 1985 in the USA under the name of SONET.
Functions :SDH used to combine n signals with a bit rate of b to form data streams with bit rates of (n × b) on the synchronously clocked networks. Unlike PDH, the transmission paths that transfer individually have minimal clock discrepancies.
The synchronous mode of operation allows low order multiplex system such as communication links for telephone systems, to be inserted in higher hierarchy levels and then remove again via add and drop. SDH has following Synchronous Transport Modules (STM) and their rates are as follows :
1. STM-1 (155 Mbps)
2. STM-4 (622 Mbps)
3. STM-16 (2.5 Gbps)
4. STM-64 (10 Gbps) 
Advantages :
The structure is synchronous and is quite flexible.
It is capable of conveying Broadband signals.
The format is fully digital and fulfills the criteria of world standard.
It provides network transport services such as LAN in video conferencing and various interactive multimedia.
Speed of SDH is high as compared to PDH.
SDH allows quick recovery from any kind of failures.
It supports different kinds of operators.
Disadvantages :
The bandwidth utilization ratio is quite low as compared to PDH as because of OH bytes used for OAM.
There are various software’s being used and so it is more prone to viruses.
Pointers are being used for the adding or dropping of low rate signals and this causes the circuit to become more complex.
It requires complicated SDH materials due to a variety of management traffic types.
It cannot carry E2 due to the unavailability of the container.
Applications :
It is being used in electrical converters.
It is widely used in optical transports.
It can be used as carriers in ATM cells.
It can be used for bandwidth in demand.
It can be used to cable TV networks.
It can be used for T1 and T3 carriers.
Digital Electronics & Logic Design
Full Form
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Properties of Boolean Algebra
Difference between Multiplexer and Demultiplexer
Shift Micro-Operations in Computer Architecture
Latches in Digital Logic
Introduction to memory and memory units
DBA Full Form
HTTP Full Form
RDBMS Full Form
CDMA Full Form
What is IGMP(Internet Group Management Protocol)?
How do we use an enum type with a constructor in Java?


Enum type can have a private constructor that can be used to initialize instance fields. 
The EnumDemo class demonstrates this. It features a Food enum type with four constants: HAMBURGER, FRIES, HOTDOG, and ARTICHOKE. Notice that after each constant value is present in parentheses. This calls the constructor for that member to initialize the price field for that member. 
We iterate over the Food values in the for loop in the main() method. In this method, we first display the name of the food constant. Next, we examine the price for that food item and display whether the price is expensive or affordable. Following this, for fun, we demonstrate the use of a switch statement with the Food enum type.
public class EnumDemo {
   public enum Food {
      HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);
      Food(int price) {this.price = price;}
      private final int price;
      public int getPrice() {
         return price;
      }
}
public static void main(String[] args) {
   for (Food f : Food.values()) {
   System.out.print("Food: " + f + ", ");

      if (f.getPrice() >= 4) {
         System.out.print("Expensive, ");
      } else {
               System.out.print("Affordable, ");
   }
switch (f) {
      case HAMBURGER:
         System.out.println("Tasty");
      continue;
      case ARTICHOKE:
         System.out.println("Delicious");
      continue;
      default:
      System.out.println("OK");
    }
  }
 }
}
Food: HAMBURGER, Expensive, Tasty
Food: FRIES, Affordable, OK
Food: HOTDOG, Affordable, OK
Food: ARTICHOKE, Expensive, Delicious
How to draw different shapes using the Python Turtle library?

In this program, we will draw different shapes using the Turtle
library in Python. Turtle is a python feature like a drawing board, which lets you command a turtle to draw all over it. The different shapes that we are going to draw are square, rectangle, circle and a hexagon.
Step 1: Take lengths of side for different shapes as input.
Step 2: Use different turtle methods like forward() and left() for drawing different shapes.
import turtle
t = turtle.Turtle()

#SQUARE
side = int(input("Length of side: "))
for i in range(4):
   t.forward(side)
   t.left(90)

#RECTANGLE
side_a = int(input("Length of side a: "))
side_b = int(input("Length of side b: "))
t.forward(side_a)
t.left(90)
t.forward(side_b)
t.left(90)
t.forward(side_a)
t.left(90)
t.forward(side_b)
t.left(90)

#CIRCLE
radius = int(input("Radius of circle: "))
t.circle(radius)

#HEXAGON
for i in range(6):
   t.forward(side)
   t.left(300)
SQUARE:
Length of side: 100
RECTANGLE:
Length of side a: 100
Length of side b: 20
CIRCLE:
Radius of circle: 60

HEXAGON:Length of side: 100
Check if two strings are equal or not in Arduino

In order to check if two strings are equal, the .equals() function can be used. This returns a Boolean. True if both the strings are equal, else false. An example code is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello";
   String s2 = "Hello";
   String s3 = "World";
   if(s1.equals(s2)){
      Serial.print("s1 equals s2");
      }
   if(s1.equals(s3)){
      Serial.print("s1 equals s3");
      }
   if(s2.equals(s3)){
      Serial.print("s2 equals s3");
   }
}
void loop() {
   // put your main code here, to run repeatedly:
}
As you would have guessed, only "s1 equals s2" gets printed on the Serial Monitor.
RxJava - Single Observable

The Single class represents the single value response. Single observable can only emit either a single successful value or an error. It does not emit onComplete event.
Following is the declaration for io.reactivex.Single<T> class −
public abstract class Single<T>
   extends Object
      implements SingleSource<T>

Following is the sequential protocol that Single Observable operates −
onSubscribe (onSuccess | onError)?

Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import java.util.concurrent.TimeUnit;

import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;

public class ObservableTester  {
   public static void main(String[] args)  throws InterruptedException {
      //Create the observable
      Single<String> testSingle = Single.just("Hello World");

      //Create an observer
      Disposable disposable = testSingle
         .delay(2, TimeUnit.SECONDS, Schedulers.io())
         .subscribeWith(
         new DisposableSingleObserver<String>() {

         @Override
         public void onError(Throwable e) { 
            e.printStackTrace();
         }

         @Override
         public void onSuccess(String value) {
            System.out.println(value);
         }
      }); 
      Thread.sleep(3000);
      //start observing
      disposable.dispose();
   }
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java

Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester

It should produce the following output −
Hello World

 Print
 Add Notes
 Bookmark this page
Create Mirror Image using MATLAB - GeeksforGeeks

21 Nov, 2019
Prerequisite: Image representation in MATLAB
In MATLAB, Images are stored in matrices, in which each element of the matrix corresponds to a single discrete pixel of the image. We can get the mirror image of the given image if we reverse the order of the pixels (elements of the matrix) in each row.
Code #1: Using MATLAB Library function
% Read the target image fileimg = imread('leaf.png');  % Reverse the element in each rowmirror_image = flip(img, 2);  % Display the mirror imageimshow(mirror_img); title('Mirror image');
 Code #2: Using matrix manipulation
% Read the target image fileimg = imread('leaf.png');  % Flip the columns left to rightmirror_image = img(:, end :, -1:, 1, :);  % Display the mirror imageimshow(mirror_img); title('Mirror image');          
 Code #3: Using matrix manipulation (Using loops)
Approach:
Read the source image file in MATLAB environment
Get the Dimensions of the image matrix
Reverse the order of the elements of each row in every image plane
Display the mirror image
Below is the implementation of the above approach:
% Read the target image fileimg = imread('leaf.png');  % Get the dimensions of the image[x, y, z] =size(img);    % Reverse elements of each row% in every image planefor plane = 1: z    for i = 1 : x        len = y;         for j = 1 : y              % To reverse the order of the element            % of a row we can swap the             % leftmost element of the row with            % its rightmost element                    if j < y/2                 temp = img(i, j, plane);                img(i, j, plane) = img(i, len, plane);                img(i, len, plane) = temp;                len = len - 1;            end        end    endend    % Display the mirror imageimshow(img); title('Mirror image');
Input Image: leaf.png
Output:
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Decision Tree Introduction with example
Reinforcement learning
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
Clustering in Machine Learning
KDD Process in Data Mining
Check if a linked list is Circular Linked List in C++

Here we will see, hoe to check a linked list is circular linked list or not. To check whether the linked list is circular or not, we will store the header node into some other variable, then traverse the list, if we get null at the next part of any node, then that is not circular, otherwise we will check the next node is same as the stored node or not, if so then that is circular.
 Live Demo
#include <iostream>
using namespace std;
class Node{
   public:
   int data;
   Node *next;
};
Node* getNode(int data){
   Node *newNode = new Node;
   newNode->data = data;
   newNode->next = NULL;
   return newNode;
}
bool isCircularList(Node *start){
   if(start == NULL)
      return true;
   Node *node = start->next;
   while(node != NULL && node != start){
      node = node->next;
   }
   if(node == start)
      return true;
      return false;
}
int main() {
   Node *start = getNode(10);
   start->next = getNode(20);
   start->next->next = getNode(30);
   start->next->next->next = getNode(40);
   start->next->next->next->next = getNode(50);
   start->next->next->next->next->next = start;
   if (isCircularList(start))
      cout << "The list is circular list";
   else
      cout << "The list is not circular list";
}
The list is circular list
Repeated String Match | Practice | GeeksforGeeks

Given two strings A and B, find the minimum number of times A has to be repeated such that B becomes a substring of the repeated A. If B cannot be a substring of A no matter how many times it is repeated, return -1.
Example 1:
Input: A = "abcd", B = "cdabcdab"
Output: 3
Explanation: After repeating A three times, 
we get "abcdabcdabcd".
Example 2:
Input: A = "aa", B = "a"
Output: 1
Explanation: B is already a substring of A.

Your Task:  
You don't need to read input or print anything. Complete the function repeatedStringMatch() which takes strings A and B as input parameters and returns the minimum number of operations to complete the task. If it is not possible then return -1.
Expected Time Complexity: O(|A| * |B|)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ |A|, |B| ≤ 4 * 103
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
qqplot (Quantile-Quantile Plot) in Python - GeeksforGeeks

25 Nov, 2019
When the quantiles of two variables are plotted against each other, then the plot obtained is known as quantile – quantile plot or qqplot. This plot provides a summary of whether the distributions of two variables are similar or not with respect to the locations.
Interpretations
All point of quantiles lie on or close to straight line at an angle of 45 degree from x – axis. It indicates that two samples have similar distributions.And in practice it is always not possible to get such a 100 percent clear straight line but the plot looks like below. Here the points are lying nearly on the straight line.
The y – quantiles are lower than the x – quantiles. It indicates y values have a tendency to be lower than x values.And in practice it is not always possible to get 100 percent as shown above but the plot looks as shown below. Here you can see that most of the points are lying below the line and few points are above the line. Hence we can say that the distributions are not the same.
The x – quantiles are lower than the y – quantiles. It indicates x values have a tendency to be lower than the y values.
Indicates that there is a breakpoint up to which the y – quantiles are lower than the x – quantiles and after that point the y – quantiles are higher than the x – quantiles.
Quantile – Quantile plot using statsmodel in Python –
import numpy as npimport statsmodels.api as smimport pylab as py  # np.random generates different random numbers# whenever the code is executed# Note: When you execute the same code # the graph look different than shown below.  # Random data points generateddata_points = np.random.normal(0, 1, 100)      sm.qqplot(data_points, line ='45')py.show()
Output:
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Activation functions in Neural Networks
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
UGC-NET | UGC NET CS 2016 July – III | Question 73

27 Apr, 2018
Consider the following game tree in which root is a maximizing node and children are visited left to right. What nodes will be pruned by the alpha-beta pruning ?(A) I(B) HI(C) CHI(D) GHIAnswer: (B)Explanation:We have to maximize A and minimize B and C. Minimum of B is 3 and C is 2 But max from B is 12 and max from C is 15. So, there is no need of further expanding H and I. Because whatever value their successor will produce will be immaterial. Hence H I are pruned. For more information on Game theory Refer:Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)Option (B) is correct.Quiz of this Question
UGC NET CS 2016 July – III
UGC-NET
UGC-NET-UGC NET CS 2016 July – III
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UGC-NET | UGC NET CS 2018 July - II | Question 23
UGC-NET | UGC NET CS 2015 Jun - III | Question 35
UGC-NET | UGC NET CS 2015 Jun - III | Question 33
UGC-NET | UGC NET CS 2015 Jun - III | Question 32
UGC-NET | UGC NET CS 2015 Dec - II | Question 16
UGC-NET | UGC NET CS 2016 Aug - III | Question 32
UGC-NET | UGC NET CS 2015 Jun - III | Question 64
UGC-NET | UGC NET CS 2016 July – II | Question 22
UGC-NET | UGC NET CS 2016 July – III | Question 32
UGC-NET | UGC NET CS 2014 Dec - II | Question 35
How to sort mixed numeric/alphanumeric array in JavaScript

Suppose we have an array of alphanumeric strings like this −
const arr = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3'];
We are required to write a JavaScript function that in one such array as one and the only argument.
And the function should sort this array inplace −
The strings that contains only numbers should come first sorted in increasing order.
The strings containing a combination of alphabets and numbers should be sorted first according to alphabets and then according to numbers in increasing order.
Therefore, the output should look like −
const output = ['1', '2', 'A1', 'A2', 'A3', 'A3A', 'A3B', 'A4', 'A10', 'A11', 'A12', 'B2', 'B10', 'F1', 'F3'];
const arr = ['A1', 'A10', 'A11', 'A12', 'A3A', 'A3B', 'A3', 'A4', 'B10', 'B2', 'F1', '1', '2', 'F3'];
const alphaNumericSort = (arr = []) => {
   const sorter = (a, b) => {
      const isNumber = (v) => (+v).toString() === v;
      const aPart = a.match(/\d+|\D+/g);
      const bPart = b.match(/\d+|\D+/g);
      let i = 0; let len = Math.min(aPart.length, bPart.length);
      while (i < len && aPart[i] === bPart[i]) { i++; };
         if (i === len) {
            return aPart.length - bPart.length;
      };
      if (isNumber(aPart[i]) && isNumber(bPart[i])) {
         return aPart[i] - bPart[i];
      };
      return aPart[i].localeCompare(bPart[i]); };
      arr.sort(sorter);
};
alphaNumericSort(arr);
console.log(arr);
And the output in the console will be −
[
   '1', '2', 'A1',
   'A3', 'A3A', 'A3B',
   'A4', 'A10', 'A11',
   'A12', 'B2', 'B10',
   'F1', 'F3'
]
How to delete document by _id using MongoDB?

To delete by _id, use remove() in MongoDB. Following is the syntax −
db.yourCollectionName.remove({_id:yourObjectId});
To understand the above syntax, let us create a collection with documents −
> db.demo518.insertOne({"ClientName":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b02db3fbf26334ef610e")
}
> db.demo518.insertOne({"ClientName":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b030b3fbf26334ef610f")
}
> db.demo518.insertOne({"ClientName":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88b035b3fbf26334ef6110")
}
Display all documents from a collection with the help of find() method −
> db.demo518.find();
This will produce the following output −
{ "_id" : ObjectId("5e88b02db3fbf26334ef610e"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5e88b030b3fbf26334ef610f"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e88b035b3fbf26334ef6110"), "ClientName" : "David" }
Following is the query to delete by _id −
> db.demo518.remove({_id:ObjectId("5e88b02db3fbf26334ef610e")});
WriteResult({ "nRemoved" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo518.find();
This will produce the following output −
{ "_id" : ObjectId("5e88b030b3fbf26334ef610f"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e88b035b3fbf26334ef6110"), "ClientName" : "David" }
GATE | GATE-CS-2015 (Set 3) | Question 48

28 Jun, 2021
In the network 200.10.11.144/27, the fourth octet (in decimal) of the last IP address of the network which can be assigned to a host is ________(A) 158(B) 255(C) 222(D) 223Answer: (A)Explanation:
The last or fourth octet of network address is 144 
144 in binary is 10010000.

The first three bits of this octal are fixed as 100, 
the remaining bits can get maximum value as 11111.  
So the maximum possible last octal IP address is 
10011111 which is 159.

The question seems to by asking about host address. The
address with all 1s in host part is broadcast address 
and can't be assigned to a host. So the maximum possible 
last octal in a host IP is 10011110 which is 158.

The maximum possible network address that can be assigned 
is 200.10.11.158/31 which has last octet as 158.

Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
Python – Reverse Dictionary Keys Order

04 May, 2020
Sometimes, while working with dictionary, we can have a problem in which we need to reverse the order of dictionary. This is quite a common problem and can have application in many domains including day-day programming and web development. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using OrderedDict() + reversed() + items()This method is for older versions of Python. Older versions don’t keep order in dictionaries, hence have to converted to OrderedDict to execute this task.
# Python3 code to demonstrate working of # Reverse Dictionary Keys Order# Using OrderedDict() + reversed() + items()from collections import OrderedDict  # initializing dictionarytest_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Reverse Dictionary Keys Order# Using OrderedDict() + reversed() + items()res = OrderedDict(reversed(list(test_dict.items())))  # printing result print("The reversed order dictionary : " + str(res)) 
The original dictionary : {‘is’: 2, ‘best’: 5, ‘gfg’: 4}The reversed order dictionary : OrderedDict([(‘gfg’, 4), (‘best’, 5), (‘is’, 2)])
 
Method #2 : Using reversed() + items()The combination of above functions can be used to solve this problem. This is for newer versions of Python, which have dictionary in incoming order of elements.
# Python3 code to demonstrate working of # Reverse Dictionary Keys Order# Using reversed() + items()  # initializing dictionarytest_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Reverse Dictionary Keys Order# Using reversed() + items()res = dict(reversed(list(test_dict.items())))  # printing result print("The reversed order dictionary : " + str(res)) 
The original dictionary : {'gfg': 4, 'is': 2, 'best': 5}
The reversed order dictionary : {'best': 5, 'is': 2, 'gfg': 4}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
QUARTER() Function in MySQL

02 Dec, 2020
QUARTER() function in MySQL is used to return the quarter of the year for a given date value. It returns a number from 1 to 4. 
Syntax :
QUARTER(date)
Parameter : The function accepts only one parameter 
date : The date or DateTime from which we want to extract the quarter.
Returns : It returns 1 if the given date is in range January-March. 2 for April-June.3 for July-September and if the date is in the range from October-December it returns 4.
Example-1 : 
Finding the Current QUARTER Using QUARTER() Function.
SELECT QUARTER(NOW()) AS CURRENT_QUARTER;
Output :
Example-2 : 
Finding the Quarter from given DateTime Using QUARTER() Function.
SELECT QUARTER('2020-04-26 08:09:22') AS QUARTER_NUMBER;
Output :
Example-3 : 
Finding the Quarter from given DateTime Using QUARTER() Function when the date is NULL.
SELECT QUARTER(NULL) AS QUARTER_NUMBER;
Output :
Example-4 : 
The QUARTER function can also be used to find the total product sold for every QUARTER. To demonstrate create a table named.
Product :
CREATE TABLE Product(
  Product_id INT AUTO_INCREMENT,  
  Product_name VARCHAR(100) NOT NULL,
  Buying_price DECIMAL(13, 2) NOT NULL,
  Selling_price DECIMAL(13, 2) NOT NULL,
  Selling_Date Date NOT NULL,
  PRIMARY KEY(Product_id)
);
Now insert some data to the Product table :
INSERT INTO  
  Product(Product_name, Buying_price, Selling_price, Selling_Date)
VALUES
  ('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ),
  ('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ),
  ('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ),
  ('BMW X5', 5000500.00, 7006500.00, '2018-10-18'  ),
  ('Jaguar XF', 5000000, 7507000.00, '2018-01-27'  ),
  ('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2018-04-01'  ),
  ('Jaguar F-PACE', 5000000.00, 7000000.00, '2018-12-26'  ),
  ('Porsche Macan', 6500000.00, 8000000.00, '2018-04-16' ) ;
So, Our table looks like :
Now, we are going to find the number of products sold per quarter by using the MONTH () function.
SELECT 
    QUARTER(Selling_Date) as quarter, 
    COUNT(Product_id) as PRODUCT_SOLD 
FROM 
    Product   
GROUP BY QUARTER(Selling_Date)       
ORDER BY QUARTER(Selling_Date);
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get boxplot data for Matplotlib boxplots?

To get boxplot data for Matplotlib boxplot we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make data frame using pandas.
Make a box plot from DataFrame columns.
Get boxplot's outliers, boxes, medians and whiskers data.
Prit all the above information.
To display the figure, use show() method.
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt

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

df = pd.DataFrame(dict(age=[23, 45, 21, 15, 12]))
_, bp = pd.DataFrame.boxplot(df, return_type='both')
outliers = [flier.get_ydata() for flier in bp["fliers"]]
boxes = [box.get_ydata() for box in bp["boxes"]]
medians = [median.get_ydata() for median in bp["medians"]]
whiskers = [whiskers.get_ydata() for whiskers in bp["whiskers"]]

print("Outliers: ", outliers)
print("Boxes: ", boxes)
print("Medians: ", medians)
print("Whiskers: ", whiskers)

plt.show()
Outliers: [array([45])]
Boxes: [array([15., 15., 23., 23., 15.])]
Medians: [array([21., 21.])]
Whiskers: [array([15., 12.]), array([23., 23.])]
How to check whether a given string is an absolute URL or not in JavaScript ? - GeeksforGeeks

12 May, 2021
In this article, we will learn how to return true if the given string is an absolute URL in JavaScript. There are two types of URLs either relative or absolute.
Absolute URL: It is a URL that contains all the information that is important for locating the resources. The thing which is included in the absolute URL is the protocol (HTTPS) in the site’s domain at the starting point of the URL.
Relative URL: It is a short URL that holds the name of the domain and exact things which is only allowed to access on the same server or page. 
Syntax:
/* Absolute Url */
https://www.geeksforgeeks.org/

/* Relative Url */
geeksforgeeks.org
The task is to create a JavaScript function that takes an argument as a URL and returns true if the URL is an absolute link and if not then return false.
Approach: Absolute URL has protocol (HTTPS) included in the starting. We can simply check if the URL has https:// in front or not. If it is found we return true else false. 
For checking protocol, we use regex (regular expression). 
Syntax:
^https:\/\/
Where,
^: It is used for selecting from starting.
https: It is used for selecting the text.
\: It is used for a special regex character matches the front character.
Example: Below example explains the use of above approach.
HTML
<!DOCTYPE html><html lang="en">  <body>    <h1 style="color: green;">GeeksforGeeks</h1>    <form action="#">        <label for="#">Please input the url</label>        <input type="text" id="url">        <input type="button" onclick="absolute_url()" value="Click">        <h2 id="result"></h2>    </form>      <script>        function absolute_url() {            let urls = document.getElementById('url').value;            let result = document.getElementById('result');              // Regex pattern for checking            var pattern = /^https:\/\//i;              // Check if pattern is there in the string             // or not with .test() method            if (pattern.test(urls)) {                result.innerText = "true";            }            else {                result.innerText = "false";            }        }    </script></body>  </html>
Output:
For non-absolute URL’s:
For absolute URL’s:
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
jQuery | event.preventDefault() Method - GeeksforGeeks

20 Feb, 2019
The preventDefault() Method in jQuery is used to stop the default action of selected element to occur. It is also used to check whether preventDefault() method is called for the selected element or not.
Syntax:
event.preventDefault()
Parameter: It does not accept any parameter.
Return Value: It returns the selected element with the applied change.
Example 1: This example uses preventDefault() method to stop to open the new link.
<!DOCTYPE html><html>   <head>    <title>        jQuery event.preventDefault() Method    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <style>        body {            width: 50%;            height: 40%;            padding: 20px;            border: 2px solid green;            font-size: 20px;        }    </style>          <!-- Script to use event.preventDefault() method -->    <script>        $(document).ready(function() {            $("a").click(function(event) {                event.preventDefault();                alert("The required page will not be open");            });        });    </script></head>   <body>    <a href="https://www.geeksforgeeks.org">        Welcome to GeeksforGeeks!    </a></body>   </html>
Output:Before Click on the link:After click on the link:
Example 2: This example uses event.preventDefault() method to stop submitting the form.
<!DOCTYPE html><html>   <head>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <style>        body {            width: 50%;            height: 40%;            padding: 20px;            border: 2px solid green;            font-size: 20px;        }        input {            width: 220px;            height: 30px;            border-radius: 10px;        }    </style>          <!-- Script to use event.preventDefault() method -->    <script>        $(document).ready(function() {            $("button").click(function(event) {                event.preventDefault();                alert("This form will not submit");            });        });    </script></head>   <body>       <input type="text" placeholder="enter name" />          <br><br>          <button>Submit </button></body>   </html>
Output:Before Click on the button:After Click on the button:
jQuery-Events
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Dictionary.Count Property in C#

The Dictionary. Count property in C# gets the number of key/value pairs in the Dictionary.
public int Count { get; }
Let us now see an example to implement the Dictionary. Count property −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      if (dict.ContainsValue("Angelina"))
         Console.WriteLine("Value found!");
      else
         Console.WriteLine("Value isn't in the dictionary!");
      dict.Clear();
      Console.WriteLine("Cleared Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value isn't in the dictionary!
Cleared Key/value pairs...
Count of elements now = 0
Let us now see another example to implement the Dictionary. Count property −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "David");
      dict.Add("Two", "Brian");
      dict.Add("Three", "Paul");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
   }
}
This will produce the following output −
Count of elements = 5
CSS Responsive Table

A responsive table will display a horizontal scroll bar if the screen is too 
small to display the full content:
Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
Make a fancy table
This example demonstrates how to create a fancy table.
Set the position of the table caption
This example demonstrates how to position the table caption.
Set the border to "2px solid green" for table, th and td elements.
<style>
 {
  : 2px solid green;
}
</style>

<body>
<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
  </tr>
  <tr>
    <td>Peter</td>
    <td>Griffin</td>
  </tr>
  <tr>
    <td>Lois</td>
    <td>Griffin</td>
  </tr>
</table>
</body>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Plotting points on the surface of a sphere in Python's Matplotlib

To plot points on the surface of a sphere in Python, we can use plot_surface() method.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add a set of subplots using add_subplot() method with 3d projection.
Add a set of subplots using add_subplot() method with 3d projection.
Initialize a variable, r.
Initialize a variable, r.
Get the theta value for spherical points and x, y, and z data points using numpy.
Get the theta value for spherical points and x, y, and z data points using numpy.
Plot the surface using plot_surface() method.
Plot the surface using plot_surface() method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
r = 0.05
u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:20j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)
ax.plot_surface(x, y, z, cmap=plt.cm.YlGnBu_r)
plt.show()
math.Round() Function in Golang With Examples - GeeksforGeeks

13 Apr, 2020
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can round off the given number to the nearest integer(rounding half away from zero) with the help of Round() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Round() function.
Syntax:
func Round(a float64) float64
If you pass -Inf or +Inf in this function like Round(-Inf) or Round(+Inf), then this function will return -Inf or +Inf.
If you pass -0 or +0 in this function like Round(-0) or Round(+0), then this function will return -0 or +0.
If you pass NaN in this function like Round(NaN), then this function will return NaN.
Example 1:
// Golang program to illustrate how to// round off the given number to the // nearest integer  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding the nearest integer    // of the given numbers    // Using Round() function    res_1 := math.Round(36.98)    res_2 := math.Round(-100.98)    res_3 := math.Round(math.Inf(-1))    res_4 := math.Round(math.NaN())    res_5 := math.Round(math.Inf(1))      // Displaying the result    fmt.Printf("Result 1: %.1f", res_1)    fmt.Printf("\nResult 2: %.1f", res_2)    fmt.Printf("\nResult 3: %.1f", res_3)    fmt.Printf("\nResult 4: %.1f", res_4)    fmt.Printf("\nResult 5: %.1f", res_5)  }
Output:
Result 1: 37.0
Result 2: -101.0
Result 3: -Inf
Result 4: NaN
Result 5: +Inf

Example 2:
// Golang program to illustrate how to// round off the given number to the// nearest integer  package main  import (    "fmt"    "math")  // Main functionfunc main() {      // Finding the nearest integer    // of the given numbers    // Using Round() function    nvalue_1 := math.Round(49.89)    nvalue_2 := math.Round(-4.567)      // Finding sum of the given numbers    res := nvalue_1 + nvalue_2    fmt.Printf("%.2f + %.2f = %.2f",           nvalue_1, nvalue_2, res)  }
Output:
50.00 + -5.00 = 45.00
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to Trim a String in Golang?
How to Parse JSON in Golang?
Inheritance in GoLang
How to compare times in Golang?
Different Ways to Find the Type of Variable in Golang
Get row data for the lowest and highest values in a MySQL column

For the lowest values in a MySQL column, use the MIN() method and for highest, use the MAX() method. Let us first create a table −
mysql> create table DemoTable
(
   CustomerName varchar(20),
   ProductAmount int
) ;
Query OK, 0 rows affected (1.03 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris',3599);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',7843);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Mike',97474);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Bob',65884);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+---------------+
| CustomerName | ProductAmount |
+--------------+---------------+
| Chris        |          3599 |
| David        |          7843 |
| Mike         |         97474 |
| Bob          |         65884 |
+--------------+---------------+
4 rows in set (0.00 sec)
Following is the query to get the lowest and highest values using MAX() and MIN() −
mysql> select *from DemoTable where ProductAmount=(select max(ProductAmount) from DemoTable)
   or ProductAmount=(select min(ProductAmount) from DemoTable);
This will produce the following output −
+--------------+---------------+
| CustomerName | ProductAmount |
+--------------+---------------+
| Chris        |          3599 |
| Mike         |         97474 |
+--------------+---------------+
2 rows in set (0.00 sec)
Comparing two columns in a single MySQL query to get one row?

For this, you can use ORDER BY clause. Let us first create a table −
mysql> create table DemoTable
-> (
-> Num1 int,
-> Num2 int
-> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(60,249);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(59,250);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+------+
| Num1 | Num2 |
+------+------+
| 60   | 249  |
| 59   | 250  |
+------+------+
2 rows in set (0.00 sec)
Here is the query to comparing with two maximum of columns get one row −
mysql> select *from DemoTable
-> order by Num2 DESC,Num1 DESC limit 1;
Here is the query to comparing with two maximum of columns get one row −
mysql> select *from DemoTable
-> order by Num2 DESC,Num1 DESC limit 1;
This will produce the following output −
+------+------+
| Num1 | Num2 |
+------+------+
| 59   | 250  |
+------+------+
1 row in set (0.00 sec)