code-rag-bench/online-tutorials huggingface dataset:
Checking if the Object is a Factor in R Programming – is.factor() Function

04 Jun, 2020
is.factor() function in R Language is used to check if the object passed to the function is a Factor or not. It returns a boolean value as output.
Syntax: is.factor(Object)
Parameters:Object: Object to be checked
Example 1:
# Creating a vector x<-c("female", "male", "male", "female")   # Converting the vector x into a factor named gender gender<-factor(x)    # Using is.factor() Functionis.factor(gender)
Output:
[1] TRUE

Example 2:
# Creating a vector x<-c("female", "male", "male", "female")   # Converting the vector x into a factor named gender gender<-factor(x)    # Using is.factor() Functionis.factor(x)
Output:
[1] FALSE

R Factor-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python | Pandas str.join() to join string/list elements with passed delimiter

19 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of character (or List of characters), hence when this method is applied on a series of strings, the string is joined at every character with the passed delimiter.
.str has to be prefixed every time before calling this method to differentiate it from the Python’s default string method.
Syntax: Series.str.join(sep)
Parameters:sep: string value, joins elements with the string between them
Return type: Series with joined elements
To download the Csv file used, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Joining string elements
In this example, the str.join() method is used on Name column (Series of String). As discussed earlier, a string is also an array of character and hence every character of string will be joined with the passed separator using str.join() method.
# importing pandas module import pandas as pd     # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # dropping null value columns to avoid errorsdata.dropna(inplace = True)    # joining string and overwriting data["Name"]= data["Name"].str.join("-")  # displaydata
Output:As shown in the output image, the string in name column have been joined character wise with the passed separator. Example #2: Joining elements of a list
In this example, the str.join() method is applied to a series of list. The Data in team column is separated into list using str.split() method.
# importing pandas module import pandas as pd     # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # dropping null value columns to avoid errorsdata.dropna(inplace = True)    # splitting string and overwriting data["Team"]= data["Team"].str.split("t")  # joining with "_"data["Team"]= data["Team"].str.join("_")  # displaydata
Output:As shown in the output images, the data was splitted into list using str.split() and then the list was joined using str.join() with separator “_”.
Dataframe after splitting –
DataFrame after joining list –
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LockPhish – Phishing Tool in Kali Linux

30 Jun, 2021
LockPhish is the first phishing tool to use an HTTPS link to steal Windows credentials, Android PINs, and iPhone Passcodes. LinuxChoice is the company that created this tool.
When the target enters a credential, it is captured and sent to the attacker through a ngrok tunnel. The device is automatically detected by this tool. Also, keep an eye on the victim’s IP address.
Phishing website for Windows, Android, and iPhone’s lock screen.
The device that recognizes itself.
Ngrok provides port forwarding.
IP Tracker.
Step 1: Before we install any tool on Kali, we must first update all the pre-installed packages so that we do not encounter any errors while using the tool.
sudo apt-get update
Step 2: To clone this tool from its GitHub repository, first, open a terminal window and execute the following command:
git clone https://github.com/kali-linux-tutorial/lockphish
Step 3: After the procedure is complete, we must use the cd command to get to the LockPhish directory:
cd lockphish
Step 4: Before we start Lockphish, we need to provide it root access. To do so, use the following command to change the file’s permissions:
sudo chmod +x lockphish.sh
Step 5: Then, using the following command, we must execute the tool:
./lockphish.sh
After phishing, we need to insert the redirecting website’s link below. YouTube is the default setting. We can use YouTube or other sites for social engineering. For this example, we’ll leave it at default and press Enter.
It will then install ngrok on our Kali Linux machine, configure the phishing servers on our localhost, and provide us with the Phishing URL.
With certain social engineering tactics, we can now deliver this URL to our target. When our target clicks on this link, it will prompt them to go to YouTube.
We obtained IP and some information of the victim’s pc on our terminal when our victim clicks the URL.
The same technique will work on a Windows PC and an iPhone; we only need to transmit the link, and it will detect the device type (Android, Windows, iPhone). This is how we can employ a phishing attack on a device’s lock-screen to obtain login credentials.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
TCP Server-Client implementation in C
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
Scala | Function Composition

