code-rag-bench/online-tutorials huggingface dataset:
Set add() method in Java with Examples

31 Dec, 2018
The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set.
Syntax:
boolean add(E element)

Where, E is the type of element maintained
by this Set collection.

Parameters: The parameter element is of the type of element maintained by this Set and it refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the set and is new, else it returns False if the element is already present in the set.
Below programs illustrate the use of Java.util.Set.add() method:
Program 1:
// Java code to illustrate add() methodimport java.io.*;import java.util.*;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> s = new HashSet<String>();          // Use add() method to add elements into the Set        s.add("Welcome");        s.add("To");        s.add("Geeks");        s.add("4");        s.add("Geeks");        s.add("Set");          // Displaying the Set        System.out.println("Set: " + s);    }}
Set: [Set, 4, Geeks, Welcome, To]

Program 2:
// Java code to illustrate add() methodimport java.io.*;import java.util.*;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<Integer> s = new HashSet<Integer>();          // Use add() method to add elements into the Set        s.add(10);        s.add(20);        s.add(30);        s.add(40);        s.add(50);        s.add(60);          // Displaying the Set        System.out.println("Set: " + s);    }}
Set: [50, 20, 40, 10, 60, 30]

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)
Java-Collections
Java-Functions
java-set
Misc
Misc
Misc
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
General purpose registers in 8086 microprocessor

24 Jun, 2022
General-purpose registers are used to store temporary data within the microprocessor. There are 8 general-purpose registers in the 8086 microprocessor.
 
1. AX: This is the accumulator. It is of 16 bits and is divided into two 8-bit registers AH and AL to also perform 8-bit instructions. It is generally used for arithmetical and logical instructions but in 8086 microprocessor it is not mandatory to have an accumulator as the destination operand. Example:
ADD AX, AX (AX = AX + AX)
2. BX: This is the base register. It is of 16 bits and is divided into two 8-bit registers BH and BL to also perform 8-bit instructions. It is used to store the value of the offset. Example:
MOV BL, [500] (BL = 500H)
3. CX: This is the counter register. It is of 16 bits and is divided into two 8-bit registers CH and CL to also perform 8-bit instructions. It is used in looping and rotation. Example:
MOV CX, 0005
LOOP
4. DX: This is the data register. It is of 16 bits and is divided into two 8-bit registers DH and DL to also perform 8-bit instructions. It is used in the multiplication and input/output port addressing. Example:
MUL BX (DX, AX = AX * BX)
5. SP: This is the stack pointer. It is of 16 bits. It points to the topmost item of the stack. If the stack is empty the stack pointer will be (FFFE)H. Its offset address is relative to the stack segment.
6. BP – This is the base pointer. It is of 16 bits. It is primarily used in accessing parameters passed by the stack. Its offset address is relative to the stack segment.
7. SI – This is the source index register. It is of 16 bits. It is used in the pointer addressing of data and as a source in some string-related operations. Its offset is relative to the data segment.
8. DI – This is the destination index register. It is of 16 bits. It is used in the pointer addressing of data and as a destination in some string-related operations. Its offset is relative to the extra segment.
tilakraj7050
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Control Characters
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Programmable peripheral interface 8255
Architecture of 8085 microprocessor
Interrupts
Write Through and Write Back in Cache
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Python – Specific Characters Frequency in String List

05 Sep, 2020
Given String list, extract frequency of specific characters in whole strings list.
Input : test_list = [“geeksforgeeks is best for geeks”], chr_list = [‘e’, ‘b’, ‘g’, ‘f’]Output : {‘g’: 3, ‘e’: 7, ‘b’: 1, ‘f’ : 1}Explanation : Frequency of certain characters extracted.
Input : test_list = [“geeksforgeeks], chr_list = [‘e’, ‘g’]Output : {‘g’: 2, ‘e’: 4}Explanation : Frequency of certain characters extracted.
Method #1 : Using join() + Counter()
In this, we concatenate all the strings, and then Counter() performs task of getting all frequencies. Last step is to get only specific characters from List in dictionary using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using join() + Counter()from collections import Counter  # initializing liststest_list = ["geeksforgeeks is best for geeks"]  # printing original listprint("The original list : " + str(test_list))  # char list chr_list = ['e', 'b', 'g']  # dict comprehension to retrieve on certain Frequenciesres = {key:val for key, val in dict(Counter("".join(test_list))).items() if key in chr_list}      # printing result print("Specific Characters Frequencies : " + str(res))
The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}

