code-rag-bench/online-tutorials huggingface dataset:
Python – Type conversion in Nested and Mixed List

08 Jun, 2020
While working with Python lists, due to its heterogenous nature, we can have a problem in which we need to convert data type of each nested element of list to particular type. In mixed list, this becomes complex. Let’s discuss certain way in which this task can be performed.
Input : test_list = [(‘7’, [‘8’, (‘5’, )])]Output : [(7, [8, (5, )])]
Input : test_list = [‘6’]Output : [6]
Method : Using recursion + isinstance()The combination of above functions can be used to solve this problem. In this, we use isinstance() to get the data type of element of list, and if its container, the inner elements are recursed to perform conversion.
# Python3 code to demonstrate working of # Type conversion in Nested and Mixed List# Using recursion + isinstance()  # helper_fncdef change_type(sub):    if isinstance(sub, list):        return [change_type(ele) for ele in sub]    elif isinstance(sub, tuple):        return tuple(change_type(ele) for ele in sub)    else:        return int(sub)          # initializing listtest_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]  # printing original listprint("The original list is : " + str(test_list))  # Type conversion in Nested and Mixed List# Using recursion + isinstance()res = change_type(test_list)  # printing result print("Data after type conversion : " + str(res)) 
The original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, (7, [8, 10]), [11, 15]]

Python list-programs
Python
Python Programs
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
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 | Convert string dictionary to dictionary
Java program to print the initials of a name with last name in full

When the full name is provided, the initials of the name are printed with the last name is printed in full. An example of this is given as follows −
Full name = Amy Thomas
Initials with surname is = A. Thomas
A program that demonstrates this is given as follows −
 Live Demo
import java.util.*;
public class Example {
   public static void main(String[] args) {
      String name = "John Matthew Adams";
      System.out.println("The full name is: " + name);
      System.out.print("Initials with surname is: ");
      int len = name.length();
      name = name.trim();
      String str1 = "";
      for (int i = 0; i < len; i++) {
         char ch = name.charAt(i);
         if (ch != ' ') {
            str1 = str1 + ch;
         } else {
            System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
            str1 = "";
         }
      }
      String str2 = "";
      for (int j = 0; j < str1.length(); j++) {
         if (j == 0)
            str2 = str2 + Character.toUpperCase(str1.charAt(0));
         else
            str2 = str2 + Character.toLowerCase(str1.charAt(j));
      }
      System.out.println(str2);
   }
}
The full name is: John Matthew Adams
Initials with surname is: J. M. Adams
Now let us understand the above program.
The name is printed. Then the first letter of the name is printed i.e. the initials. The code snippet that demonstrates this is given as follows −
String name = "John Matthew Adams";
System.out.println("The full name is: " + name);
System.out.print("Initials with surname is: ");
int len = name.length();
name = name.trim();
String str1 = "";
for (int i = 0; i < len; i++) {
   char ch = name.charAt(i);
   if (ch != ' ') {
      str1 = str1 + ch;
   } else {
      System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
      str1 = "";
   }
}
Then, the entire surname of the name is printed. The code snippet that demonstrates this is given as follows −
String str2 = "";
for (int j = 0; j < str1.length(); j++) {
   if (j == 0)
      str2 = str2 + Character.toUpperCase(str1.charAt(0));
   else
      str2 = str2 + Character.toLowerCase(str1.charAt(j));
}
System.out.println(str2);
float() in Python

Float method is part of python standard library which converts a number or a string containing numbers to a float data type. There are following rules when a string is considered to be valid for converting it to a float.
The string must have only numbers in it.
The string must have only numbers in it.
Mathematical operators between the numbers can also be used.
Mathematical operators between the numbers can also be used.
The string can represent NaN or inf
The string can represent NaN or inf
The white spaces at the beginning and end are always ignored.
The white spaces at the beginning and end are always ignored.
The below program indicates how different values are returned when float function is applied.
n = 89
print(type(n))
f = float(n)
print(type(f))
print("input",7," with float function becomes ",float(7))
print("input",-21.6," with float function becomes ",float(-21.6))
print("input NaN, with float function becomes ",float("NaN"))
print("input InF, with float function becomes ",float("InF"))
Running the above code gives us the following result −
<class 'int'>
<class 'float'>
input 7 with float function becomes 7.0
input -21.6 with float function becomes -21.6
input NaN, with float function becomes nan
input InF, with float function becomes inf
Passing a stream without having any numeric values throws error.
print("input Tutorials, with float function becomes ",float("Tutorials"))
Running the above code gives us the following result −
Traceback (most recent call last):
   File "C:/xxx.py", line 18, in
      print("input Tutorials, with float function becomes ",float("Tutorials"))