26 May, 2022
Function composition is a way in which a function is mixed with other functions. During the composition the one function holds the reference to another function in order to fulfill it’s mission. There are some different ways in which a function composition can take place, as below :-
compose : Composing method works with val functions. Syntax : 
(function1 compose function2)(parameter)
In the above syntax function2 works first with the parameter passed & then passes then returns a value to be passed to function1. Example 1: 
Scala
// A Scala program to illustrate// compose method with val function // Creating objectobject GFG{    // Main method    def main(args: Array[String])    {        println((add compose mul)(2))                 // adding more methods        println((add compose mul compose sub)(2))    }         val add=(a: Int)=> {        a + 1    }         val mul=(a: Int)=> {        a * 2    }         val sub=(a: Int) =>{        a - 1    }}
Output :
5
3
In above example, firstly mul function called we got 4(2 * 2) than add function called and we got 5(4 + 1). similarly (add compose mul compose sub)(2) will print 3 (step1 : 2 – 1 = 1, step2 : 1 * 2 = 2, step3 : 2 + 1 = 3).
andThen : andThen method also works with val functions. Syntax :
(function1 andThen function2)(parameter)
In the above syntax function1 works first with the parameter passed & then passes then returns a value to be passed to function2. or as same as below:
function2(function1(parameter))
Example 2: 
Scala
// A Scala program to illustrate//andThen method with val function // Creating objectobject GFG{    // Main method    def main(args: Array[String])    {        println((add andThen mul)(2))                 // Adding more methods        println((add andThen mul andThen sub)(2))    }         val add=(a: Int)=> {        a + 1    }         val mul=(a: Int)=> {        a * 2    }         val sub=(a: Int) =>{        a - 1    }}
Output :
6
5
In above example, firstly add function called we got 3(2 + 1) than mul function called and we got 6(3 * 2). similarly add (andThen mul andThen sub)(2)) will print 5 (step1 : 2 + 1 = 3, step2 : 3 * 2 = 6, step3 : 6 – 1 = 5).
Passing methods to methods : Methods are passed to other methods. Syntax :
function1(function2(parameter))
It works as same as compose function, but it works with def and val methods. Example 3: 
Scala
// A Scala program to illustrate// passing methods to methods // Creating objectobject GFG{    // Main method    def main(args: Array[String])    {        println(add(mul(2)))                 // Adding more methods        println(add(mul(sub(2))))    }         val add=(a: Int)=> {        a + 1    }         val mul=(a: Int)=> {        a * 2    }         val sub=(a: Int) =>{        a - 1    }}
Output :
5
3
In above example, firstly mul function called we got 4(2 * 2) than add function called and we got 5(4 + 1). similarly add(mul(sub(2)) will print 3 (step1 : 2 – 1 = 1, step2 : 1 * 2 = 2, step3 : 2 + 1 = 3).
varshagumber28
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Check if given words appear together in a list of sentence

Say we have a list containing small sentences as its elements. We have another list which contains some of the words used in this sentences of the first list. We want to find out if two words from the second list are present together in some of the sentences of the first list or not.
We use the for loop with in condition to check for the presence of words in the lists of sentences. Then we use the len function to check if we have reached the end of the list.
 Live Demo
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']

print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)

res = []
for x in list_sen:
   k = [w for w in list_wrd if w in x]
   if (len(k) == len(list_wrd)):
      res.append(x)
print(res)
Running the above code gives us the following result −
Given list of sentences:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
Given list of words:
['Eggs', 'Fruits']
['Eggs and Fruits on Wednesday']
Here we design a for loop for checking if the words are present in the list containing sentences and then apply all function to verify indeed all the words are present in the sentence.
 Live Demo
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']

print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)

res = [all([k in s for k in list_wrd]) for s in list_sen]
print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])
Running the above code gives us the following result −
Given list of sentences:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
Given list of words:
['Eggs', 'Fruits']

The sentence containing the words:
['Eggs and Fruits on Wednesday']
We can take a similar approach as above but with lambda and map functions. We also use the split functions and check the availability of the all the given words in the list with sentences. The map function is used to apply this logic again and to each element of the lists.
 Live Demo
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']

print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)

res = list(map(lambda i: all(map(lambda j:j in i.split(),
list_wrd)), list_sen))

