code-rag-bench/online-tutorials huggingface dataset:
Python | Intersect two dictionaries through keys

28 Feb, 2019
Given two dictionaries, the task is to find the intersection of these two dictionaries through keys. Let’s see different ways to do this task.Method #1: Using dict comprehension
# Python code to demonstrate# intersection of two dictionaries # using dict comprehension  # inititialising dictionaryini_dict1 = {'nikhil': 1, 'vashu' : 5,              'manjeet' : 10, 'akshat' : 15}ini_dict2 = {'akshat' :15, 'nikhil' : 1, 'me' : 56}  # printing initial jsonprint ("initial 1st dictionary", ini_dict1)print ("initial 2nd dictionary", ini_dict2)  # intersecting two dictionariesfinal_dict = {x:ini_dict1[x] for x in ini_dict1                               if x in ini_dict2}  # printing final resultprint ("final dictionary", str(final_dict))
initial 1st dictionary {‘vashu’: 5, ‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15}initial 2nd dictionary {‘nikhil’: 1, ‘me’: 56, ‘akshat’: 15}final dictionary {‘nikhil’: 1, ‘akshat’: 15}
 Method #2: Using & operator
# Python code to demonstrate# intersection of two dictionaries # using dict comprehension  # inititialising dictionaryini_dict1 = {'nikhil': 1, 'vashu' : 5,             'manjeet' : 10, 'akshat' : 15}ini_dict2 = {'akshat' :15, 'nikhil' : 1, 'me' : 56}  # printing initial jsonprint ("initial 1st dictionary", ini_dict1)print ("initial 2nd dictionary", ini_dict2)  # intersecting two dictionariesfinal_dict = dict(ini_dict1.items() & ini_dict2.items())  # printing final resultprint ("final dictionary", str(final_dict))
initial 1st dictionary {‘vashu’: 5, ‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15}initial 2nd dictionary {‘nikhil’: 1, ‘akshat’: 15, ‘me’: 56}final dictionary {‘nikhil’: 1, ‘akshat’: 15}
Marketing
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
Material Design Lite - Icons

MDL provides a range of CSS classes to apply various predefined visual and behavioral enhancements and display the different types of checkboxes as icons. The following tables lists down the available classes and their effects.
mdl-icon-toggle
Identifies label as an MDL component and is required on label element.
mdl-js-icon-toggle
Sets basic MDL behavior to label and is required on label element.
mdl-icon-toggle__input
Sets basic MDL behavior to icon-toggle and is required on input element (icon-toggle).
mdl-icon-toggle__label
Sets basic MDL behavior to caption and is required on on i element (icon).
mdl-js-ripple-effect
Sets ripple click effect and is optional; goes on the label element and not on the input element (icon-toggle).
The following example showcases the use of mdl-icon-toggle classes to show different types of checkboxes as icons.
<html>
   <head>
      <script 
         src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js">
      </script>
      <link rel = "stylesheet" 
         href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css">
      <link rel = "stylesheet" 
         href = "https://fonts.googleapis.com/icon?family=Material+Icons">	  
   </head>
   
   <body>
      <table>
         <tr><td>On Icon</td><td>Off Icon</td>
            <td>Disabled Icon</td></tr>
         <tr>
            <td> 
               <label class = "mdl-icon-toggle mdl-js-icon-toggle mdl-js-ripple-effect" 
                  for = "icon-toggle-1">
                  <input type = "checkbox" id = "icon-toggle-1" 
                     class = "mdl-icon-toggle__input" checked>
                  <i class = "mdl-icon-toggle__label material-icons">format_bold</i>
               </label>
            </td>
            
            <td>
               <label class = "mdl-icon-toggle mdl-js-icon-toggle mdl-js-ripple-effect" 
                  for = "icon-toggle-2">
                  <input type = "checkbox" id = "icon-toggle-2" 
                     class = "mdl-icon-toggle__input">
                  <i class = "mdl-icon-toggle__label material-icons">format_italic</i>
               </label>
            </td>
            
            <td>
               <label class = "mdl-icon-toggle mdl-js-icon-toggle mdl-js-ripple-effect" 
                  for = "icon-toggle-2">
                  <input type = "checkbox" id = "icon-toggle-2" 
                     class = "mdl-icon-toggle__input" disabled>
                  <i class = "mdl-icon-toggle__label material-icons">format_underline</i>
               </label>
            </td>
         </tr>
      </table>   
   
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Pascal - For-do Loop