ValueError: could not convert string to float: 'Tutorials'
Case Function in Tableau

22 Oct, 2020
In this article, we will learn about aggregate functions, their types and uses in Tableau.
Tableau: Tableau is a very powerful data visualization tool that can be used by data analysts, scientists, statisticians, etc. to visualize the data and get a clear opinion based on the data analysis. Tableau is very famous as it can take in data and produce the required data visualization output in a very short time.
Case Function: Case Function is the part of Logical functions in Tableau. These functions are used to perform the logical test and return the required value when the test expression is true.
It starts with CASE function evaluating the 1st logical expression corresponding to set/sequence of values and when the logical expression becomes True, it returns the respective specified value as result.
If no match is found in logical expression then the value of default return expression is used.
In case no default value is being mentioned by the user then NULL is returned.
This function finds the first that matches the given <expression> and returns the corresponding value as a result.
CASE [<expression>]
    WHEN <expression> THEN <expression>
    WHEN <expression> THEN <expression>
    ELSE <expression>
END

Dataset used in the given examples is Dataset.
In this example, we simply create a new calculated field by using the CASE function on some fields.
View new calculated field.
Use in Visualization.
CASE-WHEN statements are easier to write down and comprehend.
Due to its simplicity, for a user, it’s helpful to avoid making mistakes like referencing the incorrect field.
CASE-WHEN statements perform faster than IF-ELSE statements.
Usage of CASE-WHEN in Tableau is extremely limited as they can’t perform Boolean logic conditions.
CASE-WHEN in tableau only compares the expression to the precise values.
Conditional operators like OR, AND can’t be used with CASE-WHEN.
Using CASE-WHEN, multiple expressions can’t be evaluated during a single line.
Tableau
Tableau
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Word Cloud in Tableau
IF Function in Tableau
Funnel Chart in Tableau
Box Plot in Tableau
Tableau - Data Terminology
Tableau Installation Guide
Combined Set in Tableau
Start Page in Tableau
Image Object on Dashboard in Tableau
Quick Table Calculation in Tableau
Puzzle 12 | (Maximize probability of White Ball)

22 Jul, 2021
There are two empty bowls in a room. You have 50 white balls and 50 black balls. After you place the balls in the bowls, a random ball will be picked from a random bowl. Distribute the balls (all of them) into the bowls to maximize the chance of picking a white ball. 
      
Explanation: First, let us assume that we divided the balls into jars equally so each jar will contain 50 balls. So the probability of selecting a white ball will be = probability of selecting the first jar*probability of white ball in the first jar + probability of selecting the second jar*probability of white ball in the second jar =(1/2)*(25/50)+(1/2)*(25/50)=0.5Since we have to maximize the probability so we will increase the probability of white ball in the first jar and keep the second probability same mean equal to 1 so we add 49 white balls with 50 black balls in the first jar and only one white ball in the second jar so the probability will be now=  
(1/2)*(49/99)+(1/2)*(1/1)=0.747
Therefore, probability of getting white ball becomes 1/2*1 + 1/2*49/99 which is approximately 3/4. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above  
Maximize probability of White Ball | Puzzle - YouTubeGeeksforGeeks School18.5K subscribersMaximize probability of White Ball | PuzzleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rul79-fYVnw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
puneet chamria
srijanchandra26
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)
set::size() in C++ STL

22 Jan, 2018
Sets are containers that store unique elements following a specific order. Internally, the elements in a set are always sorted. Sets are typically implemented as binary search trees.
set::size()size() function is used to return the size of the set container or the number of elements in the set container.
Syntax:
set_name.size()

