code-rag-bench/online-tutorials huggingface dataset:
HTML | DOM Input Text defaultValue Property

08 Mar, 2019
The Input Text defaultValue Property in HTML DOM is used to set or return the default value of the Text Field. This property is used to reflect the HTML value attribute. The main difference between the default value and value is that the default value indicate the default value and the value contains the current value after making some changes. This property is useful to find out whether the text field have been changed or not.
Syntax:
It returns the defaultValue property.textObject.defaultValue
textObject.defaultValue
It is used to set the defaultValue property.textObject.defaultValue = value
textObject.defaultValue = value
Property Values: It contains single property value value which defines the default value for text field.
Return Value: It returns a string value which represent the default value of the text field.
Example 1: This example illustrates how to return Input Text defaultValue property.
<!DOCTYPE html> <html>   <head>     <title>         HTML DOM Input Text defaultValue Property    </title> </head>   <body style="text-align:center;">       <h1>GeeksForGeeks</h1>       <h2>DOM Input Text defaultValue Property</h2>           <form id="myGeeks">        <input type="text" id="text_id" name="geeks"                value="GeeksForGeeks">     </form><br>          <button onclick="myGeeks()">Click Here!</button>           <p id="GFG" style="font-size:20px;"></p>           <!-- script to return the defaultValue Property-->    <script>         function myGeeks() {             var txt = document.getElementById("text_id").defaultValue;            document.getElementById("GFG").innerHTML = txt;        }     </script> </body>   </html>                    
Output:Before Clicking the Button:After Clicking the Button:
Example 2: This example illustrates how to set Input Text defaultValue property.
<!DOCTYPE html> <html>   <head>     <title>         HTML DOM Input Text defaultValue Property    </title> </head>   <body style="text-align:center;">       <h1>GeeksForGeeks</h1>       <h2>DOM Input Text defaultValue Property</h2>           <form id="myGeeks">        <input type="text" id="text_id" name="geeks"                value="GeeksForGeeks">     </form><br>          <button onclick="myGeeks()">Click Here!</button>           <p id="GFG" style="font-size:20px;"></p>           <!-- script to set the defaultValue Property-->    <script>         function myGeeks() {             var txt = document.getElementById("text_id").defaultValue                    = "HelloGeeks";                                  document.getElementById("GFG").innerHTML = txt;        }     </script> </body>   </html>                         
Output:Before Clicking the Button:After Clicking the Button:
Supported Browsers: The browser supported by DOM input Text defaultValue Property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-DOM
HTML-Property
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python str() function

30 Sep, 2021
Python str() function returns the string version of the object.
Syntax: str(object, encoding=’utf-8?, errors=’strict’)
Parameters:
object: The object whose string representation is to be returned.
encoding: Encoding of the given object.
errors: Response when decoding fails.
Returns: String version of the given object
Python3
# Python program to demonstrate# strings # Empty strings = str()print(s) # String with valuess = str("GFG")print(s)
Output:
GFG
Python3
# Python program to demonstrate# strings num = 100s = str(num)print(s, type(s)) num = 100.1s = str(num)print(s, type(s))
Output:
100 <class 'str'>
100.1 <class 'str'>
There are six types of error taken by this function.
strict (default): it raises a UnicodeDecodeError.
ignore: It ignores the unencodable Unicode
replace: It replaces the unencodable Unicode with a question mark
xmlcharrefreplace: It inserts XML character reference instead of the unencodable Unicode
backslashreplace: inserts a \uNNNN Espace sequence instead of unencodable Unicode
namereplace: inserts a \N{...} escape sequence instead of an unencodable Unicode
Example:
Python3
# Python program to demonstrate# str() a = bytes("ŽString", encoding = 'utf-8')s = str(a, encoding = "ascii", errors ="ignore")print(s)
Output:
String
In the above example, the character Ž should raise an error as it cannot be decoded by ASCII. But it is ignored because the errors is set as ignore.
kumar_satyam
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program for KMP Algorithm for Pattern Searching

