code-rag-bench/online-tutorials huggingface dataset:
PHP Constructors and Destructors

In object oriented programming terminology, constructor is a method defined inside a class is called automatically at the time of creation of object. Purpose of a constructor method is to initialize the object. In PHP, a method of special name __construct acts as a constructor.
__construct ([ mixed $args = "" [, $... ]] ) : void
This example shows that constructor is automatically executed when object is declared
 Live Demo
<?php
class myclass{
   function __construct(){
      echo "object initialized";
   }
}
$obj=new myclass();
?>
This will produce following result. −
object initialized
Class properties are initialized by constructor with arguments
 Live Demo
<?php
class rectangle{
   var $height;
   var $width;
   function __construct($arg1, $arg2){
      $this->height=$arg1;
      $this->width=$arg2;
   }
   function show(){
      echo "Height=$this->height Width=$this->width";
   }
}
$obj=new rectangle(10,20);
$obj->show();
?>
This will produce following result. −
Height=10 Width=20
If the parent class has constructor defined in it, it can be called within child class's constructor by parent::__construct. However, if child class doesn't define a constructor, it inherits the same from is base class.
 Live Demo
<?php
class a{
   function __construct(){
      echo "this is a constructor of base class\n";
   }
}
class b extends a{
   function __construct(){
      parent::__construct();
      echo "this a constructor class b\n";
   }
}
class c extends a {
   //
}
$a=new a();
$b=new b();
$c=new c();
?>
This will produce following result. −
this is a constructor of base class
this is a constructor of base class
this a constructor class b
this is a constructor of base class
Destructor is a method automatically as soon as garbage collector fins that a particular object has no more references. In PHP, destructor method is named as __destruct. During shutdown sequence too, objects will be destroyed. Destructor method doesn't take any arguments, neither does it return any data type
 Live Demo
<?php
class myclass{
   function __construct(){
      echo "object is initialized\n";
   }
   function __destruct(){
      echo "object is destroyed\n";
   }
}
$obj=new myclass();
?>
This will show following result
object is initialized
object is destroyed
JQuery | unique() method - GeeksforGeeks

27 Apr, 2020
This unique() Method in jQuery is used to sorts an array of DOM elements, in place, with the duplicates removed.
Syntax:
jQuery.unique( array )

Parameters: The unique() method accepts only one parameter that is mentioned above and described below:
array : This parameter is the Array of DOM elements.
Return Value: It returns the sorted array of DOM elements after removing the duplicates.
Example 1: In this example, the unique() method removes duplicate elements from the array of divs.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | unique() method</title>   <script src="https://code.jquery.com/jquery-3.4.1.js"></script><style>    div {        color: blue;    }</style></head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | unique() method</h3>    <div></div>    <div class="geek"></div>    <div class="geek"></div>    <div class="geek"></div>    <div></div>    <script>    $(function () {                   var divs = $( "div" ).get();                  divs = divs.concat( $( ".geek" ).get() );        $( "div:eq(1)" ).text( "Sorts an array of DOM elements " + divs.length + " with the duplicates removed" );              divs = jQuery.unique( divs );        $( "div:eq(2)" ).text( "Sorts an array of DOM elements " + divs.length + " with the duplicates removed" )            .css( "color", "red" );    })    </script>  </body></html>                    
Output:
Example 2: In this example, the unique() method removes all duplicate elements from the array of p’s.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | unique() method</title>   <script src = "https://code.jquery.com/jquery-3.4.1.js">     </script>   </head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | unique() method</h3>    <p></p>    <p class="geek"></p>    <p></p>    <script>    $(function () {                   var ps = $( "p" ).get();        ps = jQuery.unique( ps );        $ UniqueSort (document getElementsByTagName ( "p".));        $( "p" ).text( "Sorts an array of DOM elements with the duplicates removed" )            .css( "color", "red" );    })    </script>  </body></html>                    
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Change data type of given numpy array

The Numpy array support a great variety of data types in addition to python's native data types. After an array is created, we can still modify the data type of the elements in the array, depending on our need. The two methods used for this purpose are array.dtype and array.astype
This method gives us the existing data type of the elements in the array. In the below example we declare an array and find its data types.
 Live Demo
import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)
Running the above code gives us the following result −
[ 21.23 13.1 52.1 8. 255. ]
float64
This method converts the existing array to a new array with desired data types.In the below example we take the given array and convert it to a variety of target data types.
 Live Demo