A for-do loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax for the for-do loop in Pascal is as follows −
for < variable-name > := < initial_value > to [down to] < final_value > do 
   S;
Where, the variable-name specifies a variable of ordinal type, called control variable or index variable; initial_value and final_value values are values that the control variable can take; and S is the body of the for-do loop that could be a simple statement or a group of statements.
For example,
for i:= 1 to 10 do writeln(i);
Here is the flow of control in a for-do loop −
The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for-do loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for-do loop.
After the body of the for-do loop executes, the value of the variable is either increased or decreased.
After the body of the for-do loop executes, the value of the variable is either increased or decreased.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for-do loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for-do loop terminates.
program forLoop;
var
   a: integer;

begin
   for a := 10  to 20 do
   
   begin
      writeln('value of a: ', a);
   end;
end.
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
T-SQL - UPDATE Statement

The SQL Server UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected.
Following is the basic syntax of UPDATE query with WHERE clause −
UPDATE table_name 
SET column1 = value1, column2 = value2...., columnN = valueN 
WHERE [condition];

You can combine N number of conditions using AND or OR operators.
Consider the CUSTOMERS table having the following records −
ID  NAME       AGE       ADDRESS             SALARY 
1   Ramesh     32        Ahmedabad           2000.00 
2   Khilan     25        Delhi               1500.00 
3   kaushik    23        Kota                2000.00 
4   Chaitali   25        Mumbai              6500.00 
5   Hardik     27        Bhopal              8500.00 
6   Komal      22        MP                  4500.00 
7   Muffy      24        Indore              10000.00 

Following command is an example, which would update ADDRESS for a customer whose ID is 6 −
UPDATE CUSTOMERS 
SET ADDRESS = 'Pune' 
WHERE ID = 6; 
CUSTOMERS table will now have the following records −
ID  NAME       AGE       ADDRESS             SALARY 
1   Ramesh     32        Ahmedabad           2000.00 
2   Khilan     25        Delhi               1500.00 
3   kaushik    23        Kota                2000.00 
4   Chaitali   25        Mumbai              6500.00 
5   Hardik     27        Bhopal              8500.00 
6   Komal      22        Pune                4500.00 
7   Muffy      24        Indore              10000.00 

If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to use WHERE clause. UPDATE query would be as follows −
UPDATE CUSTOMERS 
SET ADDRESS = 'Pune', SALARY = 1000.00;
CUSTOMERS table will now have the following records.
ID  NAME       AGE       ADDRESS          SALARY 
1   Ramesh     32        Pune             1000.00 
2   Khilan     25        Pune             1000.00 
3   kaushik    23        Pune             1000.00 
4   Chaitali   25        Pune             1000.00 
5   Hardik     27        Pune             1000.00 
6   Komal      22        Pune             1000.00 
7   Muffy      24        Pune             1000.00 


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
How to close JFrame on the click of a Button in Java

Set frame.dispose() on the click of a button to close JFrame. At first create a button and frame −
JFrame frame = new JFrame();
JButton button = new JButton("Click to Close!");
Now, close the JFrame on the click of the above button with Action Listener −
button.addActionListener(e -> {
   frame.dispose();
});
The following is an example to close JFrame on the click of a Button −
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JButton button = new JButton("Click to Close!");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(button);
      button.addActionListener(e -> {
         frame.dispose();
      });
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setPreferredSize(new Dimension(550, 300));
      frame.getContentPane().setBackground(Color.ORANGE);
      frame.pack();
      frame.setVisible(true);
   }
}
When you will click on the button “Click to Close”, the frame will close.
How to write a class inside an interface in Java?

Defining a class within an interface is allowed in Java. If the methods of an interface accept a class as an argument and the class is not used elsewhere, in such cases we can define a class inside an interface.
In the following example we have an interface with name CarRentalServices and this interface has two methods that accepts an object of the class Car as an argument. Within this interface we have the class Car.
 Live Demo
interface CarRentalServices {
   void lendCar(Car c);
   void collectCar(Car c);
   public class Car{
      int carId;
      String carModel;
      int issueDate;
      int returnDate;
   }
}
public class InterfaceSample implements CarRentalServices {
   public void lendCar(Car c) {
      System.out.println("Car Issued");
   }
   public void collectCar(Car c) {
      System.out.println("Car Retrieved");
   }
   public static void main(String args[]){
      InterfaceSample obj = new InterfaceSample();
      obj.lendCar(new CarRentalServices.Car());
      obj.collectCar(new CarRentalServices.Car());
   }
}
Car Issued
Car Retrieved
What is the difference between a mutable and immutable string in C#?

