code-rag-bench/online-tutorials huggingface dataset:
Int64.MaxValue Field in C# with Examples - GeeksforGeeks

08 Apr, 2019
The MaxValue field or property of Int64 Struct is used to represent the maximum value of Int64. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 9223372036854775807. Its hexadecimal value is 0x7FFFFFFFFFFFFFFF.
Syntax:
public const long MaxValue = 9223372036854775807;
Return Value: This field always returns 9223372036854775807.
Example:
// C# program to illustrate the// Int64.MaxValue Fieldusing System;  class GFG {          // Main Method    static public void Main()    {        // display the Maximum        // value of Int64 struct        Console.WriteLine("Maximum Value is: "+                            Int64.MaxValue);                  // taking a variable                         long var1 = 93422337368375807;                  if(var1.Equals(Int64.MaxValue))        {            Console.WriteLine("Equal..!!");            Console.WriteLine("Type of var1 is: {0}",                                var1.GetTypeCode());        }        else        {            Console.WriteLine("Not equal..!!");            Console.WriteLine("Type of var1 is: {0}",                                var1.GetTypeCode());        }    }}
Maximum Value is: 9223372036854775807
Not equal..!!
Type of var1 is: Int64

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int64.maxvalue?view=netframework-4.7.2
CSharp-Int64-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
C# | Data Types
C# | Encapsulation
How to install python modules without root access?

If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given directory:
>>> import os, sys
>>> file_path = 'AdditionalModules/'
>>> sys.path.append(os.path.dirname(file_path))
>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH.
You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/
C# | How to use strings in switch statement - GeeksforGeeks

23 Jan, 2019
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement.
Important points:
Switching on strings can be more costly in term of execution than switching on primitive data types. Therefore, it is good to switch on strings only in cases in which the controlling data is already in string form.
The comparison perform between String objects in switch statements is case sensitive.
You must use break statements in switch case.
Example 1:
// C# program to illustrate hwo to use// a string in switch statementusing System;  class GFG {          // Main Method    static public void Main()    {        string str = "one";                  // passing string "str" in         // switch statement        switch (str) {                      case "one":            Console.WriteLine("It is 1");            break;          case "two":            Console.WriteLine("It is 2");            break;          default:            Console.WriteLine("Nothing");            break;        }    }}
Output:
It is 1
Example 2:
// C# program to illustrate hwo to use// a string in switch statementusing System;  class GFG {          // Main Method    static public void Main()    {        string subject = "C#";                  // passing string "subject" in         // switch statement        switch (subject) {                      case "Java":            Console.WriteLine("Subject is Java");            break;          case "C++":            Console.WriteLine("Subject is C++");            break;          default:            Console.WriteLine("Subject is C#");            break;        }    }}
Output:
Subject is C#

CSharp-ControlFlow
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
Common Language Runtime (CLR) in C#
How to Install PowerShell in Linux? - GeeksforGeeks

06 Oct, 2021

PowerShell is well-known among Windows administrators. It is a.NET-based task-based command-line shell and scripting language. You can quickly automate tasks for operating system maintenance and much more with PowerShell. PowerShell was once only available for Microsoft Windows. This admin tool, on the other hand, can now be installed and used on Linux.
1. The least complex approach to install PowerShell using snap is as per the following :
sudo snap install powershell --classic
Installing PowerShell using snap
2. Now you can simply launch PowerShell by using a simple command :
pwsh
Opening PowerShell
Installing PowerShell from a package repository is the preferred approach in Linux.
1. First update list of system packages using below command :
sudo apt-get update
Update system source
2. Install pre-requisite packages using the below command :
sudo apt-get install -y wget apt-transport-https software-properties-common
Installing pre-requisite packages
3. Now download the Microsoft repository GPG keys :
wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb
Downloading Microsoft GPG key
4. Then register the Microsoft repository GPG keys :
sudo dpkg -i packages-microsoft-prod.deb
Registering GPG key
5. Then update the system source :
sudo apt-get update
Updating system source
6. Enabling the universe repositories :
sudo add-apt-repository universe
Enable universe repositories
7. Now we can finally install PowerShell using the below command :
sudo apt-get install -y powershell
Installing PowerShell
8. Now we can start PowerShell by simply typing the below command :
$ pwsh
Starting PowerShell