import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)
# Convert the array data type to int32
a_int = a.astype('int32')
print(a_int)
print(a_int.dtype)
# Convert the array data type to str
a_str = a.astype('str')
print(a_str)
print(a_str.dtype)
# Convert the array data type to complex
a_cmplx = a.astype('complex64')
print(a_cmplx)
print(a_cmplx.dtype)
Running the above code gives us the following result −
[ 21.23 13.1 52.1 8. 255. ]
float64
[ 21 13 52 8 255]
int32
['21.23' '13.1' '52.1' '8.0' '255.0']
<U32
[ 21.23+0.j 13.1 +0.j 52.1 +0.j 8. +0.j 255. +0.j]
complex64
Ext.js - Auto Layout

This is the default layout that decides the layout of the elements based on the number of elements.
Following is a simple syntax to use Auto layout.
layout: 'auto' 

Following is a simple example showing the usage of Auto layout.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.container.Container', {
               renderTo : Ext.getBody(),
               layout : 'auto',
               width : 600,
               
               items : [{
                  title: 'First Component',
                  html : 'This is First Component'
               },{ 
                  title: 'Second Component',
                  html : 'This is Second Component'
               },{ 
                  title: 'Third Component',
                  html : 'This is Third Component' 
               },{ 
                  title: 'Fourth Component',
                  html : 'This is Fourth Component'
               }]
            });
         });
      </script>
   </head>
   
   <body>
   </body>
</html>
The above program will produce the following result −
 Print
 Add Notes
 Bookmark this page
Groovy - keySet()

Obtain a Set of the keys in this Map.
Set keySet()

None.
Set of Keys.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] 
      println(mp.keySet()); 
   } 
}
When we run the above program, we will get the following result −
[TopicName, TopicDescription]


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to change ordinal X-axis label to text labels using ggplot2 in R?

A plot created with ordinal values on X-axis needs to be ordered for plotting, otherwise, the plot will have continuous values on the X-axis that includes ordinal values. If we want to convert those values to text then scale_x_discrete should be used with the number of breaks, these number of breaks are the actual number of labels we want to use in our plot.
Consider the below data frame −
x<-1:3
Quantity<-c(515,680,550)
df<-data.frame(x,Quantity)
library(ggplot2)
ggplot(df,aes(x,Quantity))+geom_point()
Plotting text labels on X-axis in place of numbers −
ggplot(df,aes(ordered(x),Quantity))+geom_point()+
+ scale_x_discrete(breaks = 1:3, labels=c("Small","Medium","Large"))+
+ xlab(NULL)
Check if it is possible to transform one string to another in Python

Suppose we have two strings s and t, t is in uppercase. We have to check whether we can convert s to t by performing following operations.
Convert some lowercase letters uppercase.
Remove all of the lowercase letters.
So, if the input is like s = "fanToM", t = "TOM", then the output will be True as we can change ‘o’ to ‘O’ then remove all other lowercase letters from s to make it t.
To solve this, we will follow these steps −
n := size of s, m := size of t
dp:= a matrix of size (m + 1)x(n + 1) and fill with False
dp[0, 0] := True
for i in range 0 to size of s - 1, dofor j in range 0 to size of t, doif dp[i, j] is True, thenif j < size of t and s[i] in uppercase is same as t[j], thendp[i + 1, j + 1] := Trueif s[i] is not in uppercase, thendp[i + 1, j] := True
for j in range 0 to size of t, doif dp[i, j] is True, thenif j < size of t and s[i] in uppercase is same as t[j], thendp[i + 1, j + 1] := Trueif s[i] is not in uppercase, thendp[i + 1, j] := True
if dp[i, j] is True, thenif j < size of t and s[i] in uppercase is same as t[j], thendp[i + 1, j + 1] := Trueif s[i] is not in uppercase, thendp[i + 1, j] := True
if j < size of t and s[i] in uppercase is same as t[j], thendp[i + 1, j + 1] := True
dp[i + 1, j + 1] := True
if s[i] is not in uppercase, thendp[i + 1, j] := True
dp[i + 1, j] := True
return dp[n, m]
Let us see the following implementation to get better understanding −
 Live Demo
def solve(s,t):
   n = len(s)
   m = len(t)
   dp= [[False for i in range(m+1)] for i in range(n+1)]
   dp[0][0] = True
   for i in range(len(s)):
      for j in range(len(t)+1):
         if dp[i][j] == True:
            if j < len(t) and (s[i].upper() == t[j]):
               dp[i + 1][j + 1] = True
            if s[i].isupper()==False:
               dp[i + 1][j] = True
   return dp[n][m]