print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])
Running the above code gives us the following result −
Given list of sentences:
['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
Given list of words:
['Eggs', 'Fruits']

The sentence containing the words:
['Eggs and Fruits on Wednesday']
What is Linear bounded automata in TOC?

A deterministic linear bounded automaton (LBA) is 9-tuple automata
G = ( Q, Σ, E, δ, ε, q0, GL, GR, F)
Where,
Q is set of all states
Q is set of all states
Σ is set of all terminals
Σ is set of all terminals
E input alphabet.
E input alphabet.
δ is set of transitions
δ is set of transitions
q0 initial state
q0 initial state
GL left bound of tape
GL left bound of tape
GR right bound of tape.
GR right bound of tape.
F set of final state
F set of final state
A linear bounded automaton is called a multi-track non-deterministic Turing machine which has a tape of some bounded finite length.
Length = function (Length of the initial input string, constant c)
The computation in linear bounded automata is restricted to the constant bounded area. The input alphabet here contains two special symbols that serve as left end markers and right end markers. It explains that the transitions neither move to the left of the left end marker nor to the right of the right end marker of the tape.
A deterministic linear bounded automaton is context-sensitive and the linear bounded automaton with empty language is undecidable.
How linear bounded automata is constructed to accept the language L={an|n=m2,m>=1}?
For the given language L={an|n=m2,m>=1}, the strings it is generated is −
L(G) ={a.aa.ab.aaa.aab.abb.......}
S aA, A,aA,A,B,B,bB,B
S aA, A,aA,A,B,B,bB,B
S aA, aB, a, a (accepted)
S aA, aB, a, a (accepted)
S aA, aaA aaB, aa, aa (accepted)
S aA, aaA aaB, aa, aa (accepted)
S aA, aB abB, ab, ab (accepted)
S aA, aB abB, ab, ab (accepted)
SaA, aaA, aaaA, aaa aaa (accepted)
SaA, aaA, aaaA, aaa aaa (accepted)
SaA, aaA, aaB, aabB aab, aab (accepted)
SaA, aaA, aaB, aabB aab, aab (accepted)
SaA, aB, abB, abbB, abb, abb (accepted)
SaA, aB, abB, abbB, abb, abb (accepted)
We can prove every single string in L(G) here is accepted by the language by the production set.
G={{S,AB};{a,b}S, {S aA, A,aA/B, B/bB}}.
How to Hide/Encrypt/Obfuscate any Python Program | by Balakrishnakumar V | Towards Data Science

For the purpose of obfuscation, we will be using a python package called pyarmor.
We might sometimes face a situation where we need to provide code directly to a client for obvious reasons, but by doing so, we will lose control of the code. In such cases, we might we encrypt the codes to protect it, retain control and add some fallback condition to control our dependency, just like if we provided code for using only for a certain amount of time.
To address the above issues, I will be demonstrating a simple function with the above capabilities. We will be making use of the python library called “pyarmor”.
Creating a simple functionUsing pyarmor to encrypt itImporting our function / Inference
Creating a simple function
Using pyarmor to encrypt it
Importing our function / Inference
For our implementation, I will be using the utils.py with inference function definition and will be encrypting it later.
The inference function is pretty straight forward and doesn’t need any explanation.
Save it in a folder.
Now we will encrypt it, by running the following 2 commands.
pip3 install pyarmor # pip/pip3# Syntax : pyarmor obfuscate --restrict=0 <filename>pyarmor obfuscate --restrict=0 utils.py
Now if you see the folder containing our actual utils.py file, a new subfolder will be created called dist.
Let’s see the contents inside them.
Once we are done, until this point, now let’s try to import this encrypted utils.py in a new python file called main.py, which is created inside the dist folder.
The necessary keys for decrypting the utils.py at run-time is taken care of by pyarmor and it's present in the pytransform folder, thus making our code completely non-readable to other's eyes.
But if you wish to modify the original utils.py code, then you have to start from step 1 and follow the same steps to do so.
Contents inside main.py file,
# Import the inference function definition inside the utils.py filefrom utils import inference_ = inference(name="Balakrishna")
And upon running the above line, we get the output based on our utils.py file’s configuration.
This is merely the beginning. If you want to really protect and sell your code, consider adding an actual license with an embedded virtual date on it. Upon passing the date, it will no longer run the program and throws a license expiry error. Luckily pyarmor has that too. I have added the license-related documentation in the references below. You can even set up a provision to email automatically once the license is expired and you can get in touch with your clients using the SMTP services in python.
Also if you have a lot of .py files to import or as dependency, you must use the — recursive command line instead of — restrict command for your code to work.
Also, this implementation can be done in both Windows and Ubuntu-based OS.
Complete Code Implementation is available at,
Java Program for ShellSort - GeeksforGeeks

04 Dec, 2018
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.
// Java implementation of ShellSortclass ShellSort {    /* An utility function to print array of size n*/    static void printArray(int arr[])    {        int n = arr.length;        for (int i = 0; i < n; ++i)            System.out.print(arr[i] + " ");        System.out.println();    }      /* function to sort arr using shellSort */    int sort(int arr[])    {        int n = arr.length;          // Start with a big gap, then reduce the gap        for (int gap = n / 2; gap > 0; gap /= 2) {            // Do a gapped insertion sort for this gap size.            // The first gap elements a[0..gap-1] are already            // in gapped order keep adding one more element            // until the entire array is gap sorted            for (int i = gap; i < n; i += 1) {                // add a[i] to the elements that have been gap                // sorted save a[i] in temp and make a hole at                // position i                int temp = arr[i];                  // shift earlier gap-sorted elements up until                // the correct location for a[i] is found                int j;                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)                    arr[j] = arr[j - gap];                  // put temp (the original a[i]) in its correct                // location                arr[j] = temp;            }        }        return 0;    }      // Driver method    public static void main(String args[])    {        int arr[] = { 12, 34, 54, 2, 3 };        System.out.println("Array before sorting");        printArray(arr);          ShellSort ob = new ShellSort();        ob.sort(arr);          System.out.println("Array after sorting");        printArray(arr);    }}/*This code is contributed by Rajat Mishra */
Array before sorting
12 34 54 2 3 
Array after sorting
2 3 12 34 54

Please refer complete article on ShellSort for more details!
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
Amazon product price tracker using Python - GeeksforGeeks

23 Jan, 2019
As we know Python is a multi-purpose language and widely used for scripting. We can write Python scripts to automate daily life task.
Let’s say we want to track any Amazon product price and grab the deal when the price changes below our defined price. Let’s write a Python script for this.
Below is the code:
# Amazon product price tracker using Python  # importing librariesimport bs4 as bsimport sysimport scheduleimport timeimport urllib.requestfrom PyQt5.QtWebEngineWidgets import QWebEnginePagefrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtCore import QUrl  import winsoundfrequency = 2500  # Set Frequency To 2500 Hertzduration = 1000  # Set Duration To 1000 ms == 1 second    class Page(QWebEnginePage):      def __init__(self, url):        self.app = QApplication(sys.argv)        QWebEnginePage.__init__(self)        self.html = ''        self.loadFinished.connect(self._on_load_finished)        self.load(QUrl(url))        self.app.exec_()      def _on_load_finished(self):        self.html = self.toHtml(self.Callable)        print('Load finished')      def Callable(self, html_str):        self.html = html_str        self.app.quit()  def exact_url(url):    index = url.find("B0")    index = index + 10    current_url = ""    current_url = url[:index]    return current_url        def mainprogram():    url = "https://www.amazon.in/Airtel-4G-Hotspot-E5573Cs-609-Portable/dp/B06WV9WR4Z"    exacturl = exact_url(url) # main url to extract data    page = Page(exacturl)    soup = bs.BeautifulSoup(page.html, 'html.parser')    js_test = soup.find('span', id ='priceblock_ourprice')    if js_test is None:        js_test = soup.find('span', id ='priceblock_dealprice')            str = ""    for line in js_test.stripped_strings :        str = line      # convert to integer    str = str.replace(", ", "")    current_price = int(float(str))    your_price = 600    if current_price < your_price :        print("Price decreased book now")        winsound.Beep(frequency, duration)    else:        print("Price is high please wait for the best deal")      def job():    print("Tracking....")        mainprogram()  # main codeschedule.every(1).minutes.do(job)  while True:    schedule.run_pending()    time.sleep(1)
Output:
Tracking....
Load finished
Price is high please wait for the best deal

Project
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Java Swing | Simple User Registration Form
Twitter Sentiment Analysis using Python
Banking Transaction System using Java
Program for Employee Management System
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python | Remove all duplicates and permutations in nested list

12 Feb, 2019
Given nested list, the task is to remove all duplicated and permutations in that nested list.
Input:  [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11], 
         [-11, 2, -11], [-11, 2, -11], [-11, -11, 2]]
