code-rag-bench/online-tutorials huggingface dataset:
Saving multiple figures to one PDF file in matplotlib

To save multiple figures in one PDF file at once, we can take follwong steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure (fig1) or activate and existing figure using figure() method.
Create a new figure (fig1) or activate and existing figure using figure() method.
Plot the first line using plot() method.
Plot the first line using plot() method.
Create another figure (fig2) or activate and existing figure using figure() method.
Create another figure (fig2) or activate and existing figure using figure() method.
Plot the second line using plot() method.
Plot the second line using plot() method.
Initialize a variable, filename, to make a pdf file.
Initialize a variable, filename, to make a pdf file.
Create a user-defined function save_multi_image() to save multiple images in a PDF file.
Create a user-defined function save_multi_image() to save multiple images in a PDF file.
Call the save_multi_image() function with filename.
Call the save_multi_image() function with filename.
Create a new PdfPages object.
Create a new PdfPages object.
Get the number of open figures.
Get the number of open figures.
Iterate the opened figures and save them into the file.
Iterate the opened figures and save them into the file.
Close the created PDF object.
Close the created PDF object.
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

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

fig1 = plt.figure()
plt.plot([2, 1, 7, 1, 2], color='red', lw=5)

fig2 = plt.figure()
plt.plot([3, 5, 1, 5, 3], color='green', lw=5)


def save_multi_image(filename):
    pp = PdfPages(filename)
    fig_nums = plt.get_fignums()
    figs = [plt.figure(n) for n in fig_nums]
    for fig in figs:
        fig.savefig(pp, format='pdf')
    pp.close()

filename = "multi.pdf"
save_multi_image(filename)

Upon execution, it will create a PDF "multi.pdf" in the Project Directory and save the following two images in that file.
How to create a SplitMenuButton in JavaFX?