s = "fanToM"
t = "TOM"
print(solve(s, t))
"fanToM", "TOM"
True
Basic calculator program using Java

A basic calculator is able to add, subtract, multiply or divide two numbers. This is done using a switch case. A program that demonstrates this is given as follows −
import java.util.Scanner;
public class Calculator {
   public static void main(String[] args) {
      double num1;
      double num2;
      double ans;
      char op;
      Scanner reader = new Scanner(System.in);
      System.out.print("Enter two numbers: ");
      num1 = reader.nextDouble();
      num2 = reader.nextDouble();
      System.out.print("\nEnter an operator (+, -, *, /): ");
      op = reader.next().charAt(0);
      switch(op) {
         case '+': ans = num1 + num2;
            break;
         case '-': ans = num1 - num2;
            break;
         case '*': ans = num1 * num2;
            break;
         case '/': ans = num1 / num2;
            break;
      default: System.out.printf("Error! Enter correct operator");
         return;
      }
      System.out.print("\nThe result is given as follows:\n");
      System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
   }
}
Enter two numbers: 10.0 7.0
Enter an operator (+, -, *, /): -
The result is given as follows:
10.0 - 7.0 = 3.0
Now let us understand the above program.
The two numbers as well as the operator is acquired from the user. The code snippet that demonstrates this is given as follows −
double num1;
double num2;
double ans;
char op;
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("\nEnter an operator (+, -, *, /): ");
op = reader.next().charAt(0);
A switch case is used to perform the specified operation on the two numbers. If the operator entered is incorrect, an error message is displayed. The code snippet that demonstrates this is given as follows −
switch(op) {
   case '+': ans = num1 + num2;
      break;
   case '-': ans = num1 - num2;
      break;
   case '*': ans = num1 * num2;
      break;
   case '/': ans = num1 / num2;
      break;
default: System.out.printf("Error! Enter correct operator");
return;
}
Finally, the result is printed. The code snippet that demonstrates this is given as follows −
System.out.print("\nThe result is given as follows:\n");
System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
Python - Sentiment Analysis

Semantic Analysis is about analysing the general opinion of the audience. It may be a reaction to a piece of news, movie or any a tweet about some matter under discussion. Generally, such reactions are taken from social media and clubbed into a file to be analysed through NLP. We will take a simple case of defining positive and negative words first. Then taking an approach to analyse those words as part of sentences using those words. We use the sentiment_analyzer module from nltk. We first carry out the analysis with one word and then with paired words also called bigrams. Finally, we mark the words with negative sentiment as defined in the mark_negation function.
import nltk
import nltk.sentiment.sentiment_analyzer 

# Analysing for single words
def OneWord(): 
	positive_words = ['good', 'progress', 'luck']
   	text = 'Hard Work brings progress and good luck.'.split()                 
	analysis = nltk.sentiment.util.extract_unigram_feats(text, positive_words) 
	print(' ** Sentiment with one word **\n')
	print(analysis) 

# Analysing for a pair of words	
def WithBigrams(): 
	word_sets = [('Regular', 'fit'), ('fit', 'fine')] 
	text = 'Regular excercise makes you fit and fine'.split() 
	analysis = nltk.sentiment.util.extract_bigram_feats(text, word_sets) 
	print('\n*** Sentiment with bigrams ***\n') 
	print analysis

# Analysing the negation words. 
def NegativeWord():
	text = 'Lack of good health can not bring success to students'.split() 
	analysis = nltk.sentiment.util.mark_negation(text) 
	print('\n**Sentiment with Negative words**\n')
	print(analysis) 
    
OneWord()
WithBigrams() 
NegativeWord() 

When we run the above program we get the following output −
 ** Sentiment with one word **

{'contains(luck)': False, 'contains(good)': True, 'contains(progress)': True}

*** Sentiment with bigrams ***

{'contains(fit - fine)': False, 'contains(Regular - fit)': False}

**Sentiment with Negative words**

['Lack', 'of', 'good', 'health', 'can', 'not', 'bring_NEG', 'success_NEG', 'to_NEG', 'students_NEG']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Array.FindAll() Method in C#