StringBuilder is a mutable string in C#. With StringBuilder, you can expand the number of characters in the string. The string cannot be changed once it is created, but StringBuilder can be expanded. It does not create a new object in the memory.
Set StringBuilder −
StringBuilder str = new StringBuilder();
Let us see an example to learn how to work with StringBuilder in C# −
 Live Demo
using System;
using System.Text;

public class Program {
   public static void Main() {
      StringBuilder str = new StringBuilder("Web World!!",30);
      str.Replace("World", "Arena");

      Console.WriteLine(str);
   }
}
Web Arena!!
Immutable string is a String in C#. A new memory is created every time. A String cannot be changed once it is created, unlike StringBuilde. It does not create a new object in the memory.
Set a string −
String str = “tim”;
The following is an example of a string in which we are comparing two string −
 Live Demo
using System;

namespace StringApplication {

   class StringProg {

      static void Main(string[] args) {
         string str1 = "Steve";
         string str2 = "Ben";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}
Steve and Ben are not equal strings.
Group Anagrams in Python

Suppose, we have a set of strings. We have to group anagram together. So if the ["eat", "tea", "tan", "ate", "nat", "bat"], then the groups are [["ate","eat","tea"],["nat","tan"],["bat"]]
To solve this, we will follow these steps −
Define res as map
for i in string arrayx := x and join, sorted string of iif x in resultinsert i in result[x]else result[x] := [i]
x := x and join, sorted string of i
if x in resultinsert i in result[x]
insert i in result[x]
else result[x] := [i]
return values of res as list
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution:
   def groupAnagrams(self, strs):
      result = {}
      for i in strs:
         x = "".join(sorted(i))
         if x in result:
            result[x].append(i)
         else:
            result[x] = [i]
      return list(result.values())
ob1 = Solution()
print(ob1.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
["eat", "tea", "tan", "ate", "nat", "bat"]
[["ate","eat","tea"],["nat","tan"],["bat"]]
Restrict keyword in C

Here we will see what is the restrict keyword in C. The restrict keyword first introduced in C99 version. Let us see what is actually this restrict keyword.
The restrict keyword is used for pointer declarations as a type quantifier of the pointer.
The restrict keyword is used for pointer declarations as a type quantifier of the pointer.
This keyword does not add new functionalities. Using this the programmer can inform about an optimization that compiler can make.
This keyword does not add new functionalities. Using this the programmer can inform about an optimization that compiler can make.
When the restrict keyword is used with a pointer p, then it tells the compiler, that ptr is only way to access the object pointed by this. So compiler will not add any additional checks.
When the restrict keyword is used with a pointer p, then it tells the compiler, that ptr is only way to access the object pointed by this. So compiler will not add any additional checks.
If the programmer uses restrict keyword then violate the above condition, it will generate some un-defined behavior.
If the programmer uses restrict keyword then violate the above condition, it will generate some un-defined behavior.
#include <stdio.h>
void my_function(int* x, int* y, int* restrict z) {
   *x += *z;
   *y += *z;
}
main(void) {
   int x = 10, y = 20, z = 30;
   my_function(&x, &y, &z);
   printf("%d %d %d", x, y, z);
}
40 50 30
Working with the pycricbuzz library in Python

01 Nov, 2020
Pycricbuzz is a python library that can be used to get live scores, commentary and full scorecard for recent and live matches.
 In case you want to know how the library was developed, you can watch the video: https://youtu.be/OQqYbC1BKxw
Installation: Run the following pip command in the terminal.
pip install pycricbuzz

First of all, we need to create an object of Cricbuzz() for further operations.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzz  # creating a Cricbuzz objectc = Cricbuzz()
We use the matches() method to fetch all the live, upcoming and recently finished matches. Each match has an id associated with it.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzz  # creating a Cricbuzz objectc = Cricbuzz()  # displaying all the matchesprint(c.matches())
Output:
The output by default is quite difficult to read. We can use JSON to make the output matches more human-readable.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzzimport json  # creating a Cricbuzz objectc = Cricbuzz()  # displaying all the matchesprint(json.dumps(c.matches(), indent = 4))
Output:
We can use the matchinfo() method to get the information of a particular match. We have to pass the match id in this method.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzzimport json  # creating a Cricbuzz objectc = Cricbuzz()  # displaying the match informationprint(json.dumps(c.matchinfo('30560'), indent = 4))
Output:
We can fetch the score of a live match by using the livescore() method. Use it only for live matches.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzzimport json  # creating a Cricbuzz objectc = Cricbuzz()  # displaying the match scoreprint(json.dumps(c.livescore('30505'), indent = 4))
Output:
We can get the scorecard of a match by using the scorecard() method. Pass the match id of the target match in this method.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzzimport json  # creating a Cricbuzz objectc = Cricbuzz()  # displaying the match scoreprint(json.dumps(c.scorecard('30505'), indent = 4))
Output:
We can get the commentary of a particular match by using the commentary() method. Pass the match id in this method.
Python3
# importing the modulesfrom pycricbuzz import Cricbuzzimport json  # creating a Cricbuzz objectc = Cricbuzz()  # displaying the match commentaryprint(json.dumps(c.commentary('30505'), indent = 4))
Output:
python-modules
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Transport Layer Security (TLS)

14 Feb, 2022
Transport Layer Securities (TLS) are designed to provide security at the transport layer. TLS was derived from a security protocol called Secure Socket Layer (SSL). TLS ensures that no third party may eavesdrop or tampers with any message. 
There are several benefits of TLS:  
Encryption: TLS/SSL can help to secure transmitted data using encryption.
Interoperability: TLS/SSL works with most web browsers, including Microsoft Internet Explorer and on most operating systems and web servers.
Algorithm flexibility: TLS/SSL provides operations for authentication mechanism, encryption algorithms and hashing algorithm that are used during the secure session.
Ease of Deployment: Many applications TLS/SSL temporarily on a windows server 2003 operating systems.
Ease of Use: Because we implement TLS/SSL beneath the application layer, most of its operations are completely invisible to client.  
Working of TLS: The client connect to server (using TCP), the client will be something. The client sends number of specification: 
Version of SSL/TLS.which cipher suites, compression method it wants to use.  
Version of SSL/TLS.
which cipher suites, compression method it wants to use.  
The server checks what the highest SSL/TLS version is that is supported by them both, picks a cipher suite from one of the clients option (if it supports one) and optionally picks a compression method. After this the basic setup is done, the server provides its certificate. This certificate must be trusted either by the client itself or a party that the client trusts. Having verified the certificate and being certain this server really is who he claims to be (and not a man in the middle), a key is exchanged. This can be a public key, “PreMasterSecret” or simply nothing depending upon cipher suite. 
Both the server and client can now compute the key for symmetric encryption. The handshake is finished and the two hosts can communicate securely. To close a connection by finishing. TCP connection both sides will know the connection was improperly terminated. The connection cannot be compromised by this through, merely interrupted. 
bhrkaviani
prathyushtaneti11
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Inverse Dictionary Values List

14 Oct, 2020
Given a Dictionary as value lists, inverse it, i.e map elements in list to keys and create new values list.
Input : test_dict = {1: [2, 3], 2: [3], 3: [1]}Output : {2: [1], 3: [1, 2], 1: [3]}Explanation : List elements mapped with their keys.
Input : test_dict = {1: [2, 3, 4]}Output : {2: [1], 3: [1], 4: [1]}Explanation : List elements mapped with their keys.
Method : Using defaultdict() + loop
This is a way in which this task can be performed. In this, we initialize result keys with dictionary list, and iterate using loop to assign each value its keys, and reform the result dictionary values list.
Python3
# Python3 code to demonstrate working of # Inverse Dictionary Values List# Using from collections import defaultdict  # initializing dictionarytest_dict = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing empty list as Valuesres = defaultdict(list)                                                                   # using loop to perform reverse mappingfor keys, vals in test_dict.items():    for val in vals:        res[val].append(keys)  # printing result print("The required result : " + str(dict(res))) 
The original dictionary is : {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}
The required result : {2: [1, 4], 3: [1, 2], 1: [3, 4]}

Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Complete Graph using Networkx in Python

29 Apr, 2021
A complete graph also called a Full Graph it is a graph that has n vertices where the degree of each vertex is n-1. In other words, each vertex is connected with every other vertex.
Example: Complete Graph with 6 edges:
C_G6
Properties of Complete Graph:
The degree of each vertex is n-1.
The total number of edges is n(n-1)/2.
All possible edges in a simple graph exist in a complete graph.
It is a cyclic graph.
The maximum distance between any pair of nodes is 1.
The chromatic number is n as every node is connected to every other node.
Its complement is an empty graph.
We will use the networkx module for realizing a Complete graph. It comes with an inbuilt function networkx.complete_graph() and can be illustrated using the networkx.draw() method. This module in Python is used for visualizing and analyzing different kinds of graphs.
Syntax: networkx.complete_graph(n)
Parameters:
N: Number of nodes in complete graph.
Returns an networkx graph complete object.
Nodes are indexed from zero to n-1.
Used to realize the graph by passing graph object.
networkx.draw(G, node_size, node_color)
Parameters:
G: It refers to the complete graph object
node_size: It refers to the size of nodes.
node_color: It refers to color of the nodes.
Approach:
We will import the required module networkx.
Then we will create a graph object using networkx.complete_graph(n).
Where n specifies n number of nodes.
For realizing graph, we will use networkx.draw(G, node_color = ’green’, node_size=1500)
The node_color and node_size arguments specify the color and size of graph nodes.
Example 1:
Python3
# import required moduleimport networkx # create objectG = networkx.complete_graph(6) # illustrate graphnetworkx.draw(G, node_color = 'green',              node_size = 1500)
Output:
Output
The output of the above program gives a complete graph with 6 nodes as output as we passed 6 as an argument to the complete_graph function.
Example 2:
Python3
# import required moduleimport networkx # create objectG = networkx.complete_graph(10) # illustrate graphnetworkx.draw(G, node_color = 'green',              node_size = 1500)
Output:
simmytarika5
Python Networx-module
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to put the y-axis in logarithmic scale with Matplotlib ?

17 Dec, 2020
Axes’ in all plots using Matplotlib are linear by default, yscale() method of the matplotlib.pyplot library can be used to change the y-axis scale to logarithmic.
The method yscale() takes a single value as a parameter which is the type of conversion of the scale, to convert y-axes to logarithmic scale we pass the “log” keyword or the matplotlib.scale.LogScale class to the yscale method.
Syntax :  matplotlib.pyplot.yscale(value, **kwargs)
Parameters:
Value = { “linear”, “log”, “symlog”, “logit”, ... }
**kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Returns : Converts the y-axes to the given scale type. (Here we use the “log” scale type)
Linear Scale Example : 
Python3
import matplotlib.pyplot as plt  data = [10**i for i in range(4)]plt.plot(data)
Output: 
Linear Scale
Logarithmic Scale Example : 
Python3
import matplotlib.pyplot as plt  data = [10**i for i in range(4)]  # convert y-axis to Logarithmic scaleplt.yscale("log")  plt.plot(data)
Output: 
Logarithmic y-axis
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert Java String to Short in Java

Use valueOf() method to convert a String in Java to Short.
Let us take a string.
The following is an example −
String myStr = "5";
Now take Short object and use the valueOf() method. The argument should be the string we declared above.
The following is an example.
Short myShort = Short.valueOf(myStr);
Let us now see the entire example to learn how to convert a string in Java to Short.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String myStr = "5";
      System.out.println("String: "+myStr);
      Short myShort = Short.valueOf(myStr);
      System.out.println("Short: "+myShort);
   }
}
String: 5
Short: 5
Friend class and function in C++

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows −
class Box {
double width;

public:
   double length;
   friend void printWidth( Box box );
   void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place the following declaration in the definition of class ClassOne −
friend class ClassTwo;
#include <iostream>
using namespace std;

class Box {
   double width;