Output:  {(-11, 0, 11), (-11, -11, 2)}

Input:  [[-1, 5, 3], [3, 5, 0], [-1, 5, 3], 
         [1, 3, 5], [-1, 3, 5], [5, -1, 3]]
Output:  {(1, 3, 5), (0, 3, 5), (-1, 3, 5)}
 Code #1 : Using Map
# Python code to remove all duplicates# and permutations in nested list  #InitialisationlistOfPermut = [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11],                 [-11, 2, -11], [-11, -11, 2], [2, -11, -11]]  # Sorting tuple then removingoutput = set(map(lambda x: tuple(sorted(x)),listOfPermut))  # printing outputprint(output)
{(-11, 0, 11), (-11, -11, 2)}

 Code #2 :
# Python code to remove all duplicates# and permutations in nested list  #Initialisationinput = [[-11, 0, 11], [-11, 11, 0], [-11, 2, -11],                      [-11, -11, 2], [2, -11, -11]]  # Sorting tuple then removingoutput = set(tuple(sorted(x)) for x in input)  # printing outputprint(output)
{(-11, 0, 11), (-11, -11, 2)}

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery UI Datepicker getDate() Method

08 Jan, 2021
jQuery UI Datepicker getDate() method is used to get the date from the date field.
Syntax:
var a = $( ".selector" ).datepicker( "getDate" )
Parameters: This method does not accept any parameters.
Return values: This method returns the date.
Approach: First, add jQuery mobile scripts needed for your project.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js”></script><link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css” rel=”stylesheet” type=”text/css” />
Example 1:
HTML
<!doctype html><html lang = "en">   <head>    <meta charset="utf-8">     <meta name="viewport" content=         "width=device-width, initial-scale=1">       <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">     </script>       <script src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js">     </script>       <link href= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css"        rel="stylesheet" type="text/css" />         <script>         $(function() {            $( "#datepicker" ).datepicker();            var a = $( "#datepicker" ).datepicker("getDate");            console.log(a)         });      </script>   </head>        <body>      <p>Date: <input type = "text"          id = "datepicker"></p>   </body></html>
 