The Array.FindAll() method in C# is used to retrieve all the elements that match the conditions defined by the specified predicate.
Following is the syntax −
public static T[] FindAll<T> (T[] array, Predicate<T> match);
Let us now see an example to implement the Array.FindAll() method −
using System;
public class Demo{
   public static void Main(){
      Console.WriteLine("Array elements...");
      string[] arr = { "car", "bike", "truck", "bus"};
      for (int i = 0; i < arr.Length; i++){
         Console.Write("{0} ", arr[i]);
      }
      Console.WriteLine();
      String[] res = Array.FindAll(arr, ele => ele.StartsWith("b",
      StringComparison.Ordinal));
      Console.Write("\nAll Searched elements...\n");
      for (int i = 0; i < res.Length; i++) {
         Console.WriteLine("{0}", res[i]);
      }
      Console.WriteLine();
   }
}
This will produce the following output −
Array elements...
car bike truck bus
All Searched elements...
bike
bus
What is the jQuery Event for user pressing enter in a textbox?

The jQuery event for user pressing enter is keyup and keyCode. You can try to run the following code to trigger an event on pressing enter key in textbox,
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $('input').bind("enterKey",function(e){
     alert("Enter key pressed");
   });
   $('input').keyup(function(e){
     if(e.keyCode == 13)
     {
        $(this).trigger("enterKey");
     }
   });
});
</script>
</head>
<body>
<input type="text">  
<p>Press Enter key in the above input text.</p>
</body>
</html>
When to use extern in C/C++

External variables are also known as global variables. These variables are defined outside the function and are available globally throughout the function execution. The “extern” keyword is used to declare and define the external variables.
The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.
The following is the syntax of extern.
extern datatype variable_name; // variable declaration using extern
extern datatype func_name(); // function declaration using extern
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
func_name − The name of function.
The following is an example of extern:
 Live Demo
#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
   extern int b;
   printf("The value of extern variables x and b : %d,%d\n",x,b);
   x = 15;
   printf("The value of modified extern variable x : %d\n",x);
   return 0;
}
The value of extern variables x and b : 32,8
The value of modified extern variable x : 15
In the above program, two variables x and b are declared as global variables.
extern int x = 32;
int b = 8;
In the main() function, variable is referred as extern and values are printed.
extern int b;
printf("The value of extern variables x and b : %d,%d\n",x,b);
x = 15;
printf("The value of modified extern variable x : %d\n",x);
jQuery | bind() with Examples

12 Feb, 2019
The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs.Syntax:
$(selector).bind(event, data, function);

Parameter: It accepts three parameters that are specified below-
event: This is an event type which is passed to the selected elements.data: This is the data which can be shown over the selected elements.function: This is the function which is perform by the selected elements.
event: This is an event type which is passed to the selected elements.
data: This is the data which can be shown over the selected elements.
function: This is the function which is perform by the selected elements.
Return Value: It returns all the modification made on the selected element.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/              jquery/3.3.1/jquery.min.js"></script>    <script>        $(document).ready(function() {            $("p").bind("click", function() {                alert("Given paragraph was clicked.");            });        });    </script>    <style>        p {            display: block;            padding: 50px;            width: 280px;            border: 2px solid green;        }    </style></head>  <body>    <p>Click me!</p></body>  </html>
Output:Before clicking the “Click me” box-After clicking the “Click me” box-
Code #2:In the below code, same “click” event is added but this time data is also passed to this method.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/          jquery/3.3.1/jquery.min.js"></script>    <script>        function handlerName(e) {            alert(e.data.msg);        }        <!--Here data is passing along with a function in             bind method-->        $(document).ready(function() {            $("p").bind("click", {                msg: "You just clicked the paragraph!"            }, handlerName)        });    </script>    <style>        p {            display: block;            padding: 50px;            width: 280px;            border: 2px solid green;        }    </style></head>  <body>    <!--A pop will appear after clicking on this paragraph-->    <p>Click me!</p></body>  </html>
Output:Before clicking the “Click me” box-After clicking the “Click me” box-
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PrintStream print(String) method in Java with Examples

29 Jan, 2019
The print(String) method of PrintStream Class in Java is used to print the specified String value on the stream. This String value is taken as a parameter.
Syntax:
public void print(String StringValue)
Parameters: This method accepts a mandatory parameter StringValue which is the String value to be written on the stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of print(String) method:
Program 1:
// Java program to demonstrate// PrintStream print(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintStream instance            PrintStream stream                = new PrintStream(System.out);              // Print the String value 'GeeksForGeeks'            // to this stream using print() method            // This will put the StringValue in the            // stream till it is printed on the console            stream.print("GeeksForGeeks");              stream.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GeeksForGeeks

Program 2:
// Java program to demonstrate// PrintStream print(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintStream instance            PrintStream stream                = new PrintStream(System.out);              // Print the String value 'GFG'            // to this stream using print() method            // This will put the StringValue in the            // stream till it is printed on the console            stream.print("GFG");              stream.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GFG