Method #2 : Using chain.from_iterable() + Counter() + dictionary comprehension
In this, task of concatenation is done using chain.from_iterable() rather than join(). Rest all tasks are done as above method.
Python3
# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using chain.from_iterable() + Counter() + dictionary comprehensionfrom collections import Counterfrom itertools import chain  # initializing liststest_list = ["geeksforgeeks is best for geeks"]  # printing original listprint("The original list : " + str(test_list))  # char list chr_list = ['e', 'b', 'g']  # dict comprehension to retrieve on certain Frequencies# from_iterable to flatten / joinres = {key:val for key, val in dict(Counter(chain.from_iterable(test_list))).items() if key in chr_list}      # printing result print("Specific Characters Frequencies : " + str(res))
The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print factors of a number in pairs

12 Apr, 2021
Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself;Examples:  
Input : 24
Output : 1*24
         2*12
         3*8
         4*6

Input : 50
Output : 1*50
         2*25
         5*10
 
The simplest approach for this program is that we run a loop from 1 to the square root of N and print and print ‘i’ and ‘N%i’ if the number N is dividing ‘i’. The mathematical reason why we run the loop till square root of N is given below:If a*b = N where 1 < a ≤ b < N N = ab ≥ a^2 ⇔ a^2 ≤ N ⇔ a ≤ √N 
C++
Java
C#
Python 3
PHP
Javascript
// CPP program to print prime factors in// pairs.#include <iostream>using namespace std; void printPFsInPairs(int n){    for (int i = 1; i * i <= n; i++)        if (n % i == 0)            cout << i << "*" << n / i << endl;} // Driver codeint main(){    int n = 24;    printPFsInPairs(n);    return 0;}
// Java program to print prime factors in// pairs.public class GEE {     static void printPFsInPairs(int n)    {        for (int i = 1; i * i <= n; i++)            if (n % i == 0)                System.out.println(i + "*" + n / i);    }     // Driver code    public static void main(String[] args)    {         int n = 24;        printPFsInPairs(n);    }}
// C# program to print prime factors in// pairs.using System;public class GEE {     static void printPFsInPairs(int n)    {        for (int i = 1; i * i <= n; i++)            if (n % i == 0)                Console.Write(i + "*" + n / i + "\n");    }     // Driver code    public static void Main()    {         int n = 24;        printPFsInPairs(n);    }}
# Python 3 program to print prime factors in# pairs.  def printPFsInPairs(n):    for i in range(1, int(pow(n, 1 / 2))+1):        if n % i == 0:            print(str(i) +"*"+str(int(n / i)))    # Driver coden = 24printPFsInPairs(n)
<?php// PHP program to print prime factors in// pairs.  function printPFsInPairs($n){    for ($i = 1; $i*$i <= $n; $i++)        if ($n % $i == 0)            echo $i."*". $n / $i ."\n";   }  // Driver code$n = 24;printPFsInPairs($n);return 0;?>
<script> // Javascript program to print prime factors in// pairs. function printPFsInPairs(n){    for (let i = 1; i * i <= n; i++)        if (n % i == 0)            document.write(i + "*" + parseInt(n / i) + "<br>");} // Driver codelet n = 24;printPFsInPairs(n); </script>
1*24
2*12
3*8
4*6
 
ukasp
subham348
prime-factor
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Segment Tree | Set 1 (Sum of given range)
Count ways to reach the n'th stair
Check if a number is Palindrome
Median of two sorted arrays of same size
Product of Array except itself
Fizz Buzz Implementation
Flutter – Changing App Icon

29 Dec, 2020
Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. When we create a Flutter Project, it comes with the default Flutter icon. In order to get the app published in stores like Google Play Store, Apple App Store, etc the default icon can be changed.  In this article, we will look into a few possible approaches to achieve the same.
There are Two ways to change the App Icon:
Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon.
Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon.
      2. Using Package which will add all the sizes of Icons in Android and IOS folders Automatically.