08 Jun, 2022
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: 
Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12
 
Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.  
C++
// C++ program for implementation of KMP pattern searching// algorithm#include <bits/stdc++.h> void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]void KMPSearch(char* pat, char* txt){    int M = strlen(pat);    int N = strlen(txt);     // create lps[] that will hold the longest prefix suffix    // values for pattern    int lps[M];     // Preprocess the pattern (calculate lps[] array)    computeLPSArray(pat, M, lps);     int i = 0; // index for txt[]    int j = 0; // index for pat[]    while (i < N) {        if (pat[j] == txt[i]) {            j++;            i++;        }         if (j == M) {            printf("Found pattern at index %d ", i - j);            j = lps[j - 1];        }         // mismatch after j matches        else if (i < N && pat[j] != txt[i]) {            // Do not match lps[0..lps[j-1]] characters,            // they will match anyway            if (j != 0)                j = lps[j - 1];            else                i = i + 1;        }    }} // Fills lps[] for given pattern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){    // length of the previous longest prefix suffix    int len = 0;     lps[0] = 0; // lps[0] is always 0     // the loop calculates lps[i] for i = 1 to M-1    int i = 1;    while (i < M) {        if (pat[i] == pat[len]) {            len++;            lps[i] = len;            i++;        }        else // (pat[i] != pat[len])        {            // This is tricky. Consider the example.            // AAACAAAA and i = 7. The idea is similar            // to search step.            if (len != 0) {                len = lps[len - 1];                 // Also, note that we do not increment                // i here            }            else // if (len == 0)            {                lps[i] = 0;                i++;            }        }    }} // Driver program to test above functionint main(){    char txt[] = "ABABDABACDABABCABAB";    char pat[] = "ABABCABAB";    KMPSearch(pat, txt);    return 0;}
Found pattern at index 10
 
Time Complexity: O(m+n)
Space Complexity: O(m)
Please refer complete article on KMP Algorithm for Pattern Searching for more details! 
simranarora5sos
chandramauliguptach
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Find the index of Minimum element in list

17 Dec, 2019
Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss ways to achieve this task.
Method #1 : Using min() + enumerate() + list comprehensionIn this method, the combination of above functions is used to perform this particular task. This is performed in two steps. In 1st, we acquire the minimum element and then access the list using list comprehension and corresponding element using enumerate and extract every element position equal to minimum element processed in step 1.
# Python3 code to demonstrate working of# Minimum element indices in list# Using list comprehension + min() + enumerate()  # initializing listtest_list = [2, 5, 6, 2, 3, 2]  # printing listprint("The original list : " + str(test_list))  # Minimum element indices in list# Using list comprehension + min() + enumerate()temp = min(test_list)res = [i for i, j in enumerate(test_list) if j == temp]  # Printing resultprint("The Positions of minimum element : " + str(res))
The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0, 3, 5]

 
Method #2 : Using loop + min()This is brute method to perform this task. In this, we compute the minimum element and then iterate the list to equate to min element and store indices.
# Python3 code to demonstrate working of# Minimum element indices in list# Using loop + min()  # initializing listtest_list = [2, 5, 6, 2, 3, 2]  # printing listprint("The original list : " + str(test_list))  # Minimum element indices in list# Using loop + min()temp = min(test_list)res = []for idx in range(0, len(test_list)):    if temp == test_list[idx]:        res.append(idx)  # Printing resultprint("The Positions of minimum element : " + str(res))
The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0, 3, 5]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NLP | Synsets for a word in WordNet

28 Jan, 2019
WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing.
Synset is a special kind of a simple interface that is present in NLTK to look up words in WordNet. Synset instances are the groupings of synonymous words that express the same concept. Some of the words have only one Synset and some have several.
Code #1 : Understanding Synset
from nltk.corpus import wordnetsyn = wordnet.synsets('hello')[0]  print ("Synset name :  ", syn.name())  # Defining the wordprint ("\nSynset meaning : ", syn.definition())  # list of phrases that use the word in contextprint ("\nSynset example : ", syn.examples())
Output:
Synset name :   hello.n.01

Synset meaning :  an expression of greeting