Java-Functions
Java-IO package
Java-PrintStream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strcspn() in C

23 Dec, 2017
The C library function strcspn() calculates the length of the number of characters before the 1st occurrence of character present in both the string.Syntax :
strcspn(const char *str1, const char *str2)

Parameters:
str1 : The Target string in which search has to be made.
str2 : Argument string containing characters
to match in target string.

Return Value:
This function returns the number of characters before the 1st occurrence
of character present in both the string.

// C code to demonstrate the working of// strcspn()#include <stdio.h>#include <string.h>  int main(){      int size;      // initializing strings    char str1[] = "geeksforgeeks";    char str2[] = "kfc";      // using strcspn() to calculate initial chars    // before 1st matching chars.    // returns 3    size = strcspn(str1, str2);      printf("The unmatched characters before first matched character :  %d\n", size);}
Output:
The unmatched characters before first matched character :  3

Practical Application : There can be many practical application of this function, be it word games or irregularity calculator. A simple word game is demonstrated in this article.
Rules : According to this game, 2 players play and one player initially generated a string and is asked to produce a string which has as many unmatched characters. After 1 round, player producing string with maximum unmatched characters wins.
// C code to demonstrate the application of// strcspn()  #include <stdio.h>#include <stdlib.h>#include <string.h>  int main(){      int score1 = 0, score2 = 0, k = 0, sizen = 0, size = 0;      // initial Round1 strings    char player1[] = "geeks";    char play2[] = "";      while (1) {        // generating random character        char randoml = 'a' + (random() % 26);        play2[k++] = randoml;          size = strcspn(play2, player1);          if (size == sizen) {            // if the character is present, break            score2 = size;            break;        }        else {            sizen = size;        }    }      // initial Round2 strings    const char player2[] = "geeks";    char play1[] = "";    k = 0, sizen = 0;      while (1) {        // generating random character        char randoml = 'a' + (random() % 26);        play1[k++] = randoml;          size = strcspn(play1, player2);          if (size == sizen) {              // if the character is present, break            score1 = size;            break;        }        else {            sizen = size;        }    }      if (score1 > score2)        printf("Player 1 won!! Score : %d", score1);    else if (score2 > score1)        printf("Player 2 won!! Score : %d", score2);    else        printf("Match Drawn!! Score : %d", score1);}
Output:
Match Drawn!! Score : 2

C Language
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check whether the vowels in a string are in alphabetical order or not in Python

Suppose we have a string s. We have to check whether the vowels present in s are in alphabetical order or not.
So, if the input is like s = "helloyou", then the output will be True as vowels are e, o, o, u all are in alphabetical order.
To solve this, we will follow these steps −
character := character whose ASCII is 64
for i in range 0 to size of s - 1, doif s[i] is any one of ('A','E','I','O','U','a','e','i','o','u'), thenif s[i] < character, thenreturn Falseotherwise,character := s[i]
if s[i] is any one of ('A','E','I','O','U','a','e','i','o','u'), thenif s[i] < character, thenreturn Falseotherwise,character := s[i]
if s[i] < character, thenreturn False
return False
otherwise,character := s[i]
character := s[i]
return True
Let us see the following implementation to get better understanding −
Live Demo
def solve(s):
   character = chr(64)

   for i in range(len(s)):
      if s[i] in ['A','E','I','O','U','a','e','i','o','u']:
         if s[i] < character:
           return False
         else:
           character = s[i]
 
   return True

s = "helloyou"
print(solve(s))
"helloyou"
True
Convert day of year to day of month in Java

Firstly, set the day of year using DAY_OF_YEAR constant.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2018);
cal.set(Calendar.DAY_OF_YEAR, 320);
Now, get the day of month −
int res = cal.get(Calendar.DAY_OF_MONTH);
The following is an example −
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.YEAR, 2018);
      cal.set(Calendar.DAY_OF_YEAR, 320);
      System.out.println("Date = " + cal.getTime());
      int res = cal.get(Calendar.DAY_OF_MONTH);
      System.out.println("Day of month = " + res);
   }
}
Date = Fri Nov 16 07:54:55 UTC 2018
Day of month = 16
How to remove white spaces only beginning/end of a string using PHP ? - GeeksforGeeks

02 Jun, 2020
We have given a string and the task is to remove white space only from beginning of a string or end from a string str in PHP. In order to do this task, we have the following methods in PHP:
Method 1: Using ltrim() Method: The ltrim() method is used to strip whitespace only from the beginning of a string.
Syntax:
ltrim($string, $charlist)