Go to https://appicon.co/  and upload the icon image and tick the iPhone and Android options and click on Generate. This site generates different sized Icons for both android and IOS at the same time.
It will Download the Zip file named AppIcons with the android and Assets.xcassets named folders along with images for appstore and playstore which can be directly uploaded as an icon in both the stores
Now, open your Project in Vs Code.
 Navigate to android/app/src/main/res and right-click on res folder and click “reveal in Explorer”. Now delete all the mipmap folders in res folder and paste the mipmap folders from AppIcon/android folder which you have downloaded.
Icons changed in the res folder
Now navigate to the ios/Runner/Assets.xcassets. Now after you are in Runner folder, right-click on Runner folder and click “reveal in Explorer”. Now delete the Assets.xcassets folder and paste the Assets.xcassets folder from AppIcon/Assets.xcassets which you have downloaded.
Assets.xcassets Changed in Runner Folder
After manually changing the images in android and IOS folders now go to lib/main.dart and run the flutter project using the below command in the flutter console.
flutter run
By using the package we can generate the different sized Icons at a time for both android and IOS. 
Open your Project in Vs Code and Go to pubspec.yaml file.
Go to dev_dependencies and add flutter_launcher_icons: “^0.8.0” dependency and save the file. It will get the dependency. 
Adding dependency in dev_dependencies 
Now add the flutter_icons: and save.
Now create assets folder -> create icon folder -> add icon.png file 
Note: If you are not having .png image, then change the image format in image_path: as shown in the above image.
Open the Terminal in Vs Code and run 
flutter pub get
After the command is executed successfully then run 
flutter pub run flutter_launcher_icons:main
After both the commands are executed successfully then go to lib/main.dart file and run the app
flutter run
Output: 
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to redirect to a relative URL in JavaScript?

31 Oct, 2019
This works in the same way as redirecting to any URL in javascript.
Approach 1: To redirect to a relative URL in JavaScript you can usewindow.location.href = '/path';window.location.href returns the href (URL) of the current pageExample 1: A simple redirecting program<!DOCTYPE html><html><head>  <script>    function newLocation() {        window.location.href="page.html";    }  </script></head><body>  <input type="button" value="Go to new location" onclick="newLocation()"></body></html>Output:
window.location.href = '/path';
window.location.href returns the href (URL) of the current page
Example 1: A simple redirecting program
<!DOCTYPE html><html><head>  <script>    function newLocation() {        window.location.href="page.html";    }  </script></head><body>  <input type="button" value="Go to new location" onclick="newLocation()"></body></html>
Output:
Approach 2: To redirect to a relative url you can usedocument.location.href = '../';Both windows.location.href and document.location.href are same.Example 2: A simple redirecting program<!DOCTYPE html><html><head>  <script>    function newLocation() {        document.location.href="page.html";    }  </script></head><body>  <input type="button" value="Go to new location" onclick="newLocation()"></body></html>Output:NOTE: You can use both methods but for cross browser safety first one is preferred.
document.location.href = '../';
Both windows.location.href and document.location.href are same.
Example 2: A simple redirecting program
<!DOCTYPE html><html><head>  <script>    function newLocation() {        document.location.href="page.html";    }  </script></head><body>  <input type="button" value="Go to new location" onclick="newLocation()"></body></html>
Output:
NOTE: You can use both methods but for cross browser safety first one is preferred.
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
How to get character array from string in JavaScript?
JavaScript | console.log() with Examples
How to filter object array based on attributes?
turtle.fillcolor() function in Python

06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to return or set the fillcolor. If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.
Syntax : turtle.fillcolor(*args)
fillcolor() : Return the current fillcolor as color specification string, possibly in hex-number format.
fillcolor(colorstring) : It is a Tk color specification string, such as “red” or “yellow”.
fillcolor((r, g, b)) : A tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0 to colormode
fillcolor(r, g, b) : r, g, and b represent an RGB color, and each of r, g, and b  are in the range 0 to colormode.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle  # set turtleturtle.shape("turtle")turtle.turtlesize(3,3,1)  # check by default valueprint(turtle.fillcolor())  # set blue colorturtle.fillcolor("blue")  # check fillcolor valueprint(turtle.fillcolor())
Output :
black
blue