Synset example :  ['every morning they exchanged polite hellos']
wordnet.synsets(word) can be used to get a list of Synsets. This list can be empty (if no such word is found) or can have few elements. Hypernyms and Hyponyms –
Hypernyms: More abstract termsHyponyms: More specific terms.
Both come to picture as Synsets are organized in a structure similar to that of an inheritance tree. This tree can be traced all the way up to a root hypernym. Hypernyms provide a way to categorize and group words based on their similarity to each other.
Code #2 : Understanding Hypernerms and Hyponyms
from nltk.corpus import wordnetsyn = wordnet.synsets('hello')[0]  print ("Synset name :  ", syn.name())  print ("\nSynset abstract term :  ", syn.hypernyms())  print ("\nSynset specific term :  ",        syn.hypernyms()[0].hyponyms())  syn.root_hypernyms()  print ("\nSynset root hypernerm :  ", syn.root_hypernyms())
Output:
Synset name :   hello.n.01

Synset abstract term :   [Synset('greeting.n.01')]

Synset specific term :   [Synset('calling_card.n.02'), Synset('good_afternoon.n.01'), 
Synset('good_morning.n.01'), Synset('hail.n.03'), Synset('hello.n.01'), 
Synset('pax.n.01'), Synset('reception.n.01'), Synset('regard.n.03'), 
Synset('salute.n.02'), Synset('salute.n.03'), Synset('welcome.n.02'), 
Synset('well-wishing.n.01')]

Synset root hypernerm :   [Synset('entity.n.01')]
 Code #3 : Part of Speech (POS) in Synset.
syn = wordnet.synsets('hello')[0]print ("Syn tag : ", syn.pos())  syn = wordnet.synsets('doing')[0]print ("Syn tag : ", syn.pos())  syn = wordnet.synsets('beautiful')[0]print ("Syn tag : ", syn.pos())  syn = wordnet.synsets('quickly')[0]print ("Syn tag : ", syn.pos())
Output:
Syn tag :  n
Syn tag :  v
Syn tag :  a
Syn tag :  r
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if a string contains only lower case letters in Python?

We can check if a string contains only lower case letters using 2 methods. First is using method islower().
For example:
print('Hello world'.islower())
print('hello world'.islower())
OUTPUT
False
True
You can also use regexes for the same result. For matching only lowercase, we can call the re.match(regex, string) using the regex: "^[a-z]+$". For example,
print(bool(re.match('^[a-z]+$', '123abc')))
print(bool(re.match('^[a-z]+$', 'abc')))
OUTPUT
False
True
AngularJS – isString() method

The isString() method in AngularJS basically checks if a reference is a string value or not. This method will return True if the reference passed inside the function is a string, else it will return False.
angular.isString(value)
Create a file "isString.html" in your Angular project directory and copy-paste the following code snippet.
<!DOCTYPE html>
<html>
   <head>
      <title>angular.isString()</title>

      <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
      </script>
   </head>

   <body ng-app="app" style="text-align:center">
      <h1 style="color:green">
         Welcome to Tutorials Point
      </h1>
      <h2>AngularJS | angular.isString()</h2>

      <div ng-controller="example">
         <b>Name: {{name}}</b>
         <br><br>
         {{isString}}
         <br><br>
         <b>Name: {{name2}}</b>
         <br><br>
         {{isString1}}
         <br><br>
         <b>Name: {{name3}}</b>
         <br><br>
         {{isString2}}
      </div>

      <!-- Script for passing the values and checking... -->
      <script>
         var app = angular.module("app", []);
         app.controller('example',['$scope', function ($scope)
         {
            // Defining the keys & values
            $scope.name = "SIMPLY LEARNING";
            $scope.name2 = "";
            $scope.name3 = {"name": "tutorialsPoint"};

            $scope.isString = angular.isString($scope.name) == true
                ? "$scope.name is a String."
                : "$scope.name is not a String.";

            $scope.isString1 = angular.isString($scope.name2) == true
               ? "$scope.name2 is a String."
               : "$scope.name2 is not a String.";

            $scope.isString2 = angular.isString ($scope.name3) == true
               ? "$scope.name2 is a String."
               : "$scope.name2 is not a String.";
         }]);
      </script>
   </body>