how-to-install


Picked


How To


Installation Guide


Linux-Unix

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
PostgreSQL - Array Function

PostgreSQL ARRAY_AGG function is used to concatenate the input values including null into an array.
To understand the ARRAY_AGG function, consider the table COMPANY having records as follows −
testdb# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)
Now, based on the above table, suppose you want to use the ARRAY_AGG, you can do so by using the following command −
testdb=# SELECT ARRAY_AGG(SALARY) FROM COMPANY;
The above given PostgreSQL statement will produce the following result −
                  array_agg
---------------------------------------------
 {20000,15000,20000,65000,85000,45000,10000}


    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Check if an array is sorted and rotated in Python

Suppose we have an array of n unique values. We have to check whether this array is sorted and rotated anti-clockwise. Here at least one rotation is required so a fully sorted array is not considered as sorted and rotated.
So, if the input is like nums = [4,5,6,8,1,3], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8].
To solve this, we will follow these steps −
min_element := minimum of nums
min_index := index of min_element in nums
before_sorted := True
for i in range 1 to min_index - 1, doif nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop
if nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop
before_sorted := False
come out from loop
after_sorted := True
for i in range min_index + 1 to size of nums - 1, doif nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop
if nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop
after_sorted := False
come out from loop
if before_sorted and after_sorted are true and last element of nums < nums[0], thenreturn True
return True
otherwise,return False
return False
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums):
   min_element = 999999
   min_index = -1
   min_element = min(nums)
   min_index = nums.index(min_element) before_sorted = True
   for i in range(1, min_index):
      if nums[i] < nums[i - 1]:
         before_sorted = False
         break
   after_sorted = True
   for i in range(min_index + 1, len(nums)):
      if nums[i] < nums[i - 1]:
         after_sorted = False
         break
   if before_sorted and after_sorted and nums[-1] < nums[0]:
      return True
   else:
      return False
nums = [4,5,6,8,1,3]
print(solve(nums))
[4,5,6,8,1,3]
True
Python os.remove() Method

Python method remove() removes the file path. If the path is a directory, OSError is raised.
Following is the syntax for remove() method −
os.remove(path)

path − This is the path, which is to be removed.
path − This is the path, which is to be removed.
This method does not return any value.
The following example shows the usage of remove() method.
# !/usr/bin/python

import os, sys

# listing directories
print "The dir is: %s" %os.listdir(os.getcwd())

# removing
os.remove("aa.txt")

# listing directories after removing path
print "The dir after removal of path : %s" %os.listdir(os.getcwd())
When we run above program, it produces following result −
The dir is:
[ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal of path : 
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]


    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
Protected vs Private Access Modifiers in Java - GeeksforGeeks

28 Apr, 2021

Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. 
Access Modifier 1: Protected
The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected.
Syntax:
protected void method_name(){

......code goes here..........

}
Example:
Java
 

 
 










// Java Program to illustrate Protected Access Modifier  
  
// Importing input output classes 
import java.io.*; 
  
// Main class  
public class Main { 
  
  // Input custom string  
  protected String name = "Geeks for Geeks"; 
    
  // Main driver method  
  public static void main(String[] args) { 
      
    // Creating an object of Main class  
    Main obj1 = new Main(); 
      
    // Displaying the object content as created 
    // above of Main class itself   
    System.out.println( obj1.name ); 
     
} 
} 






Geeks for Geeks
Access Modifier 2: Private 
The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private.
Syntax: 
private void method_name(){

......code goes here..........

}
Example:
Java
 

 
 










// Java Program to illustrate Private Access Modifier 
  
// Importing input output classes 
import java.io.*; 
  
// Main class 
public class Main { 
  
    // Input custom string 
    private String name = "Geeks for Geeks"; 
  
    // Main driver method 
    public static void main(String[] args) 
    { 
  
        // Creating an object of Main class 
        Main obj1 = new Main(); 
  
        // Displaying the object content as created 
        // above of Main class itself 
        System.out.println(obj1.name); 
    } 
}






Geeks for Geeks
Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers. 

Java-Modifier


Picked


Difference Between


Java

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
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Python Pillow - Creating a Watermark