Return Value: It returns the number of elements in the set container.
Examples:
Input  : set1{'a', 'b', 'c', 'd'};
         set1.size();
Output : 4

Input  : set2{};
         set2.size();
Output : 0

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// C++ program to illustrate// size() function on set#include <bits/stdc++.h>using namespace std;  int main(){    // Take any two sets    set<char> set1, set2;    for (int i = 0; i < 4; i++) {        set1.insert('a' + i);    }      // Printing the size of sets    cout << "set1 size: " << set1.size();    cout << endl;    cout << "set2 size: " << set2.size();    return 0;}
Output:
set1 size: 4
set2 size: 0

Time complexity: Constant
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
C++ Classes and Objects
Object Oriented Programming in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
How to change the text color of an element in HTML?

Use the color attribute in HTML to display the color of the text.
Note − This attribute is not supported in HTML5.
You can try to run the following code to learn how to implement color attribute in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Background Colors</title>
   </head>
   <body>
      <table width = "100%">
         <tr>
            <td>
               <p><font color="blue">This is demo text.</font></p>
            </td>
         </tr>
      </table>
   </body>
</html>
Enumerated Types or Enums in C++

16 Mar, 2022
Enumerated type (enumeration) is a user-defined data type which can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type.
If we assign a float value in a character value, then the compiler generates an error. In the same way if we try to assign any other value to the enumerated data types, the compiler generates an error. Enumerator types of values are also known as enumerators. It is also assigned by zero the same as the array. It can also be used with switch statements.For example: If a gender variable is created with value male or female. If any other value is assigned other than male or female then it is not appropriate. In this situation, one can declare the enumerated type in which only male and female values are assigned.
Syntax:
enum enumerated-type-name{value1, value2, value3.....valueN};
enum keyword is used to declare enumerated types after that enumerated type name was written then under curly brackets possible values are defined. After defining Enumerated type variables are created. It can be created in two types:-
It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or,Beside this, we can create enumerated type variables as same as the normal variables. 
It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or,
Beside this, we can create enumerated type variables as same as the normal variables. 
enumerated-type-name variable-name = value;
By default, the starting code value of the first element of enum is 0 (as in the case of array) . But it can be changed explicitly.
For example: enum enumerated-type-name{value1=1, value2, value3};
And, The consecutive values of the enum will have the next set of code value(s).
For example:
//first_enum is the enumerated-type-name
enum first_enum{value1=1, value2=10, value3};

In this case, 
first_enum e;
e=value3;
cout<<e;

Output:
11
Example 1: 
CPP
#include <bits/stdc++.h>using namespace std; int main(){    // Defining enum Gender    enum Gender { Male, Female };     // Creating Gender type variable    Gender gender = Male;     switch (gender)    {    case Male:        cout << "Gender is Male";        break;    case Female:        cout << "Gender is Female";        break;    default:        cout << "Value can be Male or Female";    }    return 0;}
Gender is Male
 
Example 2: 
CPP
#include <bits/stdc++.h>using namespace std; // Defining enum Yearenum year {    Jan,    Feb,    Mar,    Apr,    May,    Jun,    Jul,    Aug,    Sep,    Oct,    Nov,    Dec}; // Driver Codeint main(){    int i;     // Traversing the year enum    for (i = Jan; i <= Dec; i++)        cout << i << " ";     return 0;}
0 1 2 3 4 5 6 7 8 9 10 11
 
ojhashashank41
cmaggio
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Gnome Sort

22 Jun, 2022
Algorithm Steps:
If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
If the current array element is larger or equal to the previous array element then go one step right
                   if (arr[i] >= arr[i-1])
                      i++;
If the current array element is smaller than the previous array element then swap these two elements and go one step backwards 
                       if (arr[i] < arr[i-1])
                       {
                           swap(arr[i], arr[i-1]);
                           i--;
                       }