</html>
To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.
Observe that name and name2 are strings, whereas name3 is a key-value pair in the given code, which is why we got the output "$scope.name2 is not a String."
GATE | GATE CS 1997 | Question 21 - GeeksforGeeks

25 Oct, 2018
The correct matching for the following pairs is
(A) Disk Scheduling        (1) Round robin
(B) Batch Processing       (2) SCAN
(C) Time sharing           (3) LIFO
(D) Interrupt processing   (4) FIFO

Codes:
    A   B   C   D
a   3   4   2   1
b   4   3   2   1
c   2   4   1   3
d   3   4   3   2

(A) a(B) b(C) c(D) dAnswer: (C)Explanation: Round-Robin is also called Time-sharing.
Disk Scheduling Algorithms are used to reduce the total seek time of any request. SCAN is one of the Algorithms.
Interrupt processing is LIFO because when we are processing an interrupt, we disable the interrupts originating from lower priority devices so lower priority interrupts cannot be raised. If an interrupt is detected then it means that it has higher priority than currently executing interrupt so this new interrupt will preempt the current interrupt so, LIFO.
Batch processing – FIFOQuiz of this Question
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE-IT-2004 | Question 71
MySQL Tryit Editor v1.0

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
YAML - Block Styles

YAML includes two block scalar styles: literal and folded. Block scalars are controlled with few indicators with a header preceding the content itself. An example of block scalar headers is given below −
%YAML 1.2
---
!!seq [
   !!str "literal\n",
   !!str "·folded\n",
   !!str "keep\n\n",
   !!str "·strip",
]
The output in JSON format with a default behavior is given below −
[
   "literal\n", 
   "\u00b7folded\n", 
   "keep\n\n", 
   "\u00b7strip"
]

There are four types of block styles: literal, folded, keep and strip styles. These block styles are defined with the help of Block Chomping scenario. An example of block chomping scenario is given below −
%YAML 1.2
---
!!map {
   ? !!str "strip"
   : !!str "# text",
   ? !!str "clip"
   : !!str "# text\n",
   ? !!str "keep"
   : !!str "# text\n",
}

You can see the output generated with three formats in JSON as given below −
{
   "strip": "# text", 
   "clip": "# text\n", 
   "keep": "# text\n"
}

Chomping in YAML controls the final breaks and trailing empty lines which are interpreted in various forms.
In this case, the final line break and empty lines are excluded for scalar content. It is specified by the chomping indicator “-“.
Clipping is considered as a default behavior if no explicit chomping indicator is specified. The final break character is preserved in the scalar’s content. The best example of clipping is demonstrated in the example above. It terminates with newline “\n” character.
Keeping refers to the addition with representation of “+” chomping indicator. Additional lines created are not subject to folding. The additional lines are not subject to folding.

    33 Lectures 
     44 mins

 Tarun Telang
 Print
 Add Notes
 Bookmark this page
Get the range of elements in a C# list

Use the GetRange() method to get the range of elements −
Firstly, set a list and add elements −
List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
Now, under a new list get the range of elements between index 1 and 3 −
List<int> myList = arr1.GetRange(1, 3);
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Getting elements between a range...");
      List<int> myList = arr1.GetRange(1, 3);
      foreach (int res in myList) {
         Console.WriteLine(res);
      }
   }
}
Initial List ...
10
20
30
40
50
Getting elements between a range...
20
30
40
Sending message through WhatsApp in android?

This example demonstrate about sending message through WhatsApp 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"
   android:orientation = "vertical"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:text = "click"
      android:textSize = "30sp" />
</LinearLayout>
In the above code, we have taken text view.
Step 3 − Add the following code to src/MainActivity.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   TextView textView;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            PackageManager pm = MainActivity.this.getPackageManager();
         try {
            Intent waIntent = new Intent(Intent.ACTION_SEND);
            waIntent.setType("text/plain");
            String text = "YOUR TEXT HERE";
            PackageInfo info = pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
            waIntent.setPackage("com.whatsapp");
            waIntent.putExtra(Intent.EXTRA_TEXT, text);
            startActivity(Intent.createChooser(waIntent, "Share with"));
         } catch (PackageManager.NameNotFoundException e) {
               Toast.makeText(MainActivity.this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
               .show();
            }
         }
      });
   }
}
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 –
Now click on textview to open whatsApp
How to handle Java Array Index Out of Bounds Exception?

Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 9. Then the valid expressions to access the elements of this array will be a[0] to a[8] (length-1).
Whenever you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.
For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.
import java.util.Arrays;
import java.util.Scanner;