   public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};

// Member function definition
void Box::setWidth( double wid ) {
   width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
   /* Because printWidth() is a friend of Box, it can
   directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}

// Main function for the program
int main() {
   Box box;

   // set box width without member function
   box.setWidth(10.0);

   // Use friend function to print the wdith.
   printWidth( box );

   return 0;
}
This will give the output −
Width of box: 10
Even though the function was not a member of the class, it could directly access the member variables of that class. This can be very useful in certain situations.
Python Program for Longest Palindromic Subsequence | DP-12

21 Feb, 2022
Given a sequence, find the length of the longest palindromic subsequence in it. 
As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones. 1) Optimal Substructure: Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1]. If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2. Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)). Following is a general recursive solution with all cases handled. Dynamic Programming Solution  
Python3
# A Dynamic Programming based Python # program for LPS problem Returns the length# of the longest palindromic subsequence in seqdef lps(str):    n = len(str)      # Create a table to store results of subproblems    L = [[0 for x in range(n)] for x in range(n)]      # Strings of length 1 are palindrome of length 1    for i in range(n):        L[i][i] = 1      # Build the table. Note that the lower     # diagonal values of table are    # useless and not filled in the process.     # The values are filled in a    # manner similar to Matrix Chain     # Multiplication DP solution (See    # https://www.geeksforgeeks.org/    # dynamic-programming-set-8-matrix-chain-multiplication/    # cl is length of substring    for cl in range(2, n + 1):        for i in range(n-cl + 1):            j = i + cl-1            if str[i] == str[j] and cl == 2:                L[i][j] = 2            elif str[i] == str[j]:                L[i][j] = L[i + 1][j-1] + 2            else:                L[i][j] = max(L[i][j-1], L[i + 1][j]);      return L[0][n-1]  # Driver program to test above functionsseq = "GEEKS FOR GEEKS"n = len(seq)print("The length of the LPS is " + str(lps(seq)))  # This code is contributed by Bhavya Jain
The length of the LPS is 7
 
Time Complexity :- O(n2)
Please refer complete article on Longest Palindromic Subsequence | DP-12 for more details! 
amartyaghoshgfg
simmytarika5
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Appending a dictionary to a list in Python
Python Program to check Armstrong Number
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python | Remove spaces from a string
Python Program for Merge Sort
Python - Convert JSON to string
Python Program for simple interest
MySQL | DEFAULT() Function

25 Mar, 2019
The DEFAULT() function returns the default value for table column.
DEFAULT value of a column is a value used in the case, there is no value specified by user.
In order, to use this function there should be a DEFAULT value assign to the column. Otherwise, it will generate an error.
Syntax:
DEFAULT ( column_name)

column_name: Name of column whose default value is written.

Example: Consider two relations student and result–
Structure of table “student”-
Structure of table “result”-
Data in the tables-
Select * from student;

Select * from result;

Problem Description: We have to find result of all the students-
Query:
Select sid, sname, subject, marks, 
    IF ( grade is NULL, DEFAULT ( grade ), grade )
AS grade  FROM  student LEFT JOIN result 
    ON marks > lowest_marks 
AND marks < = highest_marks;

Output:
Explanation: Here, default() function is use to return default grade i.e “FAIL”. This default value is used in place where student marks doesn’t match according to joining condition. Those students results is shown as FAIL.
Note: The default function with select statement will return default value for all rows. That means, instead of getting a single default value of the column, we will get list of default values for that column.
For example for above table result, Output of query is-
Select default ( grade) from result;

Output:
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Interview Questions
SQL | Views
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Python dictionary type() Method

Python dictionary  method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.
Following is the syntax for type() method −
type(dict)
dict − This is the dictionary.
dict − This is the dictionary.
This method returns the type of the passed variable.
The following example shows the usage of type() method.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7};
print "Variable Type : %s" %  type (dict)
When we run above program, it produces following result −
Variable Type : <type 'dict'>


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
CASE WHEN in PostgreSQL?

If you are a programmer, you may be very familiar with IF-ELSE statements. The equivalent in PostgreSQL is CASE WHEN.
Let’s understand with an example. If you have table marks containing percentage marks of a student, and you want to find out whether the students have passed or failed. An example table is given below.
Say the passing marks are 40. Now, if the student has scored above 40 marks, we want to print ‘PASS’ against that student’s name, otherwise ‘FAIL’. This is how you can do it −
SELECT name, CASE WHEN perc_marks >= 40 THEN 'PASS' ELSE 'FAIL' END
status from marks
The output will be −
Remember, the END at the end of the CASE WHEN expression is important. You can add multiple WHEN statements. Suppose you want to say that those who scored above 80 marks have the status ‘DISTINCTION’, between 40 and 80, they have status ‘PASS’ and below 40, they have the status ‘FAIL’, you can do that as follows −
SELECT name, CASE
WHEN perc_marks >= 80 THEN 'DISTINCTION'
WHEN perc_marks >= 40 and perc_marks < 80 THEN 'PASS'
ELSE 'FAIL' END status from marks
The output will be −
Mealy Machine for 1's Complement - GeeksforGeeks

07 Jul, 2021
After converting a number to its binary form, replace every one of the number with 0 and every 0 with 1, then the resulting number will be known as 1, s complement of that binary number.  
Input-1 :
101010
Output-1 : 
010101 

Input-2 :
1110100
Output-2 :
0001011 
Approach : 
First make a initial state. Then convert each 0 to 1 and each 1 to 0, and reach to next possible state. after performing step 2 on each digit of binary number, reach at some final state to complete the process.  
First make a initial state. 
Then convert each 0 to 1 and each 1 to 0, and reach to next possible state. 
after performing step 2 on each digit of binary number, reach at some final state to complete the process.  
Design Mealy Machine : 
Step-1: Take a initial state say q1, and if the input is found 0, convert it to 1, remain at same state and check for another input alphabet. 
 
Step-2: If state q1 takes input alphabet is 1, then convert it to 0 and remain at same state. 
 
Step-3:As after converting all alphabet, it is on same state then this state will be final state as well. 
 
Example : Suppose a string 10001 and start parsing from left to right. Every 0 will be replaced by 1 and every one is replaces by 0. Then the output is 01110. 
sooda367
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction of Pushdown Automata
Construct Pushdown Automata for given languages
Converting Context Free Grammar to Chomsky Normal Form
How to identify if a language is regular or not
Simplifying Context Free Grammars
Introduction of Theory of Computation
Arden's Theorem in Theory of Computation
Conversion of Epsilon-NFA to NFA
Check if the language is Context Free or Not
Construct a Turing Machine for language L = {wwr | w ∈ {0, 1}}
How to handle the exception using UncaughtExceptionHandler in Java?

The UncaughtExceptionHandler is an interface inside a Thread class. When the main thread is about to terminate due to an uncaught exception the java virtual machine will invoke the thread’s UncaughtExceptionHandler for a chance to perform some error handling like logging the exception to a file or uploading the log to the server before it gets killed. We can set a Default Exception Handler which will be called for the all unhandled exceptions. It is introduced in Java 5 Version.
This Handler can be set by using the below static method of java.lang.Thread class.
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler ueh)
We have to provide an implementation of the interface Thread.UncaughtExceptionHandler, which has only one method.
@FunctionalInterface
public interface UncaughtExceptionHandler {
   void uncaughtException(Thread t, Throwable e);
}
Live Demo
public class UncaughtExceptionHandlerTest {
   public static void main(String[] args) throws Exception {
      Thread.setDefaultUncaughtExceptionHandler(new MyHandler());
      throw new Exception("Test Exception");
   }
   private static final class MyHandler implements Thread.UncaughtExceptionHandler {
      @Override
      public void uncaughtException(Thread t, Throwable e) {
         System.out.println("The Exception Caught: " + e);
      }
   }
}
The Exception Caught: java.lang.Exception: Test Exception
MongoDB query for Partial Object in an array

Let us first create a collection with documents −
> db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":1, "StudentName":"Chris"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfcf55bf3115999ed51206")
}
> db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":2, "StudentName":"David"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfcf55bf3115999ed51207")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.queryForPartialObjectDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cdfcf55bf3115999ed51206"),
   "StudentDetails" : [
      {
         "StudentId" : 1,
         "StudentName" : "Chris"
      }
   ]
}
{
   "_id" : ObjectId("5cdfcf55bf3115999ed51207"),
   "StudentDetails" : [
      {
         "StudentId" : 2,
         "StudentName" : "David"
      }
   ]
}
Following is the query for partial object in array with MongoDB −
> db.queryForPartialObjectDemo.find({StudentDetails: {StudentId: 1, "StudentName" : "Chris"}});
This will produce the following output −
{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }
Following is the query for partial object in an array with dot notation −
> db.queryForPartialObjectDemo.find({"StudentDetails.StudentName":"Chris"});
This will produce the following output −
{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }
Creating a QR Code of a link in React JS

In this article, we will see how to create a QR code of a link in
React JS. A QR code is a two-dimensional barcode that is readable on
smartphones. You must have seen QR codes on websites that you can
scan which redirects you to a page. For example, to access WhatsApp
from your laptop, you can go to "web.whatsapp.com" and then open
WhatsApp on your phone and scan the given QR code.
First create a React project −
npx create-react-app tutorialpurpose
Go to the project directory −
cd tutorialpurpose
Install the qrcode.react package −
npm i --save qrcode.react
This library is going to help us in generating QR codes and add
dependencies to do so.
Now insert the following lines of code in App.js −
import QRCode from "qrcode.react";
export default function App() {
   return (
      <div style={{ marginTop: 200, display: "flex",flexDirection: "row" }}>
         <div>
            <QRCode
               value="https://www.tutorialspoint.com/"style={{ marginRight: 50 }}/>
            <p>Tutorialspoint </p>
         </div>
      <div>
          <QRCode value="https://www.google.com/" style={{marginRight: 50 }} />
          <p>google</p>
      </div>
      <div>
          <QRCode value="https://github.com/" style={{marginRight: 50 }} />
          <p>github</p>
      </div>
      <div>
          <QRCode value="https://www.instagram.com/" style={{ marginRight: 50 }}/>
          <p>instagram</p>
      </div>
      <div>
          <QRCode value="https://discord.com/" style={{marginRight: 50 }} />
          <p>discord</p>
         </div>
      </div>
   );
}
The code takes a link, processes it, and then renders a QR code for
that link.
Here we first imported our QRCode object which takes one parameter called "value" which takes the link of which you want to make a QR code.
You can also apply styles on it only for positioning and size.
We have taken the links of the following 5 websites and generated their QR codes −
https://www.tutorialspoint.com/
https://www.tutorialspoint.com/
https://www.google.com/
https://www.google.com/
https://github.com/
https://github.com/
https://www.instagram.com/
https://www.instagram.com/
https://discord.com/
https://discord.com/
On execution, it will produce the following output −
Scan any of the codes with your mobile phone and it will prompt you with the link to open that page in a browser
Python | Numpy np.gumbel() method

24 Oct, 2019
With the help of np.gumbel() method, we can get the gumbel distribution in the form of an array by using np.gumbel() method.
Syntax : np.gumbel(value, scale, size)
Return : Return the array of gumbel distribution.
Example #1 :In this example we can see that by using np.gumbel() method, we are able to get an array of gumbel distribution using this method.
# import numpyimport numpy as np  # using np.gumbel() methodgfg = np.random.gumbel(12, 0.7, 20)  print(gfg)
Output :
array([12.64947204, 12.37405666, 13.58474571, 14.91257252, 12.52167875,12.4480617, 14.95250558, 11.70944994, 12.80072181, 11.60226466,11.877631, 11.5397349, 12.46834902, 13.27323288, 14.93137191,11.95035735, 12.54426051, 11.1745507, 13.10580066, 14.41014362])
Example #2 :
# import numpyimport numpy as np  # using np.gumbel() methodgfg = np.random.gumbel(0, 1.7, 10)  print(gfg)
Output :
[ 5.34883666 -0.98597658 2.35585763 1.45700115 -2.62043708 -0.619834421.8046374 -1.73997392 4.29301495 1.82840768]
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install GCC Compiler on Linux?

06 Oct, 2021
In this article, we will discuss how to install a GCC compiler on Linux. 
GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++. The GCC is an open-source collection of compilers and libraries.
Let’s start with the steps to install the GCC on Linux.
To install the GCC open the terminal on Linux.
The terminal takes the input from the user in the form of commands and displays the output on the screen. Hence we have to pass some commands to install the GCC.
Follow the commands step by step to install the GCC.
Command 1: The very first step is to update the packages. This command is used to download package information from all configured sources and to get the info of the updated versions of the packages.
sudo apt-get update
command-1
Note: In the first command it will ask for your password, make sure to enter the password correctly.
Command 2: Now we have to install the build-essential packages, which is also known as a meta-package, it contains the GCC compiler all the other essentials used to compile the software written in C and C++ language.
sudo apt install build-essential
command-2
It will take some time to install all the essential packages.
Command 3: After the second command it will install GCC on your Linux, to verify it is installed correctly, check the version of the GCC.
gcc --version
command-3
Now, we have successfully installed the GCC on Linux.
Note: Versions may vary from time to time.
how-to-install
Picked
How To
Installation Guide
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 Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
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 does auto property work in margin:0 auto in CSS ?

17 Mar, 2021
In this article, we will learn how auto property works in margin:0 auto in CSS. The margin property is used to set the margins for an element. The margin property has four values margin-top, margin-right, margin-bottom, and margin-left.
Syntax:
margin: top_margin right_margin bottom_margin left_margin;

/* We can also use the shortened syntax 
   of margin that takes only two parameters */

margin: top_and_bottom_margin left_and_right_margin;
So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered. The margin: 0 auto equivalent to:
margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>  <style>    .parent{      background-color: yellow;      /* It set top and bottom margin to 5% and, the left and right      are automatically set by browser */      margin: 5% auto;    }    .h1{      color: rgb(5, 138, 5);      font-size: 50px;    }  </style></head>  <body>  <div class="parent">    <h1 class="h1">GeeksforGeeks</h1>   </div></body>  </html>
Output: 
Before set margin:
Before set margin:
After set margin:
After set margin:
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
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