Example 2 :
Python3
# importing packageimport turtle  # method to draw a stardef star():    for i in range(5):        turtle.forward(60)        turtle.right(144)  # method to set position# and fill color in stardef draw(x,y,col):    turtle.up()    turtle.setpos(x,y)    turtle.down()    turtle.fillcolor(col)    turtle.begin_fill()    star()    turtle.end_fill()  # Driver Codedraw(-100,0,"red")draw(-50,0,"yellow")draw(0,0,"blue")draw(50,0,"green")  # hide the turtleturtle.hideturtle()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lambda and filter in Python Examples

09 Jul, 2021
Prerequisite : Lambda in Python
Given a list of numbers, find all numbers divisible by 13.
Input : my_list = [12, 65, 54, 39, 102, 
                     339, 221, 50, 70]
Output : [65, 39, 221]

We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name.
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.
# Python Program to find numbers divisible # by thirteen from a list using anonymous # function  # Take a list of numbers. my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]  # use anonymous function to filter and comparing # if divisible or notresult = list(filter(lambda x: (x % 13 == 0), my_list))   # printing the resultprint(result) 
Output:
[65, 39, 221]

Given a list of strings, find all palindromes.
# Python Program to find palindromes in # a list of strings.  my_list = ["geeks", "geeg", "keek", "practice", "aa"]  # use anonymous function to filter palindromes.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/result = list(filter(lambda x: (x == "".join(reversed(x))), my_list))   # printing the resultprint(result) 
Output :
['geeg', 'keek', 'aa']

Given a list of strings and a string str, print all anagrams of str
# Python Program to find all anagrams of str in # a list of strings.from collections import Counter  my_list = ["geeks", "geeg", "keegs", "practice", "aa"]str = "eegsk"  # use anonymous function to filter anagrams of x.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/anagram-checking-python-collections-counter/result = list(filter(lambda x: (Counter(str) == Counter(x)), my_list))   # printing the resultprint(result) 
Output :
['geeks', 'keegs']

Python-Built-in-functions
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating a sorted merged list of two unsorted lists in Python

21 Nov, 2018
We need to take two lists in Python and merge them into one. Finally, we display the sorted list.
Examples:
Input : 
list1 = [25, 18, 9, 41, 26, 31]
list2 = [25, 45, 3, 32, 15, 20]
Output :
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]

Input : 
list1 = ["suraj", "anand", "gaurav", "aman", "kishore"]
list2 = ["rohan", "ram", "mohan", "priya", "komal"]
Output :
['aman', 'anand', 'gaurav', 'kishore', 'komal', 
'mohan', 'priya', 'ram', 'rohan', 'suraj']

The plus operator “+” in Python helps us to merge two lists, be it a list of string or integers or mixture of both. Finally, we sort the list using the sort() function.
# Python program to merge and sort two listdef Merge(list1, list2):    final_list = list1 + list2    final_list.sort()    return(final_list)  # Driver Codelist1 = [25, 18, 9, 41, 26, 31]list2 = [25, 45, 3, 32, 15, 20]print(Merge(list1, list2))
Output:
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Lodash _.sumBy() Method

05 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.sumBy() method is used to compute the sum from the original array by iterating over each element in the array by using the Iteratee function. It is almost the same as _.sum() method.
Syntax:
_.sumBy(array, [iteratee = _.identity])
Parameters: This method accepts two parameters as mentioned above and described below:
array: This parameter holds the array to iterate over.
[iteratee = _.identity]:  This parameter holds the iteratee invoked per element.
Return Value: This method returns the sum.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library  const _ = require("lodash");     // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }];     // Use of _.sumBy()  // method let gfg = _.sumBy(arr, function(o) { return o.n; });          // Printing the output  console.log(gfg);
Output:
12
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");     // Original array var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }];     // Use of _.sumBy()  // method let gfg = _.sumBy(arr, 'n');          // Printing the output  console.log(gfg);
Output:
30
JavaScript-Lodash
JavaScript
Web Technologies
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Difference between C-LOOK and C-SCAN Disk Scheduling Algorithm