Repeat steps 2) and 3) till ‘i’ reaches the end of the array (i.e- ‘n-1’)
If the end of the array is reached then stop and the array is sorted.
Python
# Python program to implement Gnome Sort # A function to sort the given list using Gnome sortdef gnomeSort( arr, n):    index = 0    while index < n:        if index == 0:            index = index + 1        if arr[index] >= arr[index - 1]:            index = index + 1        else:            arr[index], arr[index-1] = arr[index-1], arr[index]            index = index - 1     return arr # Driver Codearr = [ 34, 2, 10, -9]n = len(arr) arr = gnomeSort(arr, n)print "Sorted sequence after applying Gnome Sort :",for i in arr:    print i, # Contributed By Harshit Agrawal
Sorted sequence after applying Gnome Sort : -9 2 10 34
Time Complexity: O(n2)
Auxiliary Space: O(1)Please refer complete article on Gnome Sort for more details! 
surindertarika1234
chandramauliguptach
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DNSRecon – A powerful DNS enumeration script

14 Sep, 2021
DNSRecon is a free and open-source tool or script that is available on GitHub. Dnsrecon is one of the popular scripts in the security community which is used for reconnaissance on domains. This script is written in python language. You must have python language installed in your kali Linux operating system in order to use the script. 
This script checks all the DNS records for AXFR which can be useful for a security researcher for DNS enumeration on all types of records such as SOA, NS, TXT, SVR, SPF, etc. This script also used Google dorks for fetching indexed subdomains by Googlebot.
Step 1: Open your kali Linux operating system and use the following command to install the tool.
git clone https://github.com/darkoperator/dnsrecon.git
Step 2: Now use the following command to move into the directory of the tool.
cd dnsrecon
Step 3: Now use the following command to install the dependencies of the tool.
pip3 install -r requirements.txt --no-warn-script-location
Step 4: Now use the following command to run the tool.
python3 dnsrecon.py -h
The tool has been installed and running successfully. Now we will see examples to use the tool.
Example 1: Use dnsrecon for Base domain enumeration.
python3 dnsrecon.py -d <domain>
Example 2:  Use dnsrecon for zonewalk.
python3 dnsrecon.py -d <domain>-t zonewalk
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
Introduction to Linux Operating System
chown command in Linux with Examples
chmod command in Linux with examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
How to Permanently Disable Swap in Linux?
mv command in Linux with examples
Difference between textContent and innerHTML

17 Dec, 2020
The textContent and innerHTML are properties of JavaScript. However, there are differences in the way the specified text is handled in JavaScript. Let us take a look at the syntax of both these properties.
Syntax:
Let elem be a JavaScript variable that holds an element that is selected from the page.
let elem = document.getElementById('test-btn');
The textContent and innerHTML properties can be used as follows:
The textContent property: This property is used to get or set the text content of the specified node and its descendants.elem.textContent
elem.textContent
The innerHTML property: This property is used to get or set the HTML content of an element.elem.innerHTML
elem.innerHTML
HTML
<!DOCTYPE html><html>  <body style="text-align:center;">    <h1 style="color:#006600">        GeeksforGeeks    </h1>      <div id="test-btn">        The following element contains some        <bold>bold</bold> and        some <italic>italic text</italic>.    </div>      <p></p>      <button onClick="innerHTMLfn()">        innerHTML    </button>      <button onClick="textContentfn()">        textContent    </button>          <p id="demo-para"></p>      <script>        function textContentfn() {            var elem =                document.getElementById('test-btn');            alert(elem.textContent);        }          function innerHTMLfn() {            var elem =                document.getElementById('test-btn');            alert(elem.innerHTML);        }     </script></body>  </html>
Output:
Before any button is clicked:
After the innerHTML button is clicked:
After the textContent button is clicked:
Differences: As we can see from the example above, the innerHTML property gets or sets HTML contents of the element. The textContent does not automatically encode and decode text and hence allows us to work with only the content part of the element.
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Triple quote String concatenation

22 Jun, 2020
Sometimes, while working with Python Strings, we can have problem in which we need to perform concatenation of Strings which are constructed by Triple quotes. This happens in cases we have multiline strings. This can have applications in many domains. Lets discuss certain way in which this task can be performed.
Input : test_str1 = """mango
is"""
test_str2 = """good
for health
"""
Output : mango good
 is for health

Input : test_str1 = """Gold
is"""
test_str2 = """important
for economy
"""
Output : Gold important
 is for economy