You have noticed that, some of the online photos are watermarked. Watermark is definitely one of the better ways to protect your images from misuse. Also, it is recommended to add watermark to your creative photos, before sharing them on social media to prevent it from being misused.
Watermark is generally some text or logo overlaid on the photo that identifies who took the photo or who owns the rights to the photo.
Pillow package allows us to add watermarks to your images. For adding watermark to our image, we need “Image”, “ImageDraw” and “ImageFont” modules from pillow package.
The ‘ImageDraw’ module adds functionality to draw 2D graphics onto new or existing images. The ‘ImageFont’ module is employed for loading bitmap, TrueType and OpenType font files.
Following python program demonstrates how to add watermark to an image using python pillow −
#Import required Image library
from PIL import Image, ImageDraw, ImageFont

#Create an Image Object from an Image
im = Image.open('images/boy.jpg')
width, height = im.size

draw = ImageDraw.Draw(im)
text = "sample watermark"

font = ImageFont.truetype('arial.ttf', 36)
textwidth, textheight = draw.textsize(text, font)

# calculate the x,y coordinates of the text
margin = 10
x = width - textwidth - margin
y = height - textheight - margin

# draw watermark in the bottom right corner
draw.text((x, y), text, font=font)
im.show()

#Save watermarked image
im.save('images/watermark.jpg')
Suppose, following is the input image boy.jpg located in the folder image.
After executing the above program, if you observe the output folder you can see the resultant watermark.jpg file with watermark on it as shown below −

    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
Getting Minimum and Maximum Value in MySQL

We need to use the MAX(columnName) to find the Maximum value in a column, whereas use the MIN(columnName) to find the Maximum value in a column.
Let’s say following is the syntax to find the highest and lowest value in a specific column −
mysql> SELECT @min_val:=MIN(columnName),@max_val:=MAX(columnName) FROM tableName;
mysql> SELECT * FROM tableName WHERE columnName=@min_val OR columnName=@max_val;
Note: Let’s say we have a database named ‘StudentsRecords’ and a table named ‘STUDENT.
Following is our table <STUDENT> −
We will now write the query −
mysql> SELECT @min_val:=MIN(StudentMarks),@max_val:=MAX(StudentMarks) FROM STUDENT;
mysql> SELECT * FROM STUDENT WHERE StudentMarks =@min_val OR StudentMarks =@max_val;
+---------------------+
| StudentMarks        |
+---------------------+
| 97                  |
+---------------------+
In the above query, ‘StudentMarks’refers to the name of the column. The ‘STUDENT’ refers to the name of the table from which the minimum and maximum value is being queried.
boost::split in C++ library - GeeksforGeeks

14 Dec, 2021
This function is similar to strtok in C. Input sequence is split into tokens, separated by separators. Separators are given by means of the predicate.Syntax: 
Template:
split(Result, Input, Predicate Pred);

Parameters:
Input: A container which will be searched.
Pred: A predicate to identify separators. 
This predicate is supposed to return true 
if a given element is a separator.
Result: A container that can hold copies of 
references to the substrings.

Returns: A reference the result
Application : It is used to split a string into substrings which are separated by separators. Example: 
Input : boost::split(result, input, boost::is_any_of("\t"))
       input = "geeks\tfor\tgeeks"
Output : geeks
        for
        geeks
Explanation: Here in input string we have "geeks\tfor\tgeeks"
and result is a container in which we want to store our result
here separator is "\t".
 
CPP
// C++ program to split// string into substrings// which are separated by// separator using boost::split // this header file contains boost::split function#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; int main(){    string input("geeks\tfor\tgeeks");    vector<string> result;    boost::split(result, input, boost::is_any_of("\t"));     for (int i = 0; i < result.size(); i++)        cout << result[i] << endl;    return 0;}
Output: 
geeks
for
geeks        
 
sweetyty
avtarkumar719
cpp-boost
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
vector erase() and clear() in C++
Virtual Function in C++
Templates in C++ with Examples
unordered_map in C++ STL
C++ Data Types
Powershell - Measure-Command Cmdlet

Measure-Command cmdlet is used to meaure the time taken by script or command.
In these example, we're see the Measure-Command cmdlet in action.
In this example, we'll show how to measure time of Get-EventLog command to log an event in PowerShell event log.
Measure-Command { Get-EventLog "Windows PowerShell" }
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 50
Ticks             : 506776
TotalDays         : 5.86546296296296E-07
TotalHours        : 1.40771111111111E-05
TotalMinutes      : 0.000844626666666667
TotalSeconds      : 0.0506776
TotalMilliseconds : 50.6776 


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
What is the difference between functions and methods in JavaScript?