Example :
PHP
<?php// PHP program to remove white space// from beginning of a string     $str = "  Geeks  for  Geeks   ";     // Using ltrim() function // removes whitespaces from // beginning of a string $str = ltrim($str);  // Printing the resultecho $str;   $len = strlen($str);  echo "\nLength of String: ";  echo $len;?>
Geeks  for  Geeks   
Length of String: 20
Method 2: Using rtrim() Method: The rtrim() method is used to strip whitespace only from the end of a string.
Syntax:
rtrim($string, $charlist)

Example :
PHP
<?php// PHP program to remove white space// from the end of a string     $str = "  Geeks  for  Geeks   ";     // Using rtrim() function to// remove whitespaces from // end of a string $str = rtrim($str);  // Printing the resultecho $str;   $len = strlen($str); echo "\nLength of String : ";  echo $len;?>
  Geeks  for  Geeks
Length of String : 19
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
What is the difference between global and local Variables in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global Variables − A global variable has a global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
Here’s how you can declare a global variable
Live Demo
<html>
   <body onload = checkscope();>
      <script>
         <!--
            var myVar = "global"; // Declare a global variable
            function checkscope( ) {
               var myVar = "local";  // Declare a local variable
               document.write(myVar);
            }
         //-->
      </script>
   </body>
</html>
NumPy - Byte Swapping

We have seen that the data stored in the memory of a computer depends on which architecture the CPU uses. It may be little-endian (least significant is stored in the smallest address) or big-endian (most significant byte in the smallest address).
The numpy.ndarray.byteswap() function toggles between the two representations: bigendian and little-endian.
import numpy as np 
a = np.array([1, 256, 8755], dtype = np.int16) 

print 'Our array is:' 
print a  

print 'Representation of data in memory in hexadecimal form:'  
print map(hex,a)  
# byteswap() function swaps in place by passing True parameter 

print 'Applying byteswap() function:' 
print a.byteswap(True) 

print 'In hexadecimal form:' 
print map(hex,a) 
# We can see the bytes being swapped
It will produce the following output −
Our array is:
[1 256 8755]

Representation of data in memory in hexadecimal form:
['0x1', '0x100', '0x2233']

Applying byteswap() function:
[256 1 13090]

In hexadecimal form:
['0x100', '0x1', '0x3322']


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to return local variables from a function in C++ - GeeksforGeeks

17 Jun, 2021
The following article discusses the way to return a local variable created inside a function, which can be done by returning a pointer to the variable from the called function to the caller function.
What happens when you try to return a local variable as usual?
For example, in the following code, when the array is created inside a function and returned to the caller function, it throws a runtime error as the array was created in the stack memory, and therefore it is deleted once the function ends.
C++
#include <bits/stdc++.h>using namespace std;  // Function to return an// arrayint* fun(){    int arr[5] = { 1, 2, 3, 4, 5 };    return arr;}// Driver Codeint main(){      int* arr = fun();    // Will cause error    cout << arr[2];      return 0;}
Output
Segmentation Fault (SIGSEGV)
How to return a local variable from a function?
But there is a way to access the local variables of a function using pointers, by creating another pointer variable that points to the variable to be returned and returning the pointer variable itself.
Returning a local variable:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;  // Function to return// a pointerint* fun(){    int x = 20;    int* ptr = &x;    return ptr;}// Driver Codeint main(){      int* arr = fun();    cout << *arr;    return 0;}
20
Returning an array:
C++
#include <bits/stdc++.h>using namespace std;  // Function to return an// arrayint* fun(){    int arr[5] = { 1, 2, 3, 4, 5 };    int *ptr = arr;    return ptr;}// Driver Codeint main(){      int* arr = fun();    cout << arr[2];      return 0;}
3
Arrays
Functions
Pointers
C++
Arrays
Pointers
Functions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
C# Program to Check a Specified Type is an Array or Not - GeeksforGeeks