21 Jul, 2020
C-LOOK is the modified version of both LOOK and C-scan algorithms. In this algorithm, the head starts from the first request in one direction and moves towards the last request at another end, serving all request in between. After reaching the last request in one end, the head jumps in another direction and move towards the remaining requests and then satisfies them in the same direction as before. Unlike C-SCAN, the head pointer will move till the end request of the disk.
Example :
Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 
98, 183, 40, 122, 10, 124, 65

The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-LOOK algorithm.
Total head movements
= (65 - 53) + (98 - 65)
  + (122 - 98)
  + (124 - 122) + (183 - 124)
  + (183 - 10) + (40 - 10)
= 333

C-scan algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of the disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverses its direction and go to the starting point. It then satisfies the remaining requests, in the same direction as before. Unlike C-LOOK, the head pointer will move till the end of the disk, whether there is a request or not.   
Example –
Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 
98, 183, 40, 122, 10, 124, 65

The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-scan algorithm.
Total head movements
= (65 - 53) + (98 - 65)
   + (122 - 98)
   + (124 - 122) + (183 - 124)
   + (199 - 183) + (199 - 0)
   + (10 - 0) + (40 - 10)
= 395

Algorithms
Difference Between
Operating Systems
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Unlist Single Valued Dictionary List

16 Aug, 2021
Given list of dictionaries, perform the unlisting of records in which we just have 1 dictionary as record element. 
Input : test_list = [{‘best’: [{‘a’: 6}], ‘Gfg’: 15}] Output : [{‘best’: {‘a’: 6}, ‘Gfg’: 15}] Explanation : The value list associated with ‘best’ key is changed to dictionary.
Input : test_list = [{‘Gfg’: [{‘best’ : 17}]}] Output : [{‘Gfg’: {‘best’: 17}}] Explanation : ‘Gfg’ key’s value changed to single dictionary.  
Method #1: Using loop + isinstance() This is brute force way in which this task can be performed. In this, we test for the list type using isinstance(), and loop is used for iterations.
Python3
# Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using loop + isinstance() # initializing listtest_list = [{'Gfg': 1,            'is': [{'a': 2, 'b': 3}]},            {'best': [{'c': 4, 'd': 5}],             'CS': 6}] # printing original listprint("The original list is : " + str(test_list)) # Using loop + isinstance()for dicts in test_list:    for key, val in dicts.items():                 # isinstance() is used to check for list to convert        if isinstance(val, list):            dicts[key] = val[0] # printing resultprint("The converted Dictionary list : " + str(test_list))
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]
 
Method #2: Using list comprehension + isinstance() The combination of above functions can be used to solve the problem. In this, we perform similar task with short hand approach similar to above method.
Python3
# Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using list comprehension + isinstance() # initializing listtest_list = [{'Gfg': 1,            'is': [{'a': 2, 'b': 3}]},            {'best': [{'c': 4, 'd': 5}],             'CS': 6}] # printing original listprint("The original list is : " + str(test_list)) # Using list comprehension + isinstance()# Similar way as above, extracting first element of listres = [{key: val[0] if isinstance(val, list) else val        for key, val in sub.items()}        for sub in test_list] # printing resultprint("The converted Dictionary list : " + str(res))
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]
 
kk773572498
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Collections synchronizedList() method in Java with Examples

08 Oct, 2018
The synchronizedList() method of java.util.Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
Syntax:
public static <T> List<T>
  synchronizedList(List<T> list)