Functions and methods are the same in JavaScript, but a method is a function, which is a property of an object.
The following is an example of a function in JavaScript −
function functionname(param1, param2){
   // code
}
The method is a function associated with an object. The following is an example of a method in JavaScript −
 Live Demo
<html>
   <head>
      <script>
         var employee = {
            empname: "David",
            department : "Finance",
            id : 002,
            details : function() {
               return this.empname + " with Department " + this.department;
            }
         };

         document.write(employee.details());
      </script>
   </head>
</html>
HTTP Requests with axios in ReactJS

In this article, we are going to learn how to send and receive Http Responses with axios in a React application.
Automatic conversion of response to JSON format
Automatic conversion of response to JSON format
Easy to use and more secure
Easy to use and more secure
Setting up global HTTP interceptors
Setting up global HTTP interceptors
Simultaneous Request
Simultaneous Request
npm install axios
OR
yarn add axios
Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager.
https://jsonplaceholder.typicode.com/todos/1
Jsonplaceholder is a fake API which is used to learn the process of the sending requests.
App.jsx
import React, { useEffect, useState } from 'react';
const App = () => {
   const [data, setData] = useState(null);
   const [fetchData, setFetch] = useState(false);

   useEffect(() => {
      if (fetchData) {
         axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((res) => setData(res.data.title));
      }
   }, [fetchData]);
   return (
      <>
         <h1>{data}</h1>
         <button onClick={() => setFetch(true)}>Fetch Data</button>
      </>
   );
};
export default App;
In the above example, we are sending the GET request to the jsonplaceholder and accessing the data which is going to be inserted in the state as soon as the response is received.
This will produce the following result.
https://jsonplaceholder.typicode.com/todos/1
Jsonplaceholder is a fake API which is used to learn the process of the sending requests.
App.jsx
import React, { useEffect, useState } from 'react';
import './App.css';
const App = () => {
   const [data, setData] = useState(null);
   const [val, setVal] = useState('');
   const [fetchData, setFetch] = useState(false);

   useEffect(() => {
      if (fetchData) {
         const payload = {
            method: 'POST',
            body: JSON.stringify({ title: val }),
         };
         axios.post('https://jsonplaceholder.typicode.com/posts', payload)
.then((res) => setData(res.data.id));
      }
   }, [fetchData]);
   return (
      <>
         {data && <h1>Your data is saved with Id: {data}</h1>}
         <input
            placeholder="Title of Post"
            value={val}
            onChange={(e) => setVal(e.target.value)}
         />
         <button onClick={() => setFetch(true)}>Save Data</button>
      </>
   );
};
export default App;
In the above example, we are sending the POST request to the jsonplaceholder with the input field value in the body and displaying the response accordingly.
This will produce the following result.
Python - Test if list is Palindrome - GeeksforGeeks

11 Oct, 2020
Given a List, check if its palindrome. 
Input : test_list = [4, 5, 4] Output : True Explanation : List is same from front and rear.
Input : test_list = [4, 5, 5] Output : True Explanation : List is not same from front and rear. 
Method #1: Using list slicing
In this, we extract first and reversed 2nd half of list, and then compare for equality, if found equal, then we conclude its palindrome.
Python3
# Python3 code to demonstrate working of # Test if list is Palindrome# Using list slicing  # initializing listtest_list = [1, 4, 5, 4, 1]  # printing original listprint("The original list is : " + str(test_list))  # Reversing the listreverse = test_list[::-1]  # checking if palindromeres = test_list == reverse  # printing result print("Is list Palindrome : " + str(res))
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True

Method #2 : Using reversed()
In this, we simply reverse the list and check if both original list and reversed list is similar.
Python3
# Python3 code to demonstrate working of # Test if list is Palindrome# Using reversed()  # initializing listtest_list = [1, 4, 5, 4, 1]  # printing original listprint("The original list is : " + str(test_list))  # reversing listrev_list = list(reversed(test_list))  # checking for Palindromeres = rev_list == test_list  # printing result print("Is list Palindrome : " + str(res))
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Find keys with duplicate values in dictionary in Python