Output:
Without date selection:
 
With datepicker selection:
Example 2:
HTML
<!doctype html><html lang = "en">   <head>    <meta charset="utf-8">     <meta name="viewport" content=         "width=device-width, initial-scale=1">       <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">     </script>       <script src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js">     </script>       <link href= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css"        rel="stylesheet" type="text/css" />         <script>         $(function() {            $( "#datepicker" ).datepicker();                       });         function me(){            var a = $( "#datepicker" ).datepicker("getDate");            console.log(a)         }      </script>   </head>        <body>      <p>Date: <input type = "text"          id = "datepicker"></p>        <button onclick="me()">         Click to get      </button>   </body></html>
 
Output:
 
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Sort Tuples by Total digits

11 Oct, 2020
Given a Tuple List, perform sort on basis of total digits in tuple.
Examples:
Input : test_list = [(3, 4, 6, 723), (1, 2), (134, 234, 34)] Output : [(1, 2), (3, 4, 6, 723), (134, 234, 34)] Explanation : 2 < 6 < 8, sorted by increasing total digits. 
Input : test_list = [(1, 2), (134, 234, 34)] Output : [(1, 2), (134, 234, 34)] Explanation : 2 < 8, sorted by increasing total digits. 
Method #1: Using sort() + len() + sum()
In this, we get all sum of all lengths of each element in the tuple by string conversion and len(). Then sort() is used with key to solve this problem.
Python3
# Python3 code to demonstrate working of # Sort Tuples by Total digits# Using sort() + len() + sum()  def count_digs(tup):          # gets total digits in tuples    return sum([len(str(ele)) for ele in tup ])  # initializing listtest_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]  # printing original listprint("The original list is : " + str(test_list))  # performing sort test_list.sort(key = count_digs)  # printing result print("Sorted tuples : " + str(test_list))
The original list is : [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
Sorted tuples : [(1, 2), (12345,), (3, 4, 6, 723), (134, 234, 34)]

 Method #2 : Using sorted() + lambda + sum() + len()
In this, we perform task of sorting using sorted(), and the lambda function performs the task of computation of total digits in tuples.
Python3
# Python3 code to demonstrate working of # Sort Tuples by Total digits# Using sorted() + lambda + sum() + len()  # initializing listtest_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]  # printing original listprint("The original list is : " + str(test_list))  # performing sort, lambda function provides logicres = sorted(test_list, key = lambda tup : sum([len(str(ele)) for ele in tup ]))  # printing result print("Sorted tuples : " + str(res))
The original list is : [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
Sorted tuples : [(1, 2), (12345,), (3, 4, 6, 723), (134, 234, 34)]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Class in Node.js ?

01 Jul, 2020
Introduction: In the modern JavaScript, there is a more advanced “class” construct, that introduces great new features that are useful for object-oriented programming. As we can define a function in two way i.e. function expressions and function declarations.
The class syntax has two components:
Class expressionsClass declarations
Class expressions
Class declarations
Syntax:
// Class expression
let class_name  = class {
 constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }
};

// Class declaration
class class_name {
  constructor(method1, method2) {
    this.method1 = method1;
    this.method2= method2;
  }
}

Example 1: Class Declaration
class Polygon {  constructor(height, width) {    this.area = height * width;  }}  console.log(new Polygon(5, 15).area);
Output:
Example 2: Class Expression
const Rectangle = class {  constructor(height, width) {    this.height = height;    this.width = width;  }    area() {    return this.height * this.width;  }};  console.log(new Rectangle(6, 10).area());
Output:
Class body and method definition: The body of a class is within the curly brackets {} and this is the place where you define class members such as methods or constructors. The constructor method is a special method for creating and initializing an object created with a class. A constructor can use the super keyword to call the constructor of the superclass.
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
JWT Authentication with Node.js
How to use an ES6 import in 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
C++ | this pointer | Question 3

28 Jun, 2021
Predict the output of following C++ program.
#include<iostream>using namespace std;  class Test{private:  int x;public:  Test(int x = 0) { this->x = x; }  void change(Test *t) { this = t; }  void print() { cout << "x = " << x << endl; }};  int main(){  Test obj(5);  Test *ptr = new Test (10);  obj.change(ptr);  obj.print();  return 0;}
(A) x = 5(B) x = 10(C) Compiler Error(D) Runtime ErrorAnswer: (C)Explanation: this is a const pointer, so there is an error in line “this = t;”Quiz of this Question
C++-this pointer
this pointer
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
long keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. long is a keyword that is used to declare a variable which can store a signed integer value from the range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is an alias of System.Int64.
Syntax:
long variable_name = value;
long keyword occupies 8 bytes (64 bits) space in the memory.
Example:
Input: num: 34638

Output: num: 34638
        Size of a long variable: 8

Input: num = -79349367648374345

Output: Type of num: System.Int64
        num: -79349367648374345
        Size of a long variable: 8

If we input number beyond the range, it shows error-
Integral constant is too large
Example 1:
// C# program for long keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // variable declaration        long num = 34638;          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a long variable: " + sizeof(long));    }}
Output:
num: 34638
Size of a long variable: 8

Example 2:
// C# program for long keywordusing System;using System.Text;  namespace Test {  class GFG {      static void Main(string[] args)    {        // variable declaration        long num = -79349367648374345;          // to print type of variable        Console.WriteLine("Type of num: " + num.GetType());          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a long variable: " + sizeof(long));          // to print minimum & maximum value of long        Console.WriteLine("Min value of long: " + long.MinValue);        Console.WriteLine("Max value of long: " + long.MaxValue);          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of num: System.Int64
num: -79349367648374345
Size of a long variable: 8
Min value of long: -9223372036854775808
Max value of long: 9223372036854775807

CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
How to access array elements using a pointer in C#?

In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not the same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that.
Here is an example −
using System;

namespace UnsafeCodeApplication {
   class TestPointer {
      public unsafe static void Main() {
         int[] list = {5, 25};
         fixed(int *ptr = list)

         /* let us have array address in pointer */
         for ( int i = 0; i < 2; i++) {
            Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
            Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
         }
         Console.ReadKey();
      }
   }
}
Here is the output −
Address of list[0] = 31627168
Value of list[0] = 5
Address of list[1] = 31627172
Value of list[1] = 25
How to initialize private static members in C++?

Here we will see how to initialize the private static member variables initialization in C++. We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class.
To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
The following code will illustrate the of static member initializing technique.
#include <iostream>
using namespace std;
class MyClass{
   private:
      static int st_var;
   public:
      MyClass(){
         st_var++; //increase the value of st_var when new object is created
      }
      static int getStaticVar() {
         return st_var;
      }
};
int MyClass::st_var = 0; //initializing the static int
main() {
   MyClass ob1, ob2, ob3; //three objects are created
   cout << "Number of objects: " << MyClass::getStaticVar();
}
Number of objects: 3
How to read an image file in internal storage in android?

This example demonstrates How to read an image file in internal storage in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <Button
      android:id = "@+id/read"
      android:text = "read"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
   <ImageView
      android:id = "@+id/imageView"
      android:layout_width = "300dp"
      android:layout_height = "300dp" />
</LinearLayout>
In the above code, we have taken a button and image view. When user click on button, it will take an image from internal storage and append to image view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity {
   Button read;
   ImageView imageView;

   @Override
   protected void onCreate(Bundle readdInstanceState) {
      super.onCreate(readdInstanceState);
      setContentView(R.layout.activity_main);
      imageView = findViewById(R.id.imageView);
      read = findViewById(R.id.read);
      read.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            File file = new File(directory, "mario" + ".png");
            imageView.setImageDrawable(Drawable.createFromPath(file.toString()));
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, click on read button to read an image from internal storage as shown below –
Click here to download the project code
What are abstract properties in C#?

An implementation of the property accessors will not be provided by an abstract property declaration.
Let us see how to learn how to work with abstract properties. Here we have an abstract class Shape with two derived classes: Square and Circle.
Here, we have an abstract Area property.
The following is the Circle class.
public class Circle : Shape {
   private int radius;
   public Circle(int radius, string id) : base(id) {
      this.radius = radius;
   }
   public override double Area {
      get {
         return radius * radius * System.Math.PI;
      }
   }
}
In the same way, the Square class.
public class Square : Shape {
   private int side;
   public Square(int side, string id) : base(id) {
      this.side = side;
   }
   public override double Area {
      get {
         return side * side;
      }
   }
}
The following is the Shape class, which is abstract.
public abstract class Shape {
   private string name;
   public Shape(string s) {
      Id = s;
   }
   public string Id {
      get {
         return name;
      }
      set {
         name = value;
      }
   }
   public abstract double Area {
      get;
   }
   public override string ToString() {
      return Id + " Area = " + string.Format("{0:F2}", Area);
   }
}
Cypress - Tabs

Cypress does not have a specific command to work with tabs. It has a workaround method in jQuery through which it handles the tabs. In the html code, a link or button opens to a new tab, because of the attribute target.
If the target attribute has value blank, it opens to a new tab. Cypress uses the jQuery method removeAttr, which is invoked by the invoke command. The removeAttr deletes the attribute, which is passed as one of the parameters to the invoke method.
Once the target=blank is removed, then a link/button opens in the parent window. Later on after performing the operations on it, we can shift back to the parent URL with the go command.
The Html code for the same is as follows −
Given below is the implementation of the use of commands with regards to tabs in Cypress −
describe('Tutorialspoint', function () {
   // test case
   it('Scenario 1', function (){
      // url launch
      cy.visit("https://the-internet.herokuapp.com/windows")
      // delete target attribute with invoke for link
      cy.get('.example > a')
      .invoke('removeAttr', 'target').click()
      // verify tab url
      cy.url()
      .should('include', 'https://the-internet.herokuapp.com/windows/new')
      // shift to parent window
     cy.go('back');
   });
});
Execution Results
The output is as follows −
The output logs show the deletion of the target attribute and launch of the new tab within the parent window.

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
C++ Program to Construct an Expression Tree for a Postfix Expression

An expression tree is basically a binary tree which is used to represent expressions. In expression tree, nodes correspond to the operator and each leaf node corresponds to the operand. This is a C++ program to construct an expression tree for a postfix Expression in inorder, preorder and postorder traversals.
Begin
   Function r() has a character variable as parameter.
      If the characters are + or - or * or / then
         Return will be -1
      If the characters are from A to Z then
         Return will be 1.
      If the characters are from a to z then
         Return will be 1.
      Else
         Return -100.
   Function construct_expression_tree() to construct the expression tree
   Function push() to push values in the stack
   Function pop() to pop values from the stack
   Function preOrder() for pre-order traversal
   Function inOrder() for in-order traversal
   Function postOrder() for post-order traversal 
End.
 Live Demo
#include <iostream>
using namespace std;
struct n {
   char d;
   n *l;
   n *r;
};
char pf[50];
int top = -1;
n *a[50];
int r(char inputch) {
   if (inputch == '+' || inputch == '-' || inputch == '*' || inputch== '/')
      return (-1);
   else if (inputch >= 'A' || inputch <= 'Z')
      return (1);
   else if (inputch >= 'a' || inputch <= 'z')
      return (1);
   else
      return (-100);
}
void push(n *tree) {
   top++;
   a[top] = tree;
}
n *pop() {
   top--;
   return (a[top + 1]);
}
void construct_expression_tree(char *suffix) {
   char s;
   n *newl, *p1, *p2;
   int flag;
   s = suffix[0];
   for (int i = 1; s != 0; i++) {
      flag = r(s);
      if (flag == 1) {
         newl = new n;
         newl->d = s;
         newl->l = NULL;
         newl->r = NULL;
         push(newl);
      } else {
         p1 = pop();
         p2 = pop();
         newl = new n;
         newl->d = s;
         newl->l = p2;
         newl->r = p1;
         push(newl);
      }
      s = suffix[i];
   }
}
void preOrder(n *tree) {
   if (tree != NULL) {
      cout << tree->d;
      preOrder(tree->l);
      preOrder(tree->r);
   }
}
void inOrder(n *tree) {
   if (tree != NULL) {
      inOrder(tree->l);
      cout << tree->d;
      inOrder(tree->r);
   }
}
void postOrder(n *tree) {
   if (tree != NULL) {
      postOrder(tree->l);
      postOrder(tree->r);
      cout << tree->d;
   }
}
int main(int argc, char **argv) {
   cout << "Enter Postfix Expression : ";
   cin >> pf;
   construct_expression_tree(pf);
   cout << "\nIn-Order Traversal : ";
   inOrder(a[0]);
   cout << "\nPre-Order Traversal : ";
   preOrder(a[0]);
   cout << "\nPost-Order Traversal : ";
   postOrder(a[0]);
   return 0;
}
Enter Postfix Expression : 762*+6+
In-Order Traversal : 7+6*2+6
Pre-Order Traversal : ++7*626
Post-Order Traversal : 762*+6+
Obtain the hash code for a string in Java

The hashCode() method is used to obtain the hash code for a string. This method does not accept any parameters as it is a default method and it returns a hash code value.
A program that demonstrates the hashCode() method in Java is given as follows:
 Live Demo
import java.io.*;
public class Demo {
   public static void main(String args[]) {
      String str = new String("The sky is blue");
      System.out.println("The string is: " + str);
      System.out.println("The Hashcode for the string is: " + str.hashCode());
   }
}
The string is: The sky is blue
The Hashcode for the string is: -729257918
Now let us understand the above program.
The string str is defined. Then the string is printed and its HashCode is also printed using the hashCode() method. A code snippet which demonstrates this is as follows:
String str = new String("The sky is blue");
System.out.println("The string is: " + str);
System.out.println("The Hashcode for the string is: " + str.hashCode());
Magic Squares In Grid in C++

Suppose we have a grid we have to find the number of magic square sub-grid into that grid. A magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
So, if the input is like
then the output will be 1, as the magic square is
To solve this, we will follow these steps −
Define one set with values: [816357492, 834159672, 618753294, 672159834,492357816, 438951276, 294753618, 276951438]
Define an array offset of size: 9 x 2 := {{-2,-2},{-2,-1},{-2,0},{-1,-2},{-1,-1},{-1,0},{0,-2},{0,-1},{0,0}}
ans := 0
for initialize i := 2, when i < grid row count, update (increase i by 1), do −for initialize j := 2, when j < grid row count, update (increase j by 1), do −sum := 0for initialize k := 0, when k < 9, update (increase k by 1), do −sum := sum * 10sum := sum + grid[i + offset[k, 0], j + offset[k, 1]]ans := ans + occurrence of sum in s
for initialize j := 2, when j < grid row count, update (increase j by 1), do −sum := 0for initialize k := 0, when k < 9, update (increase k by 1), do −sum := sum * 10sum := sum + grid[i + offset[k, 0], j + offset[k, 1]]ans := ans + occurrence of sum in s
sum := 0
for initialize k := 0, when k < 9, update (increase k by 1), do −sum := sum * 10sum := sum + grid[i + offset[k, 0], j + offset[k, 1]]
sum := sum * 10
sum := sum + grid[i + offset[k, 0], j + offset[k, 1]]
ans := ans + occurrence of sum in s
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int numMagicSquaresInside(vector<vector<int>>& grid) {
      const unordered_set<int> s{816357492, 834159672, 618753294,
      672159834,492357816, 438951276, 294753618,276951438};
      const int offset[][2] = {{-2, -2}, {-2, -1}, {-2, 0},{-1, -2}, {-1, -1}, {-1, 0},
{ 0, -2}, { 0, -1}, { 0, 0}};
      int ans = 0;
      for(int i = 2; i< grid.size(); i++)
      {
         for(int j = 2; j<grid.size(); j++)
         {
            int sum = 0;
            for(int k = 0; k<9; k++)
            {
               sum *= 10;
               sum += grid[i + offset[k][0]][j+offset[k][1]];
            }
            ans += s.count(sum);
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{4,3,8,4},{9,5,1,9},{2,7,6,2}};
   cout << (ob.numMagicSquaresInside(v));
}
{{4,3,8,4},{9,5,1,9},{2,7,6,2}}
1