public class AIOBSample {
   public static void main(String args[]) {
      int[] myArray = {897, 56, 78, 90, 12, 123, 75};
      System.out.println("Elements in the array are:: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element ::");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}
But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.
Elements in the array are::
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element ::
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at AIOBSample.main(AIOBSample.java:12)
You can handle this exception using try catch as shown below.
import java.util.Arrays;
import java.util.Scanner;

public class AIOBSampleHandled {
   public static void main(String args[]) {
      int[] myArray = {897, 56, 78, 90, 12, 123, 75};
      System.out.println("Elements in the array are:: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element ::");
      try {
         int element = sc.nextInt();
         System.out.println("Element in the given index is :: "+myArray[element]);
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("The index you have entered is invalid");
         System.out.println("Please enter an index number between 0 and 6");
      }
   }
}
Elements in the array are::
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element ::
7
The index you have entered is invalid
Please enter an index number between 0 and 6
Java Program to count all vowels in a string

Let’s say the following is our string.
String str = "!Demo Text!";
To count vowels, loop through each every character and check for any of the vowel i.e.
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
++vowelsCount;
}
The variable “vowelsCount” will give the count of all vowels.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str = "!Demo Text!";
      int vowelsCount = 0;
      for(char c : str.toCharArray()) {
         c = Character.toLowerCase(c);
         if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            ++vowelsCount;
         }
      }
      System.out.println("String "+str+" has "+ vowelsCount + " vowels.");
   }
}
String !Demo Text! has 3 vowels.
Python Tricks for Competitive Coding

Python is one of the preferred languages among coders for most of the competitive programming challenges. Most of the problems are easily computed in a reasonable time frame using python.
For some of the complex problem, writing fast-enough python code is often a challenge. Below are some of the pythonic code constructs that help to improve the performance of your code in competitive coding −
1. Strings concatenation: Do not use the below construct.
str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
for x in some_list:
   str1 += x
print(str1)
Above method gives huge time overhead.Instead, try to use this (join method) −
str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
print(str1.join(some_list))
2. The Map function
Generally, you have an input in competitive coding, something like −
1234567
To get them as a list of numbers simply
list(map (int, input().split()))
Always use the input() function irrespective of the type of input and then convert it using the map function.
>>> list(map(int, input("enter numbers:").split()))
enter numbers:1 2 3 4 5 6 7
[1, 2, 3, 4, 5, 6, 7]
>>>
The map function is one of the beautiful in-built function of python, which comes handy many times. Worth knowing.
3. Collections module
In case we want to remove duplicates from a list. While in other languages like Java you may have to use HashMap or any other freaky way, however, in pytho it's simply
>>> print(list(set([1,2,3,4,3,4,5,6])))
[1, 2, 3, 4, 5, 6]
Also, be careful to use extend() and append() in lists, while merging two or more lists.
>>> a = [1, 2, 3,4] # list 1
>>> b = [5, 6, 7] # list 2
>>> a.extend(b)#gives one list
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.append(b) # gives list of list
>>> a
[1, 2, 3, 4, [5, 6, 7]]
4. Language constructs
It's better to write your code within functions, although the procedural code is supported in Python.
def main():
   for i in range(2**3):
      print(x)
main()
is much better than
for x in range(2**3):
   print(x)
It is faster to store local variables than globals because of the underlying Cpython implementation.
5. Use the standard library:
It’s better to use built-in functions and standard library package as much as possible. There, instead of −
newlist = []
for x in somelist:
   newlist.append(myfunc(x))
Use this −
newlist = map(myfunc, somelist)
Likewise, try to use the itertools(standard library), as they are much faster for a common task. For example, you can have something like permutation for a loop with a few lines of code.
>>> import itertools
>>> iter = itertools.permutations(["a","b","c"])
>>> list(iter)
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
6. Generators
Generators are excellent constructs to reduce both, the memory footprint and the average time complexity of the code you’ve written.
def fib():
   a, b = 0, 1
   while 1:
      yield a
      a, b = b, a+b