While dealing with dictionaries, we may come across situation when there are duplicate values in the dictionary while obviously the keys remain unique. In this article we will see how we can achieve thi.
We exchange the keys with values of the dictionaries and then keep appending the values associated with a given key. This way the duplicate values get clubbed and we can see them in the resulting new dictionary.
 Live Demo
dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}

print("Given Dictionary :", dictA)

k_v_exchanged = {}

for key, value in dictA.items():
   if value not in k_v_exchanged:
      k_v_exchanged[value] = [key]
   else:
      k_v_exchanged[value].append(key)

# Result
print("New Dictionary:", k_v_exchanged)
Running the above code gives us the following result −
Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}
New Dictionary: {5: ['Sun', 'Tue'], 3: ['Mon', 'Wed']}
we follow a similar approach here. Here also we create a new dictionary from the existing dictionary using set function and adding the keys with duplicate values. Finally we filter out the values where the length is greater than 1 and mark them as duplicates.
 Live Demo
dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}

print("Given Dictionary :", dictA)

dictB = {}
for key, value in dictA.items():
   dictB.setdefault(value, set()).add(key)

res = filter(lambda x: len(x) >1, dictB.values())

# Result
print("New Dictionary:",list(res))
Running the above code gives us the following result −
Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}
New Dictionary: [{'Tue', 'Sun'}]
Puzzle 17 | (Ratio of Boys and Girls in a Country where people want only boys)

11 May, 2021
In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country?
   
Solution:Assumptions: Probability of having a boy or girl is same. Also, the probability of next kid being a boy doesn’t depend on history.
The problem can be solved by counting expected number of girls before a baby boy is born.

Let NG be the expected no. of girls before a boy is born

Let p be the probability that a child is girl and (1-p)
be probability that a child is boy.

NG can be written as sum of following infinite series.

NG = 0*(1-p) + 1*p*(1-p) + 2*p*p*(1-p) + 3*p*p*p*(1-p) + 4*p*p*p*p*(1-p) +.....

Putting p = 1/2 and (1-p) = 1/2 in above formula.

NG    = 0*(1/2) + 1*(1/2)2 + 2*(1/2)3 + 3*(1/2)4  +  4*(1/2)5 + ...
1/2*NG = 0*(1/2)2 + 1*(1/2)3 + 2*(1/2)4 + 3*(1/2)5  +  4*(1/2)6 + ...

NG - NG/2 =  1*(1/2)2 + 1*(1/2)3 + 1*(1/2)4 + 1*(1/2)5  +  1*(1/2)6 + ...

Using sum formula of infinite geometrical progression with
ratio less than 1
NG/2 = (1/4)/(1-1/2) = 1/2

NG = 1

So Expected Number of number of girls = 1
Since the expected number of girls is 1 and there is always a baby boy, the expected ratio of boys and girls is 50:50
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VirajD
rtrjjadhav001
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 21 | (3 Ants and Triangle)
Puzzle 24 | (10 Coins Puzzle)
Container with Most Water
Puzzle | Set 35 (2 Eggs and 100 Floors)
Puzzle 31 | (Minimum cut Puzzle)
Puzzle | Heaven and Hell
Puzzle | 3 cuts to cut round cake into 8 equal pieces
Puzzle 27 | (Hourglasses Puzzle)
Python | sympy.expand() method

12 Jun, 2019
With the help of sympy.expand() method, we can expand the mathematical expressions in the form of variables by using sympy.expand() method.
Syntax : sympy.expand(expression)Return : Return mathematical expression.
Example #1 :In this example we can see that by using sympy.expand() method, we can get the mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol.
# import sympyfrom sympy import expand, symbols  x, y = symbols('x y')gfg_exp = x + y  # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2)  print(exp)
Output :
x**2 + 2*x*y + y**2
Example #2 :
# import sympyfrom sympy import expand, symbols  x, y, z = symbols('x y z')gfg_exp = x + y + z  # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2)  print(exp)
Output :
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Range Slider using Material UI in React