Parameters: This method takes the list as a parameter to be “wrapped” in a synchronized list.
Return Value: This method returns a synchronized view of the specified list.
Below are the examples to illustrate the synchronizedList() method
Example 1:
// Java program to demonstrate// synchronizedList() method for String Value  import java.util.*;  public class GFG1 {    public static void main(String[] argv) throws Exception    {        try {              // creating object of List<String>            List<String> list = new ArrayList<String>();              // populate the list            list.add("A");            list.add("B");            list.add("C");            list.add("D");            list.add("E");              // printing the Collection            System.out.println("List : " + list);              // create a synchronized list            List<String> synlist = Collections                                       .synchronizedList(list);              // printing the Collection            System.out.println("Synchronized list is : " + synlist);        }          catch (IllegalArgumentException e) {            System.out.println("Exception thrown : " + e);        }    }}
List : [A, B, C, D, E]
Synchronized list is : [A, B, C, D, E]

Example 2:
// Java program to demonstrate// synchronizedList() method for Integer Value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          try {              // creating object of List<Integer>            List<Integer> list = new ArrayList<Integer>();              // populate the list            list.add(20);            list.add(30);            list.add(40);            list.add(50);            list.add(60);              // printing the Collection            System.out.println("List : " + list);              // create a synchronized list            List<Integer> synlist = Collections                                        .synchronizedList(list);              // printing the Collection            System.out.println("Synchronized list is : " + synlist);        }          catch (IllegalArgumentException e) {            System.out.println("Exception thrown : " + e);        }    }}
List : [20, 30, 40, 50, 60]
Synchronized list is : [20, 30, 40, 50, 60]

Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
How to Convert string to integer type in Golang?

14 Sep, 2021
Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can use the following methods.
1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int.
Syntax: 
func Atoi(s string) (int, error)
Example: 
Go
// Go program to illustrate how to// Convert string to the integer type package main import (    "fmt"    "strconv") func main() {     str1 := "123"     // using ParseInt method    int1, err := strconv.ParseInt(str1, 6, 12)     fmt.Println(int1)     // If the input string contains the integer    // greater than base, get the zero value in return    str2 := "123"     int2, err := strconv.ParseInt(str2, 2, 32)    fmt.Println(int2, err) }
Output: 
123
0 strconv.Atoi: parsing "12.3": invalid syntax
2. ParseInt() Function: The ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
Syntax:  
func ParseInt(s string, base int, bitSize int) (i int64, err error)
Example: 
Go
// Go program to illustrate how to// Convert string to the integer type package main import (    "fmt"    "strconv") func main() {     str1 := "123"     // using ParseInt method    int1, err := strconv.ParseInt(str1, 6, 12)     fmt.Println(int1)     // If the input string contains the integer    // greater than base, get the zero value in return    str2 := "123"     int2, err := strconv.ParseInt(str2, 2, 32)    fmt.Println(int2, err) }
Output: 
51
0 strconv.ParseInt: parsing "123": invalid syntax
 
anikakapoor
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Maximum Sum Record - GeeksforGeeks

30 Jan, 2020
Sometimes, while working with data, we might have a problem in which we need to find maximum sum between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using max() + list comprehensionThe combination of this functions can be used to perform this task. In this, we compute the sum of all pairs and then return the max of it using max().
# Python3 code to demonstrate working of# Maximum Sum Record# Using list comprehension + max()  # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)]  # printing original list print("The original list : " + str(test_list))  # Maximum Sum Record# Using list comprehension + max()temp = [b + a for a, b in test_list]res = max(temp)  # printing resultprint("Maximum sum among pairs : " + str(res))
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Maximum sum among pairs : 13

 
Method #2 : Using max() + lambdaThis is similar to above method. In this the task performed by list comprehension is solved using lambda function, providing the sum computation logic. Returns the max. sum pair.
# Python3 code to demonstrate working of# Maximum Sum Record# Using lambda + max()  # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)]  # printing original list print("The original list : " + str(test_list))  # Maximum Sum Record# Using lambda + max()res = max(test_list, key = lambda sub: sub[1] + sub[0])  # printing resultprint("Maximum sum among pairs : " + str(res))
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Maximum sum among pairs : 13

Python list-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
BigInteger abs() Method in Java - GeeksforGeeks