Method : Using splitlines() + strip() + join()The combination of above functions can be used to perform this task. In this, we perform the ask of line splitting using splitlines(). The task of concatenation is done using strip() and join().
# Python3 code to demonstrate working of # Triple quote String concatenation# Using splitlines() + join() + strip()  # initializing stringstest_str1 = """gfgis"""test_str2 = """bestfor geeks"""  # printing original stringsprint("The original string 1 is : " + test_str1)print("The original string 2 is : " + test_str2)  # Triple quote String concatenation# Using splitlines() + join() + strip()test_str1 = test_str1.splitlines()test_str2 = test_str2.splitlines()res = []  for i, j in zip(test_str1, test_str2):    res.append("   " + i.strip() + " " + j.strip())res = '\n'.join(res)  # printing result print("String after concatenation : " + str(res)) 
The original string 1 is : gfg
is
The original string 2 is : best
for geeks

String after concatenation :    gfg best
   is for geeks

 
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Emotion classification using NRC Lexicon in Python

03 Sep, 2021
Many a time, for real-world projects, emotion recognition is often just the start of the project. That time writing a whole code on that will not only increase time but also efficiency is hindered. 
NRCLexicon is an MIT-approved pypi project by Mark M. Bailey which predicts the sentiments and emotion of a given text. The package contains approximately 27,000 words and is based on the National Research Council Canada (NRC) affect lexicon and the NLTK library’s WordNet synonym sets.
To install this module type the below command in the terminal. 
pip install NRCLex
Even after the installation of this module, MissingCorpusError may occur while running programs. So it is advised to also install textblob.download_corpora by using the below command on the command prompt. 
python -m textblob.download_corpora
Approach: 
Import the module
Python3
# Import required modulesfrom nrclex import NRCLex
Assign input text
Python3
# Assigning list of wordstext = ['hate', 'lovely', 'person', 'worst']
Create NRCLex object for each input text.
Python3
for i in range(len(text)):       # creating objects    emotion = NRCLex(text[i])
Apply methods to classify emotions.
Emotional affects measured include the following:
fearangeranticipationtrustsurprisepositivenegativesadnessdisgustjoy
fear
anger
anticipation
trust
surprise
positive
negative
sadness
disgust
joy
Below is the Implementation.
Example 1:
Based on the above approach, the below example classifies various emotions using top_emotions.
Python3
# Import modulefrom nrclex import NRCLex # Assign list of stringstext = ['hate', 'lovely', 'person', 'worst'] # Iterate through listfor i in range(len(text)):     # Create object    emotion = NRCLex(text[i])     # Classify emotion    print('\n\n', text[i], ': ', emotion.top_emotions)
Output:
Example 2:
Here a single emotion love is classified using all the methods of NCRLex module.
Python3
# Import modulefrom nrclex import NRCLex # Assign emotiontext = 'love' # Create objectemotion = NRCLex(text) # Using methods to classigy emotionprint('\n', emotion.words)print('\n', emotion.sentences)print('\n', emotion.affect_list)print('\n', emotion.affect_dict)print('\n', emotion.raw_emotion_scores)print('\n', emotion.top_emotions)print('\n', emotion.affect_frequencies)
Output:
sagartomar9927
Natural-language-processing
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Moment.js moment().format() Function

29 Jul, 2020
The moment().format() function is used to format the date according to the user need. The format can be provided in string form which is passed as a parameter to this function.
Syntax:
moment().format(String);
Parameters: This function accept single parameter of string type, which defines the format.
Return Value: This function returns the date.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below.
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1: Filename: index.js
// Requiring the moduleconst moment = require('moment');   // The format() function to format the date var formatedDate = moment().format(    "dddd, MMMM Do YYYY, h:mm:ss a");console.log(formatedDate);
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Friday, July 17th 2020, 4:28:30 pm

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Friday, July 17th 2020, 4:28:30 pm

node index.js
Output:
Friday, July 17th 2020, 4:28:30 pm

Example 2: Filename: index.js
// Requiring the moduleconst moment = require('moment');   function format_Date(date){   return moment().format("dddd, MMMM Do YYYY");}   var result = format_Date(moment);console.log("Result:", result);
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Result: Friday, July 17th 2020

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Result: Friday, July 17th 2020