11 Feb, 2021
Material-UI is a React-based module. The Material-UI library provides users with the most efficient, effective, and user-friendly interface. For using the Range slider we need to install Material-UI. Moreover, for the custom styling, you can always refer to the API of the SVG icon component in Material-UI.
Prerequisites:
Basics of ReactJS
Already created ReactJS app
Below all the steps are described order wise to add colors to icons.
Installation:
Step 1: Before moving further, firstly we have to install the Material-UI module, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.
npm install @material-ui/core  
Step 2: After installing the module, now open your App.js file which is present inside your project’s directory, under src folder, and delete the code present inside it.
Step 3: Now import React , useState ( for initial state of slider) from react and Slider from Material-UI module.
Step 4: In your app.js file, add this code snippet to import  React , useState( for initial state of slider) from react and Slider from Material-UI module.
import React, { useState } from "react";
import { Slider } from "@material-ui/core";
The file structure of the project will look like:
Below is a sample program to illustrate the use of slider :
Example: Range slider for Current Temperature in the city.
Filename- src/App.js:
Javascript
//We use useState for the initial set valuesimport React, { useState } from "react";import "./App.css";//we import slider from material uiimport { Slider } from "@material-ui/core";  function App() {  //Providing different values with labels  const gfg = [    {      value: 0,      label: "0°C",    },    {      value: 25,      label: "25°C",    },    {      value: 50,      label: "50°C",    },    {      value: 100,      label: "100°C",    },  ];    const [val, setVal] = useState([0, 40]);  const updateRange = (e, data) => {    setVal(data);  };  return (    <div className="App">      <h1> What is the current temperature in your City ? </h1>      <div style={{ width: 500, margin: 60 }}>        <span> Temperature : </span>{" "}        <Slider value={val} onChange={updateRange} marks={gfg} />      </div>{" "}    </div>  );}export default App;
Filename- src/App.css:
CSS
body {  margin: 0px;}.App {  font-family: sans-serif;  color: green;  font-size: 16px;}  span {  color: red;  font-size: 18px;  font-weight: 13px;  font-family: Verdana, Geneva, Tahoma, sans-serif;    }
Output: Hence using the above-mentioned steps, we can use the Material-UI Slider to make a range slider in ReactJS.
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sort Tuples in Increasing Order by any key

18 Dec, 2017
Given a tuple, sort the list of tuples in increasing order by any key in tuple.
Examples:
Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] 
            m = 0
Output : [(1, 2), (2, 3), (2, 5), (4, 4)]
Explanation: Sorted using the 0th index key.

Input :  [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
         m = 2
Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] 
Explanation: Sorted using the 2nd index key

Given tuples, we need to sort them according to any given key. This can be done using sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples.
Below is the Python implementation of the above approach:
# Python code to sort a list of tuples # according to given key.  # get the last key.def last(n):    return n[m]     # function to sort the tuple   def sort(tuples):      # We pass used defined function last    # as a parameter.     return sorted(tuples, key = last)   # driver code  a = [(23, 45, 20), (25, 44, 39), (89, 40, 23)]m = 2print("Sorted:"),print(sort(a))
Output:
Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] 

python-tuple
Python
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
PostgreSQL – REVOKE

17 Aug, 2021
In PostgreSQL, the REVOKE statement is used to revoke previously granted privileges on database objects through a role.
The following shows the syntax of the REVOKE statement:
Syntax: 
REVOKE privilege | ALL
ON TABLE tbl_name |  ALL TABLES IN SCHEMA schema_name
FROM role_name;
Let’s analyze the above syntax:
First, specify the privileges that is to be revoked. Use the ALL option to revoke all previously granted privileges.
Then, set the name of the table after the ON keyword.
Finally, specify the name of the role whose privileges is to be revoked.
Example:
First,log into the dvdrental sample database as Postgres:
psql -U postgres -d dvdrental
Now initialize a role called ‘abhishek’ with the LOGIN and PASSWORD attributes as shown below:
CREATE ROLE abhishek
LOGIN 
PASSWORD 'geeks12345';
Now grat all privileges on the film table to the role ‘abhishek’ as shown below:
GRANT ALL 
ON film
TO abhishek;
Now provide the SELECT privilege on the actor table to the role ‘abhishek’ as shown below:
GRANT SELECT
ON actor
TO abhishek;
Here we will revoke the SELECT privilege on the actor table from the role ‘abhishek’, as shown below:
REVOKE SELECT
ON actor
FROM abhishek;
If you wish to revoke all privileges on the film table from the role ‘abhishek’, make use of theREVOKE statement with the ALL option as shown below:
REVOKE ALL
ON film
FROM abhishek;
Output:
simranarora5sos
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
PostgreSQL – IF Statement