20 May, 2019
prerequisite : BigInteger Basics
The java.math.BigInteger.abs() method returns absolute value of a BigInteger. By using this method one can find absolute value of any large size of numerical data stored as BigInteger.
Syntax:
public BigInteger abs()
Parameters: The method does not take any parameters.
Return Value: The method returns the absolute value of a BigInteger.
Examples:
Input: -2300 
Output: 2300
Explanation:
Applying mathematical abs() operation on 
-2300, positive 2300 is obtained i.e |-2300| = 2300. 

Input: -5482549 
Output: 5482549

Below program illustrates abs() method of BigInteger:
// Below program illustrates the abs() method// of BigInteger   import java.math.*;  public class GFG {  public static void main(String[] args) {          // Create BigInteger object        BigInteger biginteger=new BigInteger("-2300");                  // abs() method on bigInteger to find the absolute value        // of a BigInteger        BigInteger absolutevalue= biginteger.abs();                      // Define result        String result ="BigInteger "+biginteger+            " and Absolute value is "+absolutevalue;        // Print result         System.out.println(result);          }}
BigInteger -2300 and Absolute value is 2300

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs()
Akanksha_Rai
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
Tryit Editor v3.7

Tryit: Styling lists with colors
MySQL CREATE USER with a variable?

You can use a dynamic query for this. First set the variable name for username and variable name for a password. The syntax is as follows −
SET @anyVariableName=’yourUserName’;
SET @anyVariableName1=’yourpassword’;
Now you can use the CONCAT() function from MySQL. The syntax is as follows −
SET @yourQueryName = CONCAT
('
   CREATE USER "',@anyVariableName,'"@"localhost" IDENTIFIED BY "',@anyVariableName1,'" '
);
Let us use the prepared statement PREPARE. The syntax is as follows −
PREPARE yourStatementVariableName FROM @yourQueryName;
Now you can execute the statement. The syntax is as follows −
EXECUTE yourStatementVariableName;
Deallocate the above using the DEALLOCATE PREPARE. The syntax is as follows −
DEALLOCATE PREPARE yourStatementVariableName;
To understand the above syntax, let us follows all the steps −
Step 1 − First create two variables, one for username and second for a password using SET command.
the query is as follows to create a username −
mysql> set @UserName:='John Doe';
Query OK, 0 rows affected (0.00 sec)
The query to create a password.
mysql> set @Password:='John Doe 123456';
Query OK, 0 rows affected (0.00 sec)
Step 2 − Now use the CONCAT() function to create a user. The query is as follows −
mysql> SET @CreationOfUser = CONCAT('
   '> CREATE USER "',@UserName,'"@"localhost" IDENTIFIED BY "',@Password,'" '
   -> );
Query OK, 0 rows affected (0.02 sec)
In the above query, we have used @UserName variable name and @Password variable name to create a user with name and password.
Step 3 − Now you need to prepare the statement using the above user-defined variable @CreationOfUser. The query is as follows −
mysql> PREPARE st FROM @CreationOfUser;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
Step 4 − Execute the above-prepared statement. The query is as follows −
mysql> EXECUTE st;
Query OK, 0 rows affected (0.37 sec)
Step 5 − Check the user “John Doe” has been created in the MySQL.user table −
mysql> select user,host from MySQL.user;
The following is the output −
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| Manish           | %         |
| User2            | %         |
| mysql.infoschema | %         |
| mysql.session    | %         |
| mysql.sys        | %         |
| root             | %         |
| @UserName@       | localhost |
| Adam Smith       | localhost |
| John             | localhost |
| John Doe         | localhost |
| User1            | localhost |
| am               | localhost |
| hbstudent        | localhost |
+------------------+-----------+
13 rows in set (0.00 sec)
Yes, we have a username with John Doe.
Step 6 − Now, DEALLOCATE the prepared statement. The query is as follows −
mysql> DEALLOCATE PREPARE st;
Query OK, 0 rows affected (0.00 sec)
C++ Library - <unordered_set>

It is an associative container that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value.
Below is definition of std::unordered_set
template < class Key,                        
           class Hash = hash<Key>,        
           class Pred = equal_to<Key>,    
           class Alloc = allocator<Key>   
           > class unordered_set;