A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.
A button controls in user interface applications, in general, on clicking the button it performs the respective action.
A SplitMenuButton provides the functionality of both buttons and a Menu. It is divided into two areas − action area and, menu area. On clicking either of these areas it shows the respective functionality.
You can create a split menu button by instantiating the javafx.scene.control.SplitMenuButton class.
The following Example demonstrates the creation of a SplitMenuButton.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitMenuButton;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class SplitMenuButtonExample extends Application {
   public void start(Stage stage) {
      //Creating an ImageView
      ImageView img = new ImageView("UIControls/globe.png");
      img.setFitWidth(20);
      img.setFitHeight(20);
      //Creating a label
      Label label = new Label("Select A Language");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a menu
      SplitMenuButton menu = new SplitMenuButton();
      //Setting text to the SplitMenuButton
      menu.setText("Language");
      //Setting an image to the button
      menu.setGraphic(img);
      //Creating menu Items
      menu.setMnemonicParsing(true);
      MenuItem item1 = new MenuItem("Telugu");
      MenuItem item2 = new MenuItem("Hindi");
      MenuItem item3 = new MenuItem("English");
      MenuItem item4 = new MenuItem("Tamil");
      MenuItem item5 = new MenuItem("Malayalam");
      //Adding all the menu items to the menu
      menu.getItems().addAll(item1, item2, item3, item4, item5);
      //Adding the choice box to the scene
      HBox layout = new HBox(25);
      layout.getChildren().addAll(label, menu);
      layout.setPadding(new Insets(15, 50, 50, 130));
      layout.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(layout, 595, 200);
      stage.setTitle("Split Menu Button");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Comparing dates in MySQL ignoring time portion of a DateTime field?

To compare dates in MySQL except time portion of a datetime field, you can use DATE() function. The syntax is as follows −
select *from yourTableName where date(yourColumName) = yourDate;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table ComparingDate
   −> (
   −> Name varchar(100),
   −> Login datetime
   −> );
Query OK, 0 rows affected (0.50 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into ComparingDate values('John','2014-04-06 22:50:45');
Query OK, 1 row affected (0.15 sec)

mysql> insert into ComparingDate values('Bob','2018-12-15 15:07:46');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ComparingDate values('Carol','2016-03-10 21:50:40');
Query OK, 1 row affected (0.18 sec)

mysql> insert into ComparingDate values('David','1995-08-08 23:40:47');
Query OK, 1 row affected (0.14 sec)
Display all records from table using select statement. The query is as follows −
mysql> select *from ComparingDate;
The following is the output −
+-------+---------------------+
| Name  | Login               |
+-------+---------------------+
| John  | 2014-04-06 22:50:45 |
| Bob   | 2018-12-15 15:07:46 |
| Carol | 2016-03-10 21:50:40 |
| David | 1995-08-08 23:40:47 |
+-------+---------------------+
4 rows in set (0.00 sec)
Here is the query to compare only date, not time −
mysql> select *from ComparingDate where date(Login) = '2016-03-10';
The following is the output −
+-------+---------------------+
| Name  | Login               |
+-------+---------------------+
| Carol | 2016-03-10 21:50:40 |
+-------+---------------------+
1 row in set (0.00 sec)
Find all reachable nodes from every node present in a given set in C++

Suppose we have one undirected graph and a set of vertices; we have to find all reachable nodes from every vertex present in the given set.
So, if the input is like
then the output will be [1,2,3] and [4,5] as these are two connected components.
To solve this, we will follow these steps −
nodes := number of nodes in the graph
Define an array visited of size: nodes+1. And fill with 0
Define one map m
comp_sum := 0
for initialize i := 0, when i < n, update (increase i by 1), do −u := arr[i]if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sumprint traversal of m[visited[u]]
u := arr[i]
if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum
(increase comp_sum by 1)
m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum
print traversal of m[visited[u]]
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Graph{
   public:
      int nodes;
      list<int> *adj_list;
      Graph(int);
      void insert_edge(int, int);
      vector<int> BFS(int, int, int []);
};
Graph::Graph(int nodes) {
   this->nodes = nodes;
   adj_list = new list<int>[nodes+1];
}
void Graph::insert_edge(int u, int v) {
   adj_list[u].push_back(v);
   adj_list[v].push_back(u);
}
vector<int> Graph::BFS(int comp_sum, int src,int visited[]){
   queue<int> queue;
   queue.push(src);
   visited[src] = comp_sum;
   vector<int> reachableNodes;
   while(!queue.empty()) {
      int u = queue.front();
      queue.pop();
      reachableNodes.push_back(u);
      for (auto itr = adj_list[u].begin(); itr != adj_list[u].end(); itr++) {
         if (!visited[*itr]) {
            visited[*itr] = comp_sum;
            queue.push(*itr);
         }
      }
   }
   return reachableNodes;
}
void displayReachableNodes(int n, unordered_map <int, vector<int> > m) {
   vector<int> temp = m[n];
   for (int i=0; i<temp.size(); i++)
      cout << temp[i] << " ";
   cout << endl;
}
void get_all_reachable(Graph g, int arr[], int n) {
   int nodes = g.nodes;
   int visited[nodes+1];
   memset(visited, 0, sizeof(visited));
   unordered_map <int, vector<int> > m;
   int comp_sum = 0;
   for (int i = 0 ; i < n ; i++) {
      int u = arr[i];
      if (!visited[u]) {
         comp_sum++;
         m[visited[u]] = g.BFS(comp_sum, u, visited);
      }
      cout << "Reachable Nodes from " << u <<" are\n";
      displayReachableNodes(visited[u], m);
   }
}
int main() {
   int nodes = 5;
   Graph g(nodes);
   g.insert_edge(1, 2);
   g.insert_edge(2, 3);
   g.insert_edge(4, 5);
   int arr[] = {2, 4, 1};
   int n = sizeof(arr)/sizeof(int);
   get_all_reachable(g, arr, n);
}
g.insert_edge(1, 2);
g.insert_edge(2, 3);
g.insert_edge(4, 5);
Reachable Nodes from 2 are
2 1 3
Reachable Nodes from 4 are
4 5
Reachable Nodes from 1 are
2 1 3
Generate table DDL via a query on MySQL and SQL Server?

The DDL stands for Data Definition Language. To generate the table DDL via query, you can
use show create command.
The syntax is as follows
SHOW CREATE TABLE yourTableName;
The above syntax is MySQL specific. Suppose, we have a table with the name
‘DDLOfTableStudent’.
First, create a table with the name ‘DDLOfTableStudent’. The query to create a table is as
follows
mysql> create table DDLOfTableStudent
   -> (
   -> StudentId int,
   -> StudentFirstName varchar(100),
   -> StudentLastName varchar(100),
   -> StudentAddress varchar(200),
   -> StudentAge int,
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.84 sec)
Use the above syntax to know the DDL of a table. The query is as follows
mysql> SHOW CREATE TABLE DDLOfTableStudent;
The following is the output displaying the DDL
+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table             | Create Table                                                                                                                                                                                                                                                                                                                                                   |
+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DDLOfTableStudent | CREATE TABLE `ddloftablestudent` (`StudentId` int(11) DEFAULT NULL,`StudentFirstName` varchar(100) DEFAULT NULL,`StudentLastName` varchar(100) DEFAULT NULL,`StudentAddress` varchar(200) DEFAULT NULL,`StudentAge` int(11) DEFAULT NULL,`StudentMarks` int(11) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
How do I get email-id from a MongoDB document and display with print()

For this, use forEach() along with print() to display the email-id values. Let us create a collection with documents −
> db.demo690.insertOne({"UserName":"John","UserEmailId":"John@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db31551299a9f98c939c")
}
> db.demo690.insertOne({"UserName":"Bob","UserEmailId":"Bob@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db3c551299a9f98c939d")
}
> db.demo690.insertOne({"UserName":"David","UserEmailId":"David@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db47551299a9f98c939e")
}
Display all documents from a collection with the help of find() method −
> db.demo690.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6db31551299a9f98c939c"), "UserName" : "John", "UserEmailId" : "John@gmail.com" }
{ "_id" : ObjectId("5ea6db3c551299a9f98c939d"), "UserName" : "Bob", "UserEmailId" : "Bob@gmail.com" }
{ "_id" : ObjectId("5ea6db47551299a9f98c939e"), "UserName" : "David", "UserEmailId" : "David@gmail.com" }
Following is the query to get email-id from a MongoDB document and print using print() −
> db.demo690.find().forEach(function(document) {
...    print(document.UserEmailId);
... });
This will produce the following output −
John@gmail.com
Bob@gmail.com
David@gmail.com
std::iota in C++ - GeeksforGeeks

01 Sep, 2021
Store increasing sequence Assigns to every element in the range [first, last] successive values of val, as if incremented with ++val after each element is written.
Template : 
void iota (ForwardIterator first, ForwardIterator last, T val);

Parameters :

first, last
Forward iterators to the initial and final positions of the sequence
to be written. The range used is [first, last), which contains all the
elements between first and last, including the element pointed by
first but not the element pointed by last.

val
Initial value for the accumulator. 

Return Type :
None
C++
// C++ program to illustrate// std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){    int numbers[10];    // Initialising starting value as 100    int st = 100;     std::iota(numbers, numbers + 10, st);     std::cout << "Elements are :";    for (auto i : numbers)        std::cout << ' ' << i;    std::cout << '\n';     return 0;}
Output: 
Elements are : 100 101 102 103 104 105 106 107 108 109
Application : It can be used to generate a sequence of consecutive numbers. 
C++
// C++ program to generate// a sequence of numbers using std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){    int numbers[11];    // Initialising starting value as 10    int st = 10;     std::iota(numbers, numbers + 11, st);     std::cout << "Elements are :";    for (auto i : numbers)        std::cout << ' ' << i;    std::cout << '\n';     return 0;}
Output:
Elements are : 10 11 12 13 14 15 16 17 18 19 20
This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
anikakapoor
cpp-numerics-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
JavaScript TypeError - 'X' is not iterable - GeeksforGeeks

29 Jul, 2020
This JavaScript exception is not iterable occurs if the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, can not be iterated or is not an iterable object.
Message:
TypeError: 'x' is not iterable (Firefox, Chrome)
TypeError: 'x' is not a function or its return value is not iterable (Chrome)

Error Type:
TypeError

Cause of Error: Somewhere in the code, the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is used like it can be iterated or is an iterable object.
Example 1: In this example, the GFG_Obj is not iterable, So the error has occurred.
HTML
<script>    var GFG_Obj = { 'prop1': 'val1', 'prop2': 'val2' };    // TypeError: GFG_Obj is not iterable    for (let x of GFG_Obj) {         // Do Anything.    }</script>
Output(in console):
TypeError: GFG_Obj is not iterable

Example 2: In this example, the GFG is not iterable, So the error has occurred.
HTML
<script>    function* GFG(a, b) {      yield a;      yield b;    }    // TypeError: GFG is not iterable    for (let y of GFG)         console.log(x);</script>
Output(in console):
TypeError: GFG is not iterable

JavaScript-Errors
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
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?
Ints contains() function in Java

The contains() function of the Ints class is used to check whether an element is present in the array or not.
Following is the syntax −
public static boolean
contains(int[] arr, int target)
Here, arr is the array wherein the element is to be checked. The target is the element to be checked.
Following is an example to implement the contains() method of the Ints class −
import com.google.common.primitives.Ints;
import java.util.*;
class Demo {
   public static void main(String[] args) {
      int[] myArr1 = { 100, 150, 230, 300, 400 };
      int[] myArr2 = { 450, 550, 700, 800, 1000 };
      System.out.println("Array 1 = ");
      for(int i=0; i < myArr1.length; i++) {
         System.out.println(myArr1[i]);
      }
      System.out.println("Array 2 = ");
      for(int i=0; i < myArr2.length; i++) {
         System.out.println(myArr2[i]);
      }
      int[] arr = Ints.concat(myArr1, myArr2);
      System.out.println("Concatenated arrays = "+Arrays.toString(arr));
      if (Ints.contains(arr, 800))
         System.out.println("Element 800 is in the array!");
      else
         System.out.println("Element 800 is not in the array!");
   }
}
Array 1 =
100
150
230
300
400
Array 2 =
450
550
700
800
1000
Concatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000]
Element 800 is in the array!
Break Statement in Dart Programming

The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement.
void main() { 
   var i = 1; 
   while(i<=10) { 
      if (i % 5 == 0) { 
         print("The first multiple of 5  between 1 and 10 is : ${i}"); 
         break ;    
         //exit the loop if the first multiple is found 
      } 
      i++; 
   }
}  
The above code prints the first multiple of 5 for the range of numbers within 1 to 10.
If a number is found to be divisible by 5, the if construct forces the control to exit the loop using the break statement. The following output is displayed on successful execution of the above code.
The first multiple of 5 between 1 and 10 is: 5 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Convert a list of objects to JSON using the Gson library in Java?

A Gson is a library that can be used to convert Java Objects to JSON representation. It can also be used to convert a JSON string to an equivalent Java object. The primary class to use is Gson which we can create by calling the new Gson() and the GsonBuilder class can be used to create a Gson instance.
We can convert a list of objects by first creating a Person class and convert a list of Person objects to JSON.
import java.util.*;
import java.util.stream.*;
import com.google.gson.*;
public class JSONConverterTest {
   public static void main( String[] args ) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      List list = Stream.of(new Person("Raja", "Ramesh", 30, "9959984800"),
                            new Person("Jai", "Dev", 25, "7702144400"),
                            new Person("Adithya", "Sai", 21, "7013536200"),
                            new Person("Chaitanya", "Sai", 28, "9656444150"))
                            .collect(Collectors.toList());
      System.out.println("Convert list of person objects to Json:");
      String json = gson.toJson(list); // converts to json
      System.out.println(json);
   }
}
// Person class
class Person {
   private String firstName, lastName, contact;
   private int age;
   public Person(String firstName, String lastName, int age, String contact) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.contact = contact;
   }
   public String toString() {
      return "[" + firstName + " " + lastName + " " + age + " " +contact +"]";
   }
}
Convert list of person objects to Json:
[
{
   "firstName": "Raja",
   "lastName": "Ramesh",
   "contact": "9959984800",
   "age": 30
},
{
   "firstName": "Jai",
   "lastName": "Dev",
   "contact": "7702144400",
   "age": 25
},
{
   "firstName": "Adithya",
   "lastName": "Sai",
   "contact": "7013536200",
   "age": 21
},
{
   "firstName": "Chaitanya",
   "lastName": "Sai",
   "contact": "9656444150",
   "age": 28
}
]
Longest Common Prefix in Python

Suppose we have a set of strings in an array. We have to find the Longest Common Prefix amongst the string in the array. Here we will assume that all strings are lower case strings. And if there is no common prefix, then return “”.
So if the array of a string is like ["school", "schedule","Scotland"], then the Longest Common Prefix is “sc” as this is present in all of these string.
To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched.
Let us see the implementation to get a better understanding
 Live Demo
class Solution(object):
   def longestCommonPrefix(self, strs):
      """
      :type strs: List[str]
      :rtype: str
      """
      if len(strs) == 0:
         return ""
      current = strs[0]
      for i in range(1,len(strs)):
         temp = ""
         if len(current) == 0:
            break
         for j in range(len(strs[i])):
            if j<len(current) and current[j] == strs[i][j]:
               temp+=current[j]
            else:
               break
         current = temp
      return current
input_list = ["school","schedule","scotland"]
ob1 = Solution()
print(ob1.longestCommonPrefix(input_list))
["school","schedule","scotland"]
"sc"
Python Number sin() Method

Python number method sin() returns the sine of x, in radians.
Following is the syntax for sin() method −
sin(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the sine of the parameter x.
The following example shows the usage of sin() method.
#!/usr/bin/python
import math

print "sin(3) : ",  math.sin(3)
print "sin(-3) : ",  math.sin(-3)
print "sin(0) : ",  math.sin(0)
print "sin(math.pi) : ",  math.sin(math.pi)
print "sin(math.pi/2) : ",  math.sin(math.pi/2)
When we run above program, it produces following result −
sin(3) :  0.14112000806
sin(-3) :  -0.14112000806
sin(0) :  0.0
sin(math.pi) :  1.22464679915e-16
sin(math.pi/2) :  1.0


    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
Python | Multiply Dictionary Value by Constant - GeeksforGeeks

29 Dec, 2019
Sometimes, while working with dictionaries, we can have a use-case in which we require to multiply a particular key’s value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using get()The get function can be used to initialize a non-existing key with 1 and then the product is possible. By this way the problem of non-existing key can be avoided.
# Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using get()  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Initialize K K = 5  # Using get()# Multiply Dictionary Value by Constanttest_dict['best'] = test_dict.get('best', 1) * K      # printing result print("Dictionary after the multiplication of key : " + str(test_dict))
The original dictionary : {'for': 4, 'is': 2, 'CS': 5, 'gfg': 1}
Dictionary after the multiplication of key : {'for': 4, 'is': 2, 'CS': 5, 'best': 5, 'gfg': 1}

 
Method #2 : Using defaultdict()This problem can also be solved by using a defaultdict method, which initializes the potential keys and doesn’t throw an exception in case of non-existence of keys.
# Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using defaultdict()from collections import defaultdict  # Initialize dictionarytest_dict = defaultdict(int)  # printing original dictionaryprint("The original dictionary : " + str(dict(test_dict)))  # Initialize K K = 5  # Using defaultdict()# Multiply Dictionary Value by Constanttest_dict['best'] *= K      # printing result print("Dictionary after the multiplication of key : " + str(dict(test_dict)))
The original dictionary : {}
Dictionary after the multiplication of key : {'best': 0}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
TypeScript | String localeCompare() Method - GeeksforGeeks

18 Jun, 2020
The localeCompare() is an inbuilt function in TypeScript which is used to get the number indicating whether a reference string comes before or after or is the same as the given string in sorted order. Syntax:
string.localeCompare( param ) 

Parameter: This method accept a single parameter as mentioned above and described. 
param : This parameter is a string to be compared with string object.
Return Value: This method returns the flowing. 
0 is return, if the string is fully match.
1 is return, if the string is not match and the parameter value comes before the string object’s value.
– A negative value is return, if the string is not match and the parameter value comes after the string object’s value.
Example 1: 
JavaScript
<script>    // Original strings    var str1 = new String('Geeksforgeeks');       var index = str1.localeCompare("Geeksforgeeks");      // Use of String localeCompare() Method    console.log(index);</script>
Output: 
0

Example 2: 
JavaScript
<script>    // Original strings    var str1 = new String('Geeksforgeeks');       var index = str1.localeCompare("Geeks");      // Use of String localeCompare() Method    console.log(index);</script>
Output: 
1

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
D3.js | d3.color() Function - GeeksforGeeks

02 Dec, 2019
The d3.color() function in D3.js is used to parse the specified CSS color used as parameter of the function and return RGB or HSL color. If specifier is not given, then null is returned.
Syntax:
d3.color(color);
Parameters: This function accepts single parameter color which specifies the CSS color.
Return Value: This function returns the RGB or HSL color value of the specified CSS color taken as the parameter of the function.
Below programs illustrate the d3.color() function in D3.js:
Example 1:
<!DOCTYPE html><html>  <head>    <title>d3.color() function</title>      <script src='https://d3js.org/d3.v4.min.js'></script></head>  <body>    <script>                  // Calling the d3.color() function function        // with some parameters        var color1 = d3.color("red");        var color2 = d3.color("green");        var color3 = d3.color("blue");                // Getting the RGB or HSL values        console.log(color1);        console.log(color2);        console.log(color3);    </script></body>  </html>
Output:
{"r":255, "g":0, "b":0, "opacity":1}
{"r":0, "g":128, "b":0, "opacity":1}
{"r":0, "g":0, "b":255, "opacity":1}

Example 2:
<!DOCTYPE html><html>  <head>    <title>d3.color() function</title>      <script src='https://d3js.org/d3.v4.min.js'></script></head>  <body>    <script>                  // Calling the d3.color() function function        // without any parameters        var color = d3.color();                // Getting the RGB or HSL values        console.log(color);    </script></body>  </html>
Output:
null

Reference: https://devdocs.io/d3~5/d3-color#color
Akanksha_Rai
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python | Sort tuple list by Nth element of tuple - GeeksforGeeks

11 May, 2020
Sometimes, while working with Python list, we can come across a problem in which we need to sort list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sort() + lambdaThe combination of above functions can be used to perform this task. In this, we just pass a lambda function to sort() with appropriate tuple element index according to which sort has to be performed.
# Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + lambda  # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]  # printing original listprint("The original list is : " + str(test_list))  # index according to which sort to performN = 1  # Sort tuple list by Nth element of tuple# using sort() + lambdatest_list.sort(key = lambda x: x[N])  # printing result print("List after sorting tuple by Nth index sort : " + str(test_list))
The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

 
Method #2 : Using sort() + itemgetter()This is similar to the above method. The difference is just that we use itemgetter(), to perform this task that is done by lambda in above method.
# Python3 code to demonstrate working of# Sort tuple list by Nth element of tuple# using sort() + itemgetter()from operator import itemgetter  # initializing listtest_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]  # printing original listprint("The original list is : " + str(test_list))  # index according to which sort to performN = 1  # Sort tuple list by Nth element of tuple# using sort() + itemgetter()test_list.sort(key = itemgetter(N))  # printing result print("List after sorting tuple by Nth index sort : " + str(test_list))
The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Java Program to Find Area of Rectangle Using Method Overloading - GeeksforGeeks

04 Dec, 2020
A rectangle is a simple flat figure in a plane. It has four sides and four right-angles. In a rectangle all four sides are not of equal length like a square, sides opposite to each other have equal length and both the diagonals of the rectangle have equal length.
Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. 
In this article, we will learn how to find the area of the rectangle using the method overloading.
The area of the rectangle is the product of its length and width/breadth. We can simply calculate the area of the rectangle using the following formula:
Formula:
Area of the rectangle: A = S * T
Here, S is the length of the rectangle and T is the breadth/width of the rectangle.
Below is the implementation of the above approach:
Java
// Java program to find the area of// the rectangle using Method Overloadingimport java.io.*;  class Rectangle {      // Overloaded Area() function to    // calculate the area of the rectangle    // It takes two double parameters    void Area(double S, double T)    {        System.out.println("Area of the rectangle: "                           + S * T);    }      // Overloaded Area() function to    // calculate the area of the rectangle.    // It takes two float parameters    void Area(int S, int T)    {        System.out.println("Area of the rectangle: "                           + S * T);    }}  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating object of Rectangle class        Rectangle obj = new Rectangle();          // Calling function        obj.Area(20, 10);        obj.Area(10.5, 5.5);    }}
Area of the rectangle: 200
Area of the rectangle: 57.75

Time Complexity: O(1)
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Greatest number among three given numbers in PL/SQL - GeeksforGeeks

14 Aug, 2021
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given three numbers and the task is to find greatest among them. 
Examples:  
Input: a = 46, b = 67, c = 21
Output: 67

Input: a = 9887, b = 4554, c = 212
Output: 9887
Approach is to consider the first number and compare it with other two numbers. Similarly, check with second and third.Below is the required implementation: 
SQL
--To find the greatest number-- among given three numbersDECLARE    --a assigning with 46    a NUMBER := 46;    --b assigning with 67    b NUMBER := 67;    --c assigning with 21    c NUMBER := 21;BEGIN    --block start    --If condition start    IF a > b       AND a > c THEN      --if a is greater then print a      dbms_output.Put_line('Greatest number is '                           ||a);    ELSIF b > a          AND b > c THEN      --if b is greater then print b      dbms_output.Put_line('Greatest number is '                           ||b);    ELSE      --if c is greater then print c      dbms_output.Put_line('Greatest number is '                           ||c);    END IF;--end if conditionEND;--End program 
Output:
Greatest number is 67
sagar0719kumar
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between SQL and NoSQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL - ORDER BY
Convert a List of String to a comma separated String in Java - GeeksforGeeks

11 Dec, 2018
Given a List of String, the task is to convert the List to a comma separated String in Java.
Examples:
Input: List<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"

Input: List<String> = ["G", "e", "e", "k", "s"]
Output: "G, e, e, k, s"

Approach: This can be achieved with the help of join() method of String as follows.
Get the List of String.Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters.Print the String.
Get the List of String.
Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters.
Print the String.
Below is the implementation of the above approach:
Program:
// Java program to convert List of String// to comma separated String  import java.util.*;  public class GFG {    public static void main(String args[])    {          // Get the List of String        List<String>            list = new ArrayList<>(                Arrays                    .asList("Geeks",                            "ForGeeks",                            "GeeksForGeeks"));          // Print the List of String        System.out.println("List of String: " + list);          // Convert the List of String to String        String string = String.join(", ", list);          // Print the comma separated String        System.out.println("Comma separated String: "                           + string);    }}
Java-List-Programs
Java-String-Programs
Java-Strings
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How can we set up a MySQL User account by using INSERT INTO statement?

For adding a new user to MySQL, we just need to add a new entry to the user table in the database mysql. To illustrate it we are using the following example −
The following program is an example of adding a new user guest with SELECT, INSERT and UPDATE privileges with the password guest123; the SQL query is −
root@host# mysql -u root -p
Enter password:*******
mysql> use mysql;
Database changed

mysql> INSERT INTO user (host, user, password,select_priv, insert_priv,
update_priv) VALUES ('localhost', 'guest',PASSWORD('guest123'),'Y','Y’,
'Y');
Query OK, 1 row affected (0.20 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT host, user, password FROM user WHERE user = 'guest';
+-----------+---------+------------------+
|     host  |    user |         password |
+-----------+---------+------------------+
| localhost |   guest | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)
When adding a new user, remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example, the password bypass is encrypted to 6f8c114b58f2ce9e.
The FLUSH PRIVILEGES statement tells the server to reload the grant tables. If you don't use it, then you won't be able to connect to MySQL using the new user account at least until the server is rebooted.
Java Assignment Operator Examples

The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program −
Online Demo
public class Test {
   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 0;

      c = a + b;
      System.out.println("c = a + b = " + c );

      c += a ;
      System.out.println("c += a  = " + c );

      c -= a ;
      System.out.println("c -= a = " + c );

      c *= a ;
      System.out.println("c *= a = " + c );

      a = 10;
      c = 15;
      c /= a ;
      System.out.println("c /= a = " + c );

      a = 10;
      c = 15;
      c %= a ;
      System.out.println("c %= a  = " + c );

      c <<= 2 ;
      System.out.println("c <<= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c &= a ;
      System.out.println("c &= a  = " + c );

      c ^= a ;
      System.out.println("c ^= a   = " + c );

      c |= a ;
      System.out.println("c |= a   = " + c );
   }
}
This will produce the following result −
c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10
Difference between Java and PHP - GeeksforGeeks

10 Sep, 2020
Java is a very famous object-oriented programming language. It was developed by Sun Microsystems. It has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. It has a continuous contribution from industry experts, Java developers, and other open-source organizations. 
Example :
Java
// A Java program to print  public class GFG {     public static void main(String args[])     {         System.out.println("Welcome to GFG");     } }
Output:
Welcome to GFG
PHP is a server-side scripting language used mainly for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser.
Example:
PHP
<?php   // Here echo command is// used to display contentecho "Welcome to GFG!"; ?> 
Output:
Welcome to GFG!
Difference between Java and PHP :
JAVA
PHP
PHP-Misc
Difference Between
Java
PHP
Java
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
Anonymous Functions in Scala - GeeksforGeeks

26 Feb, 2019
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.Syntax:
(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)
In the above first syntax, => is known as a transformer. The transformer is used to transform the parameter-list of the left-hand side of the symbol into a new result using the expression present on the right-hand side.
In the above second syntax, _ character is known as a wildcard is a shorthand way to represent a parameter who appears only once in the anonymous function.
When a function literal is instantiated in an object is known as a function value. Or in other words, when an anonymous function is assigned to a variable then we can invoke that variable like a function call. We can define multiple arguments in the anonymous function.
Example 1:
// Scala program to illustrate the anonymous methodobject Main {    def main(args: Array[String])     {                  // Creating anonymous functions        // with multiple parameters Assign        // anonymous functions to variables         var myfc1 = (str1:String, str2:String) => str1 + str2                  // An anonymous function is created         // using _ wildcard instead of         // variable name because str1 and        // str2 variable appear only once         var myfc2 = (_:String) + (_:String)                  // Here, the variable invoke like a function call        println(myfc1("Geeks", "12Geeks"))        println(myfc2("Geeks", "forGeeks"))    }}
Output:
Geeks12Geeks
GeeksforGeeks

 
We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function.Example 2:
// Scala program to illustrate anonymous methodobject Main {    def main(args: Array[String])     {                  // Creating anonymous functions         // without parameter         var myfun1 = () => {"Welcome to GeeksforGeeks...!!"}        println(myfun1())                  // A function which contain anonymous         // function as a parameter        def myfunction(fun:(String, String)=> String) =         {            fun("Dog", "Cat")        }                  // Explicit type declaration of anonymous        // function in another function        val f1 = myfunction((str1: String,                    str2: String) => str1 + str2)                  // Shorthand declaration using wildcard        val f2 = myfunction(_ + _)        println(f1)        println(f2)    }}
Output:
Welcome to GeeksforGeeks...!!
DogCat
DogCat

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | map() method
Scala | flatMap Method
Scala | reduce() Function
Scala List filter() method with example
String concatenation in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala List contains() method with example
Scala String replace() method with example