22 Feb, 2022
PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.
Syntax:
IF condition THEN
   statements;
END IF;

The above conditional statement is a boolean expression that evaluates to either true or false.
Example 1:
In this example, we declare two variables a and b. In the body of the block, we compare the value of a and b using the comparison operator >, < and = in the boolean expressions of the IF statements.
DO $$
DECLARE
  a integer := 10;
  b integer := 20;
BEGIN 
  IF a > b THEN
    RAISE NOTICE 'a is greater than b';
  END IF;

  IF a < b THEN
    RAISE NOTICE 'a is less than b';
  END IF;

  IF a = b THEN
    RAISE NOTICE 'a is equal to b';
  END IF;
END $$;

Output:
Example 2:
DO $$
DECLARE
   a integer := 10;
   b integer := 10;
BEGIN 
  IF a > b THEN 
     RAISE NOTICE 'a is greater than b';
  ELSIF a < b THEN
     RAISE NOTICE 'a is less than b';
  ELSE
     RAISE NOTICE 'a is equal to b';
  END IF;
END $$;

Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
Google Cloud Platform – Introduction to BigQuery Sandbox

23 Apr, 2021
BigQuery sandbox gives you free access to try out BigQuery and use the UI without providing a credit card or using a billing account. It’s a quick way to get started and try out some BigQuery concepts. 
To get started, click on this link and follow along with the rest of the article. If you’re a new Google Cloud user, you’ll need to create an account and a project by following the prompts.
Once a project is created, you’ll be redirected to the BigQuery console, where you’ll see Sandbox in the top left-hand corner.
 If you’re a returning Google Cloud user, create a new project by selecting the Project dropdown.
 Your new project may be created with a default billing account. If that’s the case, go into the Billing Account Management page and select Disable Billing. Then use the search bar within the console to head to BigQuery.
 Make sure your new project is selected in the Project dropdown, and there, you will also see Sandbox in the top left-hand corner. Now that you’re in the BigQuery Sandbox, you’re ready to start querying. That’s all it takes to get set up.
 Because you aren’t charged for using the BigQuery Sandbox, there are a few caveats. Mainly, any tables or views that you create will expire after 60 days. You’re also limited to 10 gigabytes of storage, and one terabyte of data process each month. Now you can easily start working with public data sets, loading in your own data, and running some queries.
 BigQuery provides publicly available data sets for anyone to analyze covering a variety of data types, from historical weather to taxi trips taken in New York City. To analyze public data, just click on the Add Data button on the left-hand side to see a list of the publicly available data sets that you already have available.
As a quick example, let’s use the project sunroof public data set, so you can see how much sunlight hits your roof in a year. For this we will be using the following query:
SELECT state_name, AVG(yearly_sunlight_kwh_kw_threshold_avg) AS average_sun
FROM 'bigquery-public-data.sunroof_solar.solar_potential_by_postal_code'
GROUP BY state_name
ORDER BY average_sun DESC
IMIT 3
 In this sample query, we’re averaging the amount of sunlight per US state and ordering the top three states by the highest sunlight potential. As you can see, the top three states are New Mexico, Arizona, and Nevada.
Cloud-Computing
Google Cloud Platform
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Software Testing - Web Based Testing
Floyd’s Cycle Finding Algorithm
Samsung R&D Interview Experience
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
Deutsche Bank Interview Experience (2021-22 )
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
Python | Ways to create triplets from given list