node index.js
Output:
Result: Friday, July 17th 2020

Reference: https://momentjs.com/docs/#/displaying/format/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comparing Path of Two Files in Java

26 Oct, 2020
The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program.
To compare the path of the file, compareTo() method of File Class is used. compareTo() method compares two abstract path-names lexicographically. The ordering defined by this method is dependent upon the operating system.
Parameters: This method requires a single parameter i.e.the abstract pathname that is to be compared. 
Return Value: This method returns 0 if the argument is equal to this abstract pathname, a negative value if the abstract pathname is lexicographically less than the argument, and a value greater than 0 if the abstract pathname is lexicographically greater than the argument respectively.
Example:
Java
// Comparing path of two files in Java  import java.io.File;  public class GFG {        public static void main(String[] args)    {          File file1 = new File("/home/mayur/GFG.java");        File file2 = new File("/home/mayur/file.txt");        File file3 = new File("/home/mayur/GFG.java");          // Path comparision        if (file1.compareTo(file2) == 0) {            System.out.println(                "paths of file1 and file2 are same");        }        else {            System.out.println(                "Paths of file1 and file2 are not same");        }          // Path comparision        if (file1.compareTo(file3) == 0) {            System.out.println(                "paths of file1 and file3 are same");        }        else {            System.out.println(                "Paths of file1 and file3 are not same");        }    }}
Output:
Java-Files
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 15

28 Jun, 2021
Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node is not given, can we delete the node X from given linked list?(A) Possible if X is not last node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X.(B) Possible if size of linked list is even.(C) Possible if size of linked list is odd(D) Possible if X is not first node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X.Answer: (A)Explanation: Following are simple steps.
    struct node *temp  = X->next;
    X->data  = temp->data;
    X->next  = temp->next;
    free(temp); 
Quiz of this Question
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Hash | Question 5
Data Structures | Binary Trees | Question 1
Data Structures | Misc | Question 9
Data Structures | Queue | Question 11
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Advantages of vector over array in C++
Node.js Callback Concept

13 Oct, 2021
A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable. For example: In Node.js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.
Example 1: Code for reading a file synchronously (blocking code) in Node.js. Create a text file inputfile1.txt with the following content:
Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
Create a sync.js file with the following code:
// Write JavaScript codevar fs = require("fs");var filedata = fs.readFileSync('inputfile1.txt');console.log(filedata.toString());console.log("End of Program execution");
Explanation: fs library is loaded to handle file-system related operations. The readFileSync() function is synchronous and blocks execution until finished. The function blocks the program until it reads the file and then only it proceeds to end the programOutput:
Example 2: Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file inputfile1.txt with the following content.
Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
Create a async.js file with the following code:
// Write a JavaScript codevar fs = require("fs");      fs.readFile('inputfile1.txt', function (ferr, filedata) {      if (ferr) return console.error(ferr);      console.log(filedata.toString());  }); console.log("End of Program execution");  
Explanation: fs library is loaded to handle file-system related operations. The readFile() function is asynchronous and control return immediately to the next instruction in the program while the function keep running in the background. A callback function is passed which gets called when the task running in the background are finished.Output:
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
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 ?
Differences between Functional Components and Class Components in React
HTTP headers | Authorization

11 May, 2020
The HTTP headers Authorization header is a request type header that used to contains the credentials information to authenticate a user through a server. If the server responds with 401 Unauthorized and the WWW-Authenticate header not usually.
Syntax:
Authorization: <type> <credentials>
Directives: This header accept two directive as mentioned above and described below:
<type>: This directive holds the authentication type the default type is Basic and the other types are IANA registry of Authentication schemes and Authentication for AWS servers (AWS4-HMAC-SHA256).
<credentials>: This directive is totally depends on the type of authentication if the authentication is Basic then the credentials are struct with Username and Password combine with a colon like “Username:Password” and the resulted string is base64 encoded.
Example:
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
Supported browsers: The browsers compatible with HTTP headers Authorization are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
multimap find() in C++ STL

01 Jul, 2021
multimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In case of multiple same keys being present, the iterator that refers to one of the keys (typically the first one). In case we wish to get all the items with a given key, we may use equal_range(). If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end(). Syntax:  
iterator multimap_name.find(key)
        or 