Check if a directory is not empty in Java

The method java.io.File.list() is used to obtain the list of the files and directories in the specified directory defined by its path name. This list of files is stored in a string array. If the length of this string array is greater than 0, then the specified directory is not empty. Otherwise, it is empty.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File directory = new File("C:\\JavaProgram");
      if (directory.isDirectory()) {
         String[] files = directory.list();
         if (directory.length() > 0) {
            System.out.println("The directory " + directory.getPath() + " is not empty");
         } else {
            System.out.println("The directory " + directory.getPath() + " is empty");
         }
      }
   }
}
The output of the above program is as follows −
The directory C:\JavaProgram is not empty
Now let us understand the above program.
The method java.io.File.list() is used to obtain the list of the files and directories in the directory "C:\\JavaProgram". Then this list of files is stored in a string array files[]. If the length of this string array is greater than 0, then the specified directory is not empty is this is printed. Otherwise, it is empty is that is printed. A code snippet that demonstrates this is given as follows −
File directory = new File("C:\\JavaProgram");
if (directory.isDirectory()) {
   String[] files = directory.list();
   if (directory.length() > 0) {
      System.out.println("The directory " + directory.getPath() + " is not empty");
   } else {
      System.out.println("The directory " + directory.getPath() + " is empty");
   }
}
Tryit Editor v3.7

Tryit: Audio with autoplay
How to match multiple criteria inside an array with MongoDB?