18 Feb, 2019
Given a list of words, write a Python program to create triplets from the given list.
Examples :
Input: [‘Geeks’, ‘for’, ‘Geeks’, ‘is’, ‘best’, ‘resource’, ‘for’, ‘study’]Output:[[‘Geeks’, ‘for’, ‘Geeks’], [‘for’, ‘Geeks’, ‘is’],[‘Geeks’, ‘is’, ‘best’], [‘is’, ‘best’, ‘resource’],[‘best’, ‘resource’, ‘for’], [‘resource’, ‘for’, ‘study’]]
Input: [‘I’, ‘am’, ‘Paras’, ‘Jain’, ‘I’, ‘Study’, ‘From’, ‘GFG’]Output:[[‘I’, ‘am’, ‘Paras’], [‘am’, ‘Paras’, ‘Jain’],[‘Paras’, ‘Jain’, ‘I’], [‘Jain’, ‘I’, ‘Study’],[‘I’, ‘Study’, ‘From’], [‘Study’, ‘From’, ‘GFG’]]
Let’s see some of the methods to do this task.
Method #1: Using List comprehension
# Python code to create triplets from list of words.  # List of word initializationlist_of_words = ['I', 'am', 'Paras', 'Jain',                 'I', 'Study', 'DS', 'Algo']  # Using list comprehensionList = [list_of_words[i:i + 3]         for i in range(len(list_of_words) - 2)]  # printing listprint(List)
[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], 
 ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'],
 ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]

 Method #2: Using Iteration
# Python code to create triplets from list of words.  # List of word initializationlist_of_words = ['Geeks', 'for', 'Geeks', 'is',                 'best', 'resource', 'for', 'study']  # Output list initializationout = []  # Finding length of listlength = len(list_of_words)  # Using iterationfor z in range(0, length-2):    # Creating a temp list to add 3 words    temp = []    temp.append(list_of_words[z])    temp.append(list_of_words[z + 1])    temp.append(list_of_words[z + 2])    out.append(temp)  # printing outputprint(out)
[['Geeks', 'for', 'Geeks'], ['for', 'Geeks', 'is'],
 ['Geeks', 'is', 'best'], ['is', 'best', 'resource'],
 ['best', 'resource', 'for'], ['resource', 'for', 'study']]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Node.js http.IncomingMessage.headers Method - GeeksforGeeks

19 Jan, 2022
The http.IncomingMessage.headers is an inbuilt application programming interface of class IncomingMessage within HTTP module which is used to get all the request/response headers object.
Syntax:
const message.headers
Parameters: This method does not accept any argument as a parameter.
Return Value: This method returns all the request/response headers object.
Example 1:
Filename: index.js
Javascript
// Node.js program to demonstrate the // request.headers method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer(    function (request, response) {   // Getting request/response header  // by using request.complete method  const value = request.headers;   // Display header  console.log(value.connection)   // Display result  response.end("hello world", 'utf8', () => {    console.log("displaying the result...");     httpServer.close(() => {      console.log("server is closed")    })  });}); // Listening to http ServerhttpServer.listen(PORT, () => {  console.log("Server is running at port 3000...");});
Run the index.js file using the following command.
node index.js
Output:
Output: In-Console
Server is running at port 3000...
keep-alive
displaying the result...
Now go to http://localhost:3000/ in the browser, you will see the following output:
hello world
Example 2:
Filename: index.js
Javascript
// Node.js program to demonstrate the // request.headers Method // Importing http modulevar http = require('http'); // Request and response handlerconst http2Handlers = (request, response) => {   // Getting request/response header  // by using request.complete method  const value = request.headers;   // Display header  console.log(value.host)   // Display result  response.end("hello world!!", 'utf8', () => {    console.log("displaying the result...");     httpServer.close(() => {      console.log("server is closed")    })  });}; // Creating http Servervar httpServer = http.createServer(  http2Handlers).listen(3000, () => {  console.log("Server is running at port 3000...");});
Run the index.js file using the following command.
node index.js
Output:
Server is running at port 3000...
localhost:3000
displaying the result...
Now go to http://localhost:3000/ in the browser, you will see the following output:
hello world!!
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_message_headers
clintra
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
C program to print multiplication table by using for Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Given below is an algorithm to print multiplication table by using for loop in C language −
Step 1: Enter a number to print table at runtime.
Step 2: Read that number from keyboard.
Step 3: Using for loop print number*I 10 times.
      // for(i=1; i<=10; i++)
Step 4: Print num*I 10 times where i=0 to 10.
Following is the C program for printing a multiplication table for a given number −
 Live Demo
#include <stdio.h>
int main(){
   int i, num;
   /* Input a number to print table */
   printf("Enter number to print table: ");
   scanf("%d", &num);
   for(i=1; i<=10; i++){
      printf("%d * %d = %d\n", num, i, (num*i));
   }
   return 0;
}
When the above program is executed, it produces the following result −
Enter number to print table: 7
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70