07 Jan, 2022
In C#, an array is a group of homogeneous elements that are referred to by a common name. So in this article, we will discuss how to check the variable is of array type or not. To do this task, we use the IsArray property of the Type class. This property is used to determine whether the specified type is an array or not. IsArray property will return true if the specified type is an array. Otherwise, it will return false. 
Syntax:
public bool IsArray{get;}
Return: It will return true if the value is an array otherwise false.
Approach
Import System.Reflection namespace.
Declare an array with a datatype of a size n.
Use IsArray is the method to check the type is array or not along with GetType() method. GetType() method method gets the type of the variable.
array.GetType().IsArray
If the condition is true then display “Type is array” or if the condition is false then display “Type is not array”.
Example 1: 
C#
// C# program to determine whether the// specified type is an array or notusing System;using System.Reflection; class GFG{     static void Main(){         // Declare an array with size 5    // of integer type    int[] array1 = new int[5];     // Check whether the variable is array or not    // Using IsArray property    if (array1.GetType().IsArray == true)    {        Console.WriteLine("Type is array");    }    else    {        Console.WriteLine("Type is not array");    }}}
Output:
Type is array
Example 2:
C#
// C# program to determine whether the// specified type is an array or notusing System;using System.Reflection; class GFG{     static void Main(){     // Declare and initializing variables    int array1 = 45;    string array2 = "GeeksforGeeks";    int[] array3 = new int[3];    double[] array4 = { 2.3, 4.5, 0.33 };     // Check whether the variable is of array type or not    // Using IsArray property    Console.WriteLine("Is the type of array1 variable is array?" +                      array1.GetType().IsArray);    Console.WriteLine("Is the type of array2 variable is array?" +                      array2.GetType().IsArray);    Console.WriteLine("Is the type of array2 variable is array?" +                      array3.GetType().IsArray);    Console.WriteLine("Is the type of array2 variable is array?" +                      array4.GetType().IsArray);}}
Is the type of array1 variable is array?False
Is the type of array2 variable is array?False
Is the type of array2 variable is array?True
Is the type of array2 variable is array?True

simmytarika5
surindertarika1234
varshagumber28
CSharp-Arrays-Programs
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Getting a Month Name Using Month Number in C#
Program to Print a New Line in C#
Socket Programming in C#
Program to find absolute value of a given number
How to create a Hoverable Sidenav with CSS?

Following is the code to create hoverable side navigation buttons with CSS.
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
nav a {
   position: fixed;
   left: -120px;
   transition: 0.3s;
   padding: 10px;
   width: 140px;
   text-decoration: none;
   font-size: 20px;
   color: black;
   font-weight: bolder;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
nav a:hover {
   left: 0;
}
#Info{
   top: 20px;
   background-color: #6de2f7;
}
#Social{
   top: 80px;
   background-color: #71fc71;
}
#Address {
   top: 140px;
   background-color: #c4f553;
}
#Home {
   top: 200px;
   background-color: rgb(225, 115, 240);
}
</style>
</head>
<body>
<nav>
<a href="#" id="Home">Home</a>
This will produce the following output:
On hovering on any one of them they will expland as follows:
<a href="#" id="Address">Address</a>
<a href="#" id="Social">Social Links</a>
<a href="#" id="Info">More Info</a>
</nav>
</body>
</html>
This will produce the following output −
On hovering on any one of them they will be explained as follows −
Tensorflow.js tf.metrics.meanAbsoluteError() Function - GeeksforGeeks

25 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.metrics.meanAbsoluteError() is used to calculate mean absolute error. The mean absolute error is defined as the mean of absolute difference of two tensors. Where, the mean is applied over feature dimensions. It takes two tensors as a parameter.
mean(abs(Prediction - True))
Syntax:
tf.metrics.meanAbsoluteError(Tensor1, Tensor2);
Parameters: 
Tensor1: It is the truth tensor.
Tensor2: It is the Prediction tensor.
Return Value: It returns the tensor of the mean absolute errors.
Example 1: In this example, we are giving two 1d tensors as a parameter, and the metrics.meanAbsoluteError function will calculate the mean absolute error and return a tensor.
Javascript
// Importing the tensorflow libraryimport * as tf from "@tensorflow/tfjs"  // Defining the value of the tensorsconst True = tf.tensor([1,2,3]);const Prediction = tf.tensor([3,2,1]);  // Calculating mean absolute errorconst error = tf.metrics.meanAbsoluteError(True, Prediction);  // Printing the tensorerror.print();
Output:
Tensor
    1.3333333730697632
Example 2: In this example, we are giving two 2d tensors as a parameter, and the metrics.meanAbsoluteError function will calculate the mean absolute error and return a tensor.
Javascript
// Importing the tensorflow libraryimport * as tf from "@tensorflow/tfjs"  // Defining the value of the tensorsconst True = tf.tensor([[1,2,3],[2,4,1]]);const Prediction = tf.tensor([[3,2,1],[5,2,1]]);  // Calculating mean absolute errorconst error = tf.metrics.meanAbsoluteError(True, Prediction);  // Printing the tensorerror.print();
Output:
Tensor
    [1.3333334, 1.6666667]