constant iterator multimap_name.find(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be searched in the multimap container. Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the multimap. If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end().  
CPP
// C++ program for illustration// of multimap::find() function#include <bits/stdc++.h>using namespace std; int main(){     // initialize container    multimap<int, int> mp;     // insert elements in random order    mp.insert({ 2, 30 });    mp.insert({ 1, 40 });    mp.insert({ 2, 60 });    mp.insert({ 3, 20 });    mp.insert({ 1, 50 });    mp.insert({ 4, 50 });     cout << "The elements from position 3 in multimap are : \n";    cout << "KEY\tELEMENT\n";     // find() function finds the position at which 3 is    for (auto itr = mp.find(3); itr != mp.end(); itr++)        cout << itr->first             << '\t' << itr->second << '\n';     return 0;}
The elements from position 3 in multimap are : 
KEY    ELEMENT
3    20
4    50
 
himanshu raj
lucaopensource
CPP-Functions
cpp-multimap
cpp-multimap-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
Inheritance in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Python PIL | Image.seek() Method

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.seek() Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
Syntax: Image.seek(frame)
Parameters:frame – Frame number, starting at 0.
Raises: EOFError – If the call attempts to seek beyond the end of the sequence.
Image Used:
     # importing image class from PIL packagefrom PIL import Image  # creating gif image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\time.gif")img1 = img.tell()print(img1)  # using seek() methodimg2 = img.seek(img.tell() + 1)img3 = img.tell()print(img3)img.show()
Output:
0
1


Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Formatting Unordered and Ordered Lists in CSS

The style and position of unordered and ordered lists can be formatted by CSS properties with list-style-type, list-style-image and list-style-position.
The syntax of CSS list-style property is as follows −
Selector {
   list-style: /*value*/
}
The following examples illustrate CSS list-style property −
The following example styles ordered list −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ol {
   list-style: upper-roman;
   line-height: 150%;
}
</style>
</head>
<body>
<h2>Latest C# Versions</h2>
<ol>
<li>C# 8.0</li>
<li>C# 7.3</li>
<li>C# 7.2</li>
<li>C# 7.1</li>
<li>C# 7.0</li>
</ol>
</body>
</html>
This gives the following output −
The following example styles unordered list −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul > ul{
   list-style: circle inside;
}
li:last-child {
   list-style-type: square;
}
</style>
</head>
<body>
<h2>Programming Languages</h2>
<ul>
<li>C++ programming language created by Bjarne Stroustrup as an extension of the C programming language.</li>
<li>Java programming language developed by James Gosling.</li>
<ul>
<li>Core Java</li>
<li>Advanced Java</li>
</ul>
<li>Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way.</li>
</ul>
</body>
</html>
This gives the following output −
How do you run your own code alongside Tkinter's event loop?

Tkinter is widely used to create and develop GUI based applications and games.
Tkinter provides its window or frame where we execute our programs and functions
along with other attributes.
Let us consider that we are working with a particular application and we want to
write the changes in the code while running the application. Tkinter provides a
callback method which can be used to run the window while iterating over it. We
can keep running the window using the after(duration,task) method that will basically run the changes after a duration.
In this example, we will create a window which prints the numbers in the range (0
to 9) whilst running the main window or frame.
#Import the required libraries
from tkinter import *
from tkinter import messagebox
#Create an instance of tkinter frame or window
win= Tk()

#Set the geometry
win.geometry("700x200")

#Define the function for button
def some_task():
   for i in range(10):
      print(i)

      #Recursively call the function
      win.after(2000, some_task)

#Keep Running the window
win.after(2000, some_task)
win.mainloop()
Running the above code will keep printing the numbers in the range (0 to 9) on the
console, and along with that, it will display the main window.
0
1
2
3
4
5
6
7
8
9
.......
string.format() function in Lua programming

There are cases when we want to format strings which will help us to print the output in a particular format.
When we use the string.format() function it returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string.
The format string that we get the output, is similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string.
string.format(“s = %a”)
The string.format() syntax above contains an identifier s which is the string and the identifier a is the letter that tells how to format the argument.
There are many letters to tell how to format the argument, these are −
‘d’ - a decimal number
‘x’ - for hexadecimal
‘o’ - for octal
‘f’ - for a floating-point number
‘s’ - strings
and there are many other variants.
Now let’s consider some examples where we will run the string.format() function.
Consider the following example −
 Live Demo
s = string.format("x = %.4f",2345)
print(s)
x = 2345.0000
Now let’s consider one more example where we will print the string in a format that looks exactly similar to a date. Consider an example shown below −
 Live Demo
d = 5; m = 11; y = 2021
date = string.format("%02d/%02d/%04d",d,m,y)
print(date)
05/11/2021
Inserting data in a table in SAP HANA

To insert the data, you need to run the Insert statement in SQL editor. “Demo_HANA” is table name.
Insert into Demo_HANA Values (1,'John');
Insert into Demo_HANA Values (2,'Anna');
Insert into Demo_HANA Values (3,'Jason');
Insert into Demo_HANA Values (4,'Nick');
In SQL editor, add INSERT statements and execute (F8) as below −
Good example of functional testing a Python Tkinter application

Let us suppose that we have a GUI-based Python tkinter application that takes the
text input from the user and validates by saving it in a new text file. The file contains
the same text input that the user has typed. We can check and validate the user input from the file.
In Functional Testing, we are primarily concerned about backend API, database,
user-server communication, Input and output, etc.
To check the application using the functional testing strategy, we have to first
understand the user requirement and the input/output. After testing the pre-phase,
we test our application for different test cases.
For example, we have a GUI-based tkinter application that takes the user input
and saves it in the form of a text file in the system.
from tkinter import *

win = Tk()

win.geometry("700x600")

# Create title label
title_label = Label(win, text="Enter the File Name")
title_label.pack(anchor='n')

# Create title entry
title_entry = Entry(win, width=35)
title_entry.pack(anchor='nw')

# Create save button and function
def save():
   # Get contents of title entry and text entry
   # Create a file to write these contents in to it
   file_title = title_entry.get()
   file_contents = text_entry.get(0.0, END)
   with open(file_title + ".txt", "w") as file:
      file.write(file_contents)
      print("File successfully created")
      file.close()
   pass
#Create a save button to save the content of the file
save_button = Button(win, text="Save The File", command=save)
save_button.pack()

# Create text entry
text_entry = Text(win, width=40, height=30, border=4, relief=RAISED)
text_entry.pack()

win.mainloop()
Running the above code will create a window like this,
Once we will click the Save the File button, it will save the filename as “Tutorials.txt”.
Now, go to the file location and open the text file externally. It will have the same
text as the user input.
What is the use of router in Express.js ?

04 Jun, 2021
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, how to use the router in the express.js server.
The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.js.This is the advantage of the use of the Router.
Syntax:
express.Router( [options] )
Parameters: This function accepts one optional parameter whose properties are shown below.
Case-sensitive: This enables case sensitivity.
mergeParams: It preserves the request params values from the parent router.
strict: This enables strict routing.
Return Value: This function returns the New Router Object.
Installing Module: Install the module using the following command.
npm install express
Project structure: It will look like this.
Note: The routes folder contains Home.js and login.js file.
Implementation:
Home.js
// Importing express moduleconst express = require("express")  // Creating express routerconst router = express.Router()  // Handling request using routerrouter.get("/home", (req,res,next) => {    res.send("This is the homepage request")})  // Exporting routermodule.exports = router
login.js
// Importing the moduleconst express = require("express")  // Creating express Routerconst router = express.Router()  // Handling login requestrouter.get("/login", (req,res,next) => {  res.send("This is the login request")})  module.exports = router
index.js
// Requiring moduleconst express = require("express")  // Importing all the routesconst homeroute = require("./routes/Home.js")const loginroute = require("./routes/login")  // Creating express serverconst app = express()  // Handling routes requestapp.use("/", homeroute)app.use("/", loginroute)  // Server setupapp.listen((3000), () => {    console.log("Server is Running")})
Run index.js using the below command:
node index.js
Output: We will see the following output on the terminal screen.
Server is Running
Now go to http://localhost:3000/login and http://localhost:3000/home, we will see the following output on the browser screen.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.