To match multiple criteria inside an array, use aggregate(). Let us create a collection with documents −
> db.demo84.insertOne({
...    "EmployeeDetails": [
...       {Name: 'John', Salary:45000, isMarried: true},
...       {Name: 'Chris', Salary:50000, isMarried: false}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c0a3471bf0181ecc422a5")
}
> db.demo84.insertOne({
...    "EmployeeDetails": [
...       {Name: 'Sam', Salary:56000, isMarried: false},
...       {Name: 'Bob', Salary:50000, isMarried: false}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c0a4071bf0181ecc422a6")
}
Display all documents from a collection with the help of find() method −
> db.demo84.find();
This will produce the following output −
{
   "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
      { "Name" : "John", "Salary" : 45000, "isMarried" : true },
      { "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
   ]
}
{
   "_id" : ObjectId("5e2c0a4071bf0181ecc422a6"), "EmployeeDetails" : [
      { "Name" : "Sam", "Salary" : 56000, "isMarried" : false },
      { "Name" : "Bob", "Salary" : 50000, "isMarried" : false }
   ]
}
Following is the query to match multiple criteria inside an array −
> db.demo84.aggregate(
...    { "$match": {
...       "EmployeeDetails": {
...          "$elemMatch": {
...             "Name": "Chris",
...          "isMarried": false
...          }
...       }
...    }}
... );
This will produce the following output −
{
   "_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
      { "Name" : "John", "Salary" : 45000, "isMarried" : true },
      { "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
   ] 
}
Material - Notification Icons

This chapter explains the usage of Google's (Material) Notification icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
		
      <style>
         i.custom {font-size: 2em; color: green;}
      </style>
		
   </head>
	
   <body>
      <i class = "material-icons custom">accessibility</i>
   </body>
	
</html>
The following table contains the usage and results of Google's (Material) Notification icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Maximum Subarray in Python

Suppose we have an integer array A. We have to find the contiguous subarrays which length will be at least one, and that has the largest sum, and also return its sum. So if the array A is like A = [-2,1,-3,4,-1,2,1,-5,4], then the sum will be 6. And the subarray will be [4, -1, 2, 1]
To solve this we will try to use the Dynamic programming approach.
define an array dp same as the size of A, and fill it with 0
dp[0] := A[0]
for i = 1 to the size of A – 1dp[i] := maximum of dp[i – 1] + A[i] and A[i]
dp[i] := maximum of dp[i – 1] + A[i] and A[i]
return max in dp
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def maxSubArray(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      dp = [0 for i in range(len(nums))]
      dp[0] = nums[0]
      for i in range(1,len(nums)):
         dp[i] = max(dp[i-1]+nums[i],nums[i])
      #print(dp)
      return max(dp)
nums = [-2,1,-3,7,-2,2,1,-5,4]
ob1 = Solution()
print(ob1.maxSubArray(nums))
nums = [-2,1,-3,7,-2,2,1,-5,4]
8
How to use a click() method in Selenium with python?

While working on an application and navigating to different pages or different sections of a page, we need to click on various UI elements on a page like a link or a button. All these are performed with the help of click() method.
Thus a click() method typically works with elements like buttons and links.
driver.find_element_by_xpath("//button[id ='value']").click()
Coding Implementation with click() method for clicking a link.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link then using click() method
driver.find_element_by_link_text("Company").click()
#to close the browser
driver.close()
Coding Implementation with click() method for clicking a button.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the button then using click() method
driver.find_element_by_xpath("//button[contains(@class,'gsc-search')]") .click()
#to close the browser
driver.close()
Set Up Virtual Environment in Julia With Playground.jl | by Emmett Boudreau | Towards Data Science

There are over a billion reasons why you would want to use a virtual environment when working on a project in any language, and that sentiment is no different in Julia. Developing web-apps can be catastrophic when working with a team without a virtual environment. Fortunately, Julia has a package virtualization tool equivalent to virtual/pipenv called Playground.jl.
Before we can use Playground, of course we need to set it up. If you haven’t added the package yet, you can do it with:
julia> using Pkgjulia> Pkg.add("Playground")
Interestingly, this didn’t work for me, so I ended up switching to the Pkg REPL by simply pressing ], and then adding it through the URL, like this:
julia> ]pkg> add https://github.com/rofinn/Playground.jl   Cloning git-repo `https://github.com/rofinn/Playground.jl`  Updating git-repo `https://github.com/rofinn/Playground.jl`[ Info: Assigning UUID f8d4ef19-13c9-5673-8ace-5f74ae9cf246 to Playground Resolving package versions... Installed Syslogs ─ v0.3.0 Installed Memento ─ v0.12.1  Updating `~/.julia/environments/v1.0/Project.toml`  [f8d4ef19] + Playground v0.0.0 #master (https://github.com/rofinn/Playground.jl)  Updating `~/.julia/environments/v1.0/Manifest.toml`  [f28f55f0] + Memento v0.12.1  [f8d4ef19] + Playground v0.0.0 #master (https://github.com/rofinn/Playground.jl)  [cea106d9] + Syslogs v0.3.0  Building Playground → `~/.julia/packages/Playground/AhsNg/deps/build.log`
Cool!
Building Playground for me also through an error, a Stacktrace: Pkg not defined error. To counter this, I had to first run:
ENV["PLAYGROUND_INSTALL"] = true
Then I had to build it with Pkg from the Julia REPL... I’m not sure why this is, but I imagine it has something to do with a Playground dependency.
Although this is not essential, I also added the following to my .bashrc file, as sometimes it will be required:
echo "PATH=~/.playground/bin/:$PATH" >> ~/.bashrc
Usage is relatively simple, however something to note is you might need to close and reopen your terminal for the bashrc file to echo the new command. To create our environment, we use playground create:
playground create --name example
You can also create an environment from a REQUIREMENTS:
playground create --requirements /path
If using DECLARE files you should make sure that DeclarativePackages.jl is already installed. We can activate our playground environment like this:
playground activate /path/to/your/playground
Also, playground saves the name of our environment, so we can use the name bash tag in our terminal.
playground activate --name example
In order to remove our environment, we’ll use rm.
playground rm [playground-name|julia-version] --dir /path
Also, we have playground list and playground clean.
playground listplayground clean
That’s the rundown! That’s about all there is to it, playground is pretty easy to use and not too in depth. So hopefully, with the lacking playground documentation resources, this was relatively valuable, and you now know how to create and manage virtual environments in Julia!
Program to find leaf and non-leaf nodes of a binary tree in Python

Suppose we have a binary tree, we have to find a list of two numbers where the first number is the count of leaves in the tree and the second number is the count of non-leaf nodes.
So, if the input is like
then the output will be (3, 2), as there are 3 leaves and 2 non-leaf nodes.
To solve this, we will follow these steps −
if n is null, thenreturn (0, 0)
return (0, 0)
if left of n is null and right of n is null, thenreturn (1, 0)
return (1, 0)
left := solve(left of n)
right := solve(right of n)
return (left[0] + right[0], 1 + left[1] + right[1])
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.val = data
      self.left = left
      self.right = right
class Solution:
   def solve(self, n):
      if not n:
         return 0, 0
      if not n.left and not n.right:
         return 1, 0
      left, right = self.solve(n.left), self.solve(n.right)
      return left[0] + right[0], 1 + left[1] + right[1]
ob = Solution()
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.right.left = TreeNode(10)
root.right.right = TreeNode(2)
print(ob.solve(root))
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.right.left = TreeNode(10)
root.right.right = TreeNode(2)
(3, 2)
Detecting the first non-repeating string in Array in JavaScript

Suppose, we have an array of strings like this where strings might contain duplicate characters −
const arr = ['54gdgdfe3', '434ffd', '43frdf', '43fdhnh', 'wgcxhjny', 'fsdf34'];
We are required to write a JavaScript function that takes in one such array and returns the very first element from the array that contains 0 duplicate characters. If there does not exist any such string, we should return false.
Therefore, let’s write the code for this function −
The code for this will be −
const arr = ['54gdgdfe3', '434ffd', '43frdf', '43fdhnh', 'wgcxhjny', 'fsdf34'];
const isUnique = str => {
   return str.split('').every(el => str.indexOf(el) === str.lastIndexOf(el));
};
const findUniqueString = arr => {
   for(let i = 0; i < arr.length; i++){
      if(isUnique(arr[i])){
         return arr[i];
      };
   };
   return false;
};
console.log(findUniqueString(arr));
The output in the console will be −
wgcxhjny
Java - String regionMatches() Method

This method has two variants which can be used to test if two string regions are equal.
Here is the syntax  of this method −
public boolean regionMatches(int toffset,
                             String other,
                             int ooffset,
                             int len)

Here is the detail of parameters −
toffset − the starting offset of the subregion in this string.
toffset − the starting offset of the subregion in this string.
other − the string argument.
other − the string argument.
ooffset − the starting offset of the subregion in the string argument.
ooffset − the starting offset of the subregion in the string argument.
len − the number of characters to compare.
len − the number of characters to compare.
It returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
It returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      String Str2 = new String("Tutorials");
      String Str3 = new String("TUTORIALS");

      System.out.print("Return Value :" );
      System.out.println(Str1.regionMatches(11, Str2, 0, 9));

      System.out.print("Return Value :" );
      System.out.println(Str1.regionMatches(11, Str3, 0, 9));
   }
}
This will produce the following result −
Return Value :true
Return Value :false


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Searching characters in a String in Java.

You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.
public class Test {
   public static void main(String args[]) {
      String str = new String("hi welcome to Tutorialspoint");
      int index = str.indexOf('w');
      System.out.println("Index of the letter w :: "+index);
   }
}
Index of the letter w :: 3
C# Program to get the difference between two dates

Use DateTime.Subtract to get the difference between two dates in C#.
Firstly, set two dates −
DateTime date1 = new DateTime(2018, 8, 27);
DateTime date2 = new DateTime(2018, 8, 28);
Use the Subtract method to get the difference −
TimeSpan t = date2.Subtract(date1);
The following is the complete code −
 Live Demo
using System;
using System.Threading;
using System.Diagnostics;
public class Demo {
   public static void Main() {
      DateTime date1 = new DateTime(2018, 8, 27);
      DateTime date2 = new DateTime(2018, 8, 28);
      // getting the difference
      TimeSpan t = date2.Subtract(date1);
      Console.WriteLine(t);
      Console.WriteLine("Days (Difference) = {0} ", t.TotalDays);
      Console.WriteLine("Minutes (Difference) = {0}", t.TotalMinutes);
   }
}
1.00:00:00
Days (Difference) = 1
Minutes (Difference) = 1440