Reference:https://js.tensorflow.org/api/latest/#metrics.meanAbsoluteError
Picked
Tensorflow
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
C++ Unordered_map Library - find() Function

The C++ function std::unordered_map::find() finds an element associated with key k.
If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end().
Following is the declaration for std::unordered_map::find() function form std::unordered_map header.
iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

k − Key to be searched.
If object is constant qualified then method returns a constant iterator otherwise non-constant iterator.
Constant i.e. O(1) in average case.
Linear i.e. O(n) in worst case.
The following example shows the usage of std::unordered_map::find() function.
#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

   auto it = um.find('d');

   cout << "Iterator points to " << it->first
       << " = " << it->second << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Iterator points to d = 4

 Print
 Add Notes
 Bookmark this page
GATE-CS-2007 - GeeksforGeeks

02 Dec, 2021
P. f(x) is continuous for all real values of x
Q. f(x) is differentiable for all real values of x 
Consider an example set, S = (1,2,3)

Equivalence property follows, reflexive, symmetric
and transitive

Largest ordered set are s x s = 
{ (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) 
(3,3) } which are 9 which equal to 3^2 = n^2

Smallest ordered set are { (1,1) (2,2) ( 3,3)}
which are 3 and equals to n. number of elements.
No of inputs sequences possible for a n variable Boolean function = 2n

Each input sequence can give either T or F as output ( 2 possible values )

So, Total no of Boolean functions are -

2X2X2X2X2X2X.............X2X2X2X2X2X2

<-------------------- 2n Times -------------->

22n

Let G be the non-planar graph with the minimum possible number of edges. Then G has 
10 edges and 5 vertices  
10 edges and 6 vertices 
9 edges and 6 vertices 
9 edges and 5 vertices  
According to Kuratowski's Theorem, a graph is planar if and only if it does not contain any subdivisions of the graphs K5 or K3,3. That means K5 and K3,3 are minimum non-planar graphs. These graphs have 5 vertices with 10 edges in K5 and 6 vertices with 9 edges in K3,3 graph. So, graph K5 has minimum vertices and maximum edges than K3,3. Alternative method: A plane graph having ‘n’ vertices, cannot have more than ‘2*n-4’ number of edges. Hence using the logic we can derive that for 6 vertices, 8 edges is required to make it a plane graph. So adding one edge to the graph will make it a non planar graph. So, 6 vertices and 9 edges is the correct answer. So, option (B) is correct. 
A set is always regular if it is finite.
A set is always regular if a DFA/NFA can be drawn for it.
Here the number of sets = 128/4 = 32 (as it is 4 say set associative)

We have total 64 words then we need 6 bits to identify the word

So the line offset is 5 bits and the word offset is 6 bits

and the TAG = 20-(5+6) =9 bits

so it should be 9,5,6
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
How to check a checkbox in a page in Selenium with python?

We can check a checkbox in a page in Selenium with the help of click() method. First of all we need to uniquely identify the checkbox with the help of any of the locators like css, xpath, id, class and so on.
Next we have to use findElement() method to locate the element and finally perform the clicking action. The exception will be thrown if there is no matching element found on the page.
driver.find_element_by_xpath("//input[@name='check-box']")
Code Implementation for checkbox selection.
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/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the checkbox with xpath, then click
driver.find_element_by_xpath("//input[@value='Automation Tester']")
.click()
#to close the browser
driver.close()
Convert LinkedList to ArrayList in Java

A LinkedList can be converted into an ArrayList by creating an ArrayList such that the parameterized constructor of the ArrayList initialises it with the elements of the LinkedList.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Orange");
      l.add("Apple");
      l.add("Peach");
      l.add("Guava");
      l.add("Pear");
      List<String> aList = new ArrayList<String>(l);
      System.out.println("The ArrayList elements are: ");
    for (Object i : aList) {
         System.out.println(i);
      }
   }
}
The ArrayList elements are:
Orange
Apple
Peach
Guava
Pear
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
l.add("Pear");
An ArrayList aList is created and it is initialised using the elements of the LinkedList using a parameterized constructor. Then the ArrayList is displayed using a for loop. A code snippet which demonstrates this is as follows −
List<String> aList = new ArrayList<String>(l);
System.out.println("The ArrayList elements are: ");
for (Object i : aList) {
   System.out.println(i);
}