Key − It defines the type of element.
Key − It defines the type of element.
Hash − It is a unary function object.
Hash − It is a unary function object.
Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool.
Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool.
Alloc − It defines the type of allowcater.
Alloc − It defines the type of allowcater.
Following member types can be used as parameters or return type by member functions.
Below is list of member functions
It constructs unordered_set.
It destroys unordered_set.
It is used to assign the content.
It is used to test whether container is empty.
It returns container size.
It returns maximum size.
It returns iterator to beginning.
It returns iterator to end.
It returns const_iterator to beginning.
It return const_iterator to end.
It is used to get iterator to element.
It is used to count elements with a specific key.
It is used to get range of elements with a specific key.
It is used to construct and insert element.
It is used to construct and insert element with hint.
It is used to insert elements.
It is used to erase elements.
It is used to clear content.
It is used to swap content.
It returns number of buckets.
It returns maximum number of buckets.
It returns bucket size.
It locates element's bucket.
It returns load factor.
It is used to get or set maximum load factor.
It is used to set number of buckets.
It gives a request to capacity chage of backets
It is used to get hash function.
It is used to get key equivalence predicate.
It is used to get allocator.
It is used to get hash function.
It exchanges contents of two unordered_set containers.
It is used to get hash function.
It exchanges contents of two unordered_set containers.
 Print
 Add Notes
 Bookmark this page
C# program to create an empty string array

To create an empty string array −
string[] str = new string[] {};
Above, we haven’t added elements to the array, since it is empty.
Even if we will loop though the array, it won’t display anything as shown below −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      string[] str = new string[] {};
      Console.WriteLine("String Array elements won't get displayed since it's empty...");
      for (int i = 0; i < str.Length; i++) {
         string res = str[i];
         Console.WriteLine(res);
      }
   }
}
String Array elements won't get displayed since it's empty...
What is the difference between single-line and multi-line comments in JavaScript?

Single Line comment
The following is a single line comment in JavaScript. Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
// This is a comment. It is similar to comments in C++
Multi-Line comment
The following is a multi-line comment in JavaScript.
/*
   * This is a multiline comment in JavaScript
   * It is very similar to comments in C Programming
*/
How to generate pyramid of numbers using Python?

There are multiple variations of generating pyramids using numbers in Python. Let's look at the 2 simplest forms
for i in range(5):
   for j in range(i + 1):
      print(j + 1, end="")
   print("")
This will give the output
1
12
123
1234
12345
You can also print numbers continuously using
start = 1
for i in range(5):
   for j in range(i + 1):
      print(start, end=" ")
      start += 1
print("")
This will give the output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
You can also print these numbers in reverse using
start = 15
for i in range(5):
   for j in range(i + 1):
   print(start, end=" ")
   start -= 1
print("")
This will give the output
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
How to assign same value to multiple variables in single statement in C#?

To assign same value to multiple variables in a single line, use the = operator −
val1 = val2 = 20;
The above statement assigns 20 to the variables val1 and val2 as shown in the following code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int val1, val2;
         val1 = val2 = 20;
         Console.WriteLine("Value1 = "+val1);
         Console.WriteLine("Value2 = "+val2);
      }
   }
}
Value1 = 20
Value2 = 20
Virtual Functions in C++ - GeeksQuiz

10 Jul, 2021
In Base 
In Base 
In Base 
In Derived
In Derived
In Derived
In Derived
In Base 
In Base 
In Base 

In Base 
In Derived

In Derived
In Derived

In Derived
In Base 

// Not good code as destructor is not virtual
#include<iostream>
using namespace std;

class Base  {
public:
    Base()    { cout << "Constructor: Base" << endl; }
    ~Base()   { cout << "Destructor : Base" << endl; }
};

class Derived: public Base {
public:
    Derived()   { cout << "Constructor: Derived" << endl; }
    ~Derived()   { cout << "Destructor : Derived" << endl; }
};

int main()  {
    Base *Var = new Derived();
    delete Var;
    return 0;
}

Output on GCC:
Constructor: Base
Constructor: Derived
Destructor : Base

Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base
Constructor: Base
Constructor: Derived
Destructor : Base
Constructor: Base
Constructor: Derived
Destructor : Derived
Constructor: Derived
Destructor : Derived
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?