code-rag-bench/online-tutorials huggingface dataset:
How to Delete Tkinter Text Box's Contents?

Tkinter provides many functions and modules through which we can create fully
featured applications with buttons, dialogue boxes, widgets, and many more.
To create a text widget, we can use the tkinter entry widget function which is basically a constructor and it takes the window or frame of the tkinter. Further, we can delete the content of this text widget using the built-in method delete(first,
last=None) which basically takes a range within the textbox.
In this example, we will create a Delete Button which basically deletes all the
contents from the given text box.
from tkinter import *

win= Tk()
win.geometry("600x300")

label= Label(win, text= "Write something ??", font= ('Helvetica', 25))
label.pack(pady=20)

#Create a Text Widget
text= Text(win, height=10)
text.pack()

def delete():
   text.delete("1.0","end")

#Create a Delete Button to remove the Text from the text-widget

b1= Button(win, text= "Delete",command= delete)
b1.pack(pady=10)
win.mainloop()
Running the above code will create a text widget and a delete button which can be
used to delete the contents written in the text box.
Type something inside the textbox, and then, click the “Delete” button. It will erase
the content inside the textbox.
Bitwise ORs of Subarrays in C++

Suppose we have an array A of non-negative integers. For every (contiguous) subarray say B = [A[i], A[i+1], ..., A[j]] (with i <= j), we will do the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. We have to find the number of possible results. (Results that occur more than once are only counted once in the final answer.)
So if the input is like [1,1,2], then the result will be 3 as subarrays are [1], [1], [2], [1,1], [1,2], [1,1,2], then the results will be 1,1,2,1,3,3, then there are three distinct results.
To solve this, we will follow these steps −
Create two sets ret and curr2
Create two sets ret and curr2
for i in range 0 to size of arraymake a set curr1, insert A[i] into itfor each element e in curr2 −insert (e OR A[i]) into curr1for each element e curr1insert e in retcurr2 := curr1
for i in range 0 to size of array
make a set curr1, insert A[i] into it
make a set curr1, insert A[i] into it
for each element e in curr2 −insert (e OR A[i]) into curr1
for each element e in curr2 −
insert (e OR A[i]) into curr1
insert (e OR A[i]) into curr1
for each element e curr1insert e in ret
for each element e curr1
insert e in ret
insert e in ret
curr2 := curr1
curr2 := curr1
return size of ret
return size of ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int subarrayBitwiseORs(vector<int>& A) {
      unordered_set <int> ret;
      unordered_set <int> curr2;
      for(int i = 0; i < A.size(); i++){
         unordered_set <int> curr1;
         curr1.insert(A[i]);
         unordered_set<int>::iterator it = curr2.begin();
         while(it != curr2.end()){
            curr1.insert(*it | A[i]);
            it++;
         }
         it = curr1.begin();
         while(it != curr1.end()){
            ret.insert(*it);
            it++;
         }
         curr2 = curr1;
      }
      return ret.size();
   }
};
main(){
   vector<int> v = {1,1,2};
   Solution ob;
   cout << (ob.subarrayBitwiseORs(v));
}
[1,1,2]
3
Python - Sum only specific rows of a Pandas Dataframe

To sum only specific rows, use the loc() method. Mention the beginning and end row index using the : operator. Using loc(), you can also set the columns to be included. We can display the result in a new column.
At first, let us create a DataFrame. We have Product records in it, including the Opening and Closing Stock −
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})
Sum of some rows i.e. 1st two rows. Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock. We are displaying result in a new column “Sum_Result” −
dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1)
Following is the complete code −
import pandas as pd

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})

print"DataFrame...\n",dataFrame

# sum of some rows
# Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock
# displaying result in a new column Sum_Result
dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1)
print"\nSumming some rows...\n",dataFrame
This will produce the following output −
DataFrame...
   Closing_Stock   Opening_Stock   Product
0           200             300    SmartTV
1           500             700    ChromeCast
2          1000            1200    Speaker
3           900            1500    Earphone

Summing some rows...
   Closing_Stock   Opening_Stock   Product   Sum_Result
0           200             300    SmartTV       500.0
1           500             700    ChromeCast   1200.0
2          1000            1200    Speaker         NaN
3           900            1500    Earphone        NaN
Calculate range of data types using C++

In C++ we have different datatypes like int, char, double etc. In this section we will see how to get the size of them programmatically.
We can get the size of datatypes in byte, so we can simply multiply them into 8 to get the values in bits. Now we know that if the number of bits are n, then the minimum range will be – 2^(n-1), and maximum range will be 2^(n-1) – 1 for signed numbers. For unsigned numbers it will be 2^n – 1 as there are no negative numbers.
#include <iostream>
#include <cmath>
#define SIZE(x) sizeof(x) * 8 //Get the size in bits
using namespace std;
void getRange(string type, int n) {
   if(type.compare("SIGNED") == 0) { //for signed numbers calculate lower and upper limit
      int min = pow(2, n - 1);
      int max = pow(2, n - 1) - 1;
      cout << "Range from " << (-1) * min << " to " << max <<endl;
   }else{ //for signed numbers calculate limit from 0
      int range = pow(2, n )-1;
      cout << "Range from 0 to " << range << endl;
   }
}
int main() {
   cout << "For Signed int: ";
   getRange("SIGNED", SIZE(int));
   cout << "For Signed float: ";
   getRange("SIGNED", SIZE(float));
   cout << "For Unsigned int: ";
   getRange("UNSIGNED", SIZE(unsigned int));
   cout << "For Unsigned short: ";
   getRange("UNSIGNED", SIZE(unsigned short int));
   cout << "For Signed char: ";
   getRange("SIGNED", SIZE(char));
}
For Signed int: Range from -2147483648 to 2147483647
For Signed float: Range from -2147483648 to 2147483647
For Unsigned int: Range from 0 to -2147483648
For Unsigned short: Range from 0 to 65535
For Signed char: Range from -128 to 127
Node.js fs.readFile() Method

12 Oct, 2021
The fs.readFile() method is an inbuilt method which is used to read the file. This method read the entire file into buffer. To load the fs module we use require() method. For example: var fs = require(‘fs’); 
Syntax:  
fs.readFile( filename, encoding, callback_function )
Parameters: The method accept three parameters as mentioned above and described below:  
filename: It holds the name of the file to read or the entire path if stored at other location.
encoding: It holds the encoding of file. Its default value is ‘utf8’.
callback_function: It is a callback function that is called after reading of file. It takes two parameters:err: If any error occurred.data: Contents of the file.
err: If any error occurred.
data: Contents of the file.
Return Value: It returns the contents/data stored in file or error if any.Below examples illustrate the fs.readFile() method in Node.js:Example 1:  
javaScript
// Node.js program to demonstrate// the fs.readFile() method  // Include fs modulevar fs = require('fs');  // Use fs.readFile() method to read the filefs.readFile('Demo.txt', 'utf8', function(err, data){          // Display the file content    console.log(data);});  console.log('readFile called');
Output: 
readFile called
undefined
Explanation: The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.Example 2: 
javascript
// Node.js program to demonstrate// the fs.readFile() method  // Include fs modulevar fs = require('fs');  // Use fs.readFile() method to read the filefs.readFile('demo.txt', (err, data) => {    console.log(data); })
Output: 
undefined
Reference: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback 
simmytarika5
surindertarika1234
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Itertools.Permutations()

11 Jul, 2022
Itertool is a module provided by Python for creating iterators for efficient looping. It also provides various features or functions that work with iterators to produce complex iterators and help us to solve problems easily and efficiently in terms of time as well as memory. Itertools module provides us various ways to manipulate the sequence that we are traversing through. Different types of iterators provided by this module are:
Infinite Iterators
Iterators terminating on the shortest input sequence
Combinatoric Iterators
Note: For more information, refer to Python Itertools
Itertools.permutation() function falls under the Combinatoric Generators. The recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators. As understood by the word “Permutation” it refers to all the possible combinations in which a set or string can be ordered or arranged. Similarly here itertool.permutations() method provides us with all the possible arrangements that can be there for an iterator and all elements are assumed to be unique on the basis of there position and not by there value or category. All these permutations are provided in lexicographical order. The function itertool.permutations() takes an iterator and ‘r’ (length of permutation needed) as input and assumes ‘r’ as default length of iterator if not mentioned and returns all possible permutations of length ‘r’ each. Syntax:
Permutations(iterator, r)
Example 1:- 
Python3
from itertools import permutations  a = "GeEK" # no length entered so default length# taken as 4(the length of string GeEK)p = permutations(a) # Print the obtained permutationsfor j in list(p):  print(j)
Output :-
('G', 'e', 'E', 'K')
('G', 'e', 'K', 'E')
('G', 'E', 'e', 'K')
('G', 'E', 'K', 'e')
('G', 'K', 'e', 'E')
('G', 'K', 'E', 'e')
('e', 'G', 'E', 'K')
('e', 'G', 'K', 'E')
('e', 'E', 'G', 'K')
('e', 'E', 'K', 'G')
('e', 'K', 'G', 'E')
('e', 'K', 'E', 'G')
('E', 'G', 'e', 'K')
('E', 'G', 'K', 'e')
('E', 'e', 'G', 'K')
('E', 'e', 'K', 'G')
('E', 'K', 'G', 'e')
('E', 'K', 'e', 'G')
('K', 'G', 'e', 'E')
('K', 'G', 'E', 'e')
('K', 'e', 'G', 'E')
('K', 'e', 'E', 'G')
('K', 'E', 'G', 'e')
('K', 'E', 'e', 'G')
Time Complexity: O(n!) where n is the size of the string.Auxiliary Space: O(n*n!) 
Example 2:- 
Python3
from itertools import permutations   print ("All the permutations of the given list is:")print (list(permutations([1, 'geeks'], 2)))print() print ("All the permutations of the given string is:")print (list(permutations('AB')))print()   print ("All the permutations of the given container is:")print(list(permutations(range(3), 2)))
Output:-
All the permutations of the given list is:
[(1, 'geeks'), ('geeks', 1)]

All the permutations of the given string is:
[('A', 'B'), ('B', 'A')]

All the permutations of the given container is:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
pushpeshrajdx01
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.iloc

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.iloc attribute enables purely integer-location based indexing for selection by position over the given Series object.
Syntax:Series.iloc
Parameter : None
Returns : Series
Example #1: Use Series.iloc attribute to perform indexing over the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.iloc attribute to perform indexing over the given Series object.
# slice the object element in the # passed rangesr.iloc[0:2]
Output :
As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object. Example #2 : Use Series.iloc attribute to perform indexing over the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.iloc attribute to perform indexing over the given Series object.
# slice the object element in the # passed rangesr.iloc[1:3]
Output :As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
PyQt5 QSpinBox – Setting Maximum value

06 May, 2020
In this article we will see how we can set the maximum value i.e upper bound of the spin box, by default when we create a spin box it ranges from 0 to 99 i.e its maximum value is 99 although we can change this.
In order to do this we will use spin_box.setMaximum method
Syntax : spin_box.setMaximum(n)
Argument : It takes integer as argument
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 100, 40)          # setting maximum value        self.spin.setMaximum(5)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  window.show()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java String getChars() with examples

04 Feb, 2022
The java string getChars() method copies characters from the given string into the destination character array.Syntax:  
public void getChars(int srhStartIndex, 
int srhEndIndex, char[] destArray, int destStartIndex)     
Parameters:
srhStartIndex : Index of the first character in the string to copy. 
srhEndIndex : Index after the last character in the string to copy.
destArray : Destination array where chars will get copied.
destStartIndex : Index in the array starting from where the chars
                 will be pushed into the array.
Return: It does not return any value.
Exception: StringIndexOutOfBoundsException – If srhStartIndex, srhEndIndex are not in proper range.Example : To show working of getChars() method  
java
// Java program to demonstrate// working of getChars() method class Gfg1 {    public static void main(String args[])    {        String str = "Welcome! to GeeksforGeeks";         char[] destArray = new char[20];        try {            str.getChars(12, 25, destArray, 0);            System.out.println(destArray);        }        catch (Exception ex) {            System.out.println(ex);        }    }}
Output:  
GeeksforGeeks
 
java
// Java program to demonstrate// exception condition in// working of getChars() method class Gfg2 {    public static void main(String args[])    {        String str = "Welcome! to GeeksforGeeks";         char[] destArray = new char[20];        try {            // Starting index 0 and ending index 24            str.getChars(12, 26, destArray, 0);            System.out.println(destArray);        }        catch (Exception ex) {            System.out.println(ex);        }    }}
Output:  
java.lang.StringIndexOutOfBoundsException: String index out of range: 26
 
gulshankumarar231
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Introduction to Java
Initialize an ArrayList in Java
TimeZone getOffset() Method in Java with Examples

02 Jan, 2019
The getOffset() method of TimeZone class in Java is used to know the offset value of this TimeZone at a specific date from the UTC or the Universal Time Coordinated.
Syntax:
public int getOffset(long in_date)
Parameters: The method accepts one parameter, in_date of long type that refers to the actual date represented in milli-seconds since 1st January 1970 at 00:00:00 GMT.
Return Value: The method returns the ID of the TimeZone.
Below programs illustrate the working of getOffset() Method of TimeZone:Example 1:
// Java code to illustrate getOffset() method  import java.util.*;  public class TimeZoneDemo {    public static void main(String args[])    {          // Creating a TimeZone        TimeZone offtime_zone            = TimeZone.getTimeZone("Europe/Rome");          // Checking the offset for the systems date        System.out.println("The Offset Value is:"                           + offtime_zone                                 .getOffset(Calendar.ZONE_OFFSET));    }}
The Offset Value is:3600000

Example 2:
// Java code to illustrate getOffset() method  import java.util.*;  public class TimeZoneDemo {    public static void main(String args[])    {          // Creating a TimeZone        TimeZone offtime_zone            = TimeZone.getTimeZone("Pacific/Pago_Pago");          // Checking the offset for the systems date        System.out.println("The Offset Value is:"                           + offtime_zone                                 .getOffset(Calendar.ZONE_OFFSET));    }}
The Offset Value is:-39600000

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getOffset()
Java - util package
Java-Functions
Java-TimeZone
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
All-Pairs Shortest Paths

The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph.
At first the output matrix is same as given cost matrix of the graph. After that the output matrix will be updated with all vertices k as the intermediate vertex.
The time complexity of this algorithm is O(V3), here V is the number of vertices in the graph.
Input − The cost matrix of the graph.
0 3 6 ∞ ∞ ∞ ∞
3 0 2 1 ∞ ∞ ∞
6 2 0 1 4 2 ∞
∞ 1 1 0 2 ∞ 4
∞ ∞ 4 2 0 2 1
∞ ∞ 2 ∞ 2 0 1
∞ ∞ ∞ 4 1 1 0
Output − Matrix of all pair shortest path.
0 3 4 5 6 7 7
3 0 2 1 3 4 4
4 2 0 1 3 2 3
5 1 1 0 2 3 3
6 3 3 2 0 2 1
7 4 2 3 2 0 1
7 4 3 3 1 1 0
Input − The cost matrix of given Graph.
Output − Matrix to for shortest path between any vertex to any vertex.
Begin
   for k := 0 to n, do
      for i := 0 to n, do
         for j := 0 to n, do
            if cost[i,k] + cost[k,j] < cost[i,j], then
               cost[i,j] := cost[i,k] + cost[k,j]
            done
         done
      done
      display the current cost matrix
End
#include<iostream>
#include<iomanip>
#define NODE 7
#define INF 999
using namespace std;
//Cost matrix of the graph
int costMat[NODE][NODE] = {
   {0, 3, 6, INF, INF, INF, INF},
   {3, 0, 2, 1, INF, INF, INF},
   {6, 2, 0, 1, 4, 2, INF},
   {INF, 1, 1, 0, 2, INF, 4},
   {INF, INF, 4, 2, 0, 2, 1},
   {INF, INF, 2, INF, 2, 0, 1},
   {INF, INF, INF, 4, 1, 1, 0}
};
void floydWarshal(){
   int cost[NODE][NODE]; //defind to store shortest distance from any node to any node
   for(int i = 0; i<NODE; i++)
      for(int j = 0; j<NODE; j++)
         cost[i][j] = costMat[i][j]; //copy costMatrix to new matrix
         for(int k = 0; k<NODE; k++){
            for(int i = 0; i<NODE; i++)
               for(int j = 0; j<NODE; j++)
                  if(cost[i][k]+cost[k][j] < cost[i][j])
                     cost[i][j] = cost[i][k]+cost[k][j];
   }
   cout << "The matrix:" << endl;
   for(int i = 0; i<NODE; i++){
      for(int j = 0; j<NODE; j++)
         cout << setw(3) << cost[i][j];
      cout << endl;
   }
}
int main(){
   floydWarshal();
}
The matrix:
0 3 5 4 6 7 7
3 0 2 1 3 4 4
5 2 0 1 3 2 3
4 1 1 0 2 3 3
6 3 3 2 0 2 1
7 4 2 3 2 0 1
7 4 3 3 1 1 0
Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, 
a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Print each fruit in a fruit list:
The for loop does not require an indexing variable to set beforehand.
Even strings are iterable objects, they contain a sequence of characters:
Loop through the letters in the word "banana":
With the break statement we can stop the 
loop before it has looped through all the items:
Exit the loop when x is "banana":
Exit the loop when x is "banana", 
but this time the break comes before the print:
With the continue statement we can stop the 
current iteration of the loop, and continue with the next:
Do not print banana:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Using the range() function:
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which 
means values from 2 to 6 (but not including 6):
Using the start parameter:
The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
Increment the sequence with 3 (default is 1):
The else keyword in a
for loop specifies a block of code to be 
executed when the loop is finished:
Print all numbers from 0 to 5, and print a message when the loop has ended:
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Break the loop when x is 3, and see what happens with the 
else block:
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer 
loop":
Print each adjective for every fruit:
for loops cannot be empty, but if you for 
some reason have a for loop with no content, put in the pass statement to avoid getting an error.
Loop through the items in the fruits list.
fruits = ["apple", "banana", "cherry"]
 x  fruits
  print(x)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
VBScript If..ElseIf..Else Statements

An If statement followed by one or more ElseIf Statements that consists of boolean expressions and then followed by a default else statement, which executes when all the condition becomes false.
The syntax of an If-ElseIf-Else statement in VBScript is −
If(boolean_expression) Then
   Statement 1
	.....
	.....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
	.....
	....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
	.....
	....
   Statement n
Else
   Statement 1
	.....
	....
   Statement n
End If

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a  
         a = -5

         If a > 0 Then
            Document.write "a is a POSITIVE Number"
         ElseIf a < 0 Then
            Document.write "a is a NEGATIVE Number"
         Else
            Document.write "a is EQUAL than ZERO"
         End If
      </script>
   </body>
</html>
When the above code is executed, it produces the following result −
a is a NEGATIVE Number


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
How to create a dynamic 2D array inside a class in C++

Here it is a simple C++ program to create a dynamic 2D array inside a class to print the elements of the array.
Begin
   Create a class Arr and declare size of array.
   Inside the class, initialize all the elements by using for loop.
   Print the all elements.
End.
 Live Demo
#include <iostream>
#include <stdlib.h>
using namespace std;
const int M=7;
class Arr {
   private:
   int A[M];
   int size;
   public:
   Arr(int s, int v) {
      if(s>M) {
         cout<<endl<<"This is beyond maximum size";
         exit(1);
      }
      size = s;
      for(int i=0;i<size;i++)
         A[i] = v;
   }
   int& operator[](int i) {
      if( (i<0) || (i >= size) ) {
         cout<<endl<<"Error: Array out of bound";
         exit(1);
      }
      return A[i];
   }
};
int main() {
   int i=0;
   Arr a(7,0);
   for(i=0;i<7;i++)
      a[i] = i*10;
   cout<<"Array elements are:"<<endl;
   for(i=0;i<7;i++) {
      int val = a[i];
      cout<<val<<endl;
   }
   return 0;
}
Array elements are:
0
10
20
30
40
50
60
PLSQL | SOUNDEX Function - GeeksforGeeks

27 Sep, 2019
The PLSQL SOUNDEX function is used for returning a phonetic representation of a string. The phonetic represents the way the string will sound. The PLSQL SOUNDEX function helps to compare words that are spelled differently, but sound alike in English.
The SOUNDEX function accepts one parameter input_string which can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same datatype as char.
Syntax:
SOUNDEX( input_string )
Parameters Used:
input_string – It is used to specify the string whose phonetic representation you want to know.
Note:
The value returned by the SOUNDEX function will always begin with the first letter of the input_string.
The SOUNDEX function uses only the first 5 consonants to determine the NUMERIC portion of the return value, except if the first letter of string1 is a vowel.
The SOUNDEX function is not a case-sensitive function.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE 
   Test_String string(25) := 'geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(SOUNDEX(Test_String)); 
   
END;     
Output:
G216 
Example-2:
DECLARE 
   Test_String string(25) := 'GEEKSFORGEEKS';
   
BEGIN 
   dbms_output.put_line(SOUNDEX(Test_String)); 
   
END;  
Output:
G216 
Example-3:
DECLARE 
   Test_String string(25) := 'Hello';
   
BEGIN 
   dbms_output.put_line(SOUNDEX(Test_String)); 
   
END;  
Output:
H400 
Example-4:
DECLARE 
   Test_String string(25) := 'Hello';
   
BEGIN 
   dbms_output.put_line(SOUNDEX(Test_String)); 
   
END;  
Output:
H400 
Example-5:
DECLARE 
   Test_String string(25) := 'Hello User';
   
BEGIN 
   dbms_output.put_line(SOUNDEX(Test_String)); 
   
END;  
Output:
H426 
shubham_singh
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
TypeScript - For Loop

The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as below −
for (initial_count_value; termination-condition; step) {
   //statements 
}

The loop uses a count variable to keep track of the iterations. The loop initializes the iteration by setting the value of count to its initial value. It executes the code block, each time the value of count satisfies the termination_condtion. The step changes the value of count after every iteration.
var num:number = 5; 
var i:number; 
var factorial = 1; 

for(i = num;i>=1;i--) {
   factorial *= i;
}
console.log(factorial)

The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10 
var num = 5; 
var factorial = 1; 
while (num >= 1) { 
   factorial = factorial * num; 
   num--; 
} 
console.log("The factorial  is " + factorial); 

The code produces the following output −
120

Another variation of the for loop is the for... in loop. The for... in loop can be used to iterate over a set of values as in the case of an array or a tuple. The syntax for the same is given below −
The for...in loop is used to iterate through a list or collection of values. The data type of val here should be string or any. The syntax of the for..in loop is as given below −
for (var val in list) { 
   //statements 
}

Let’s take a look at the following example −
var j:any; 
var n:any = "a b c" 

for(j in n) {
   console.log(n[j])  
}

On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var j;
var n = "a b c";

for (j in n) {
   console.log(n[j]);
}

It will produce the following output −
a 
b 
c


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Amazon Interview Experience for SDE-1 (Off-Campus) - GeeksforGeeks

17 Oct, 2021
Round 1: Online Assessment
Amazon Fresh Deliveries: Given all Locations list of co-ordinates (x,y) you have to find the X – closest locations from truck’s location which is (0,0). Distance is calculated using the formula (x^2 + y^2). If there is a tie then choose the co-ordinate with the least x value. Sample Input :
All Locations : [ [1, 2] , [1, -1], [3, 4] ]
numOfDeliveries : 2
Sample Output :
[ [1, -1], [1 , 2] ]
The output list can be in any order. This question was basically K closest points to the origin (0,0) with added tie condition.
Demolition Robot: Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1.
The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix.
Sample Input :
[1, 0, 0],
[1, 0, 0],
[1, 9, 1]]
Sample Output :
3
This question can be solved by using BFS or DFS.
Round 2: Interviews
Generate the sequence of N magic numbers. A magic number is 
Consists of digits 4 and 5
Must be an even palindrome
Expression evaluation (using stacks). The expression may contain parenthesis or not .
Round 3: 
Difference between linear and non linear data structure.
Internal working of the map, including its implementation.
First non repeating character in a stream of data in O(1) time complexity.
Creation of a binary tree.
Round 4: Technical Interview
Variation of word-ladder problem.
Tips: 
You must know how to calculate time and space complexities.
In each round they ask you about the project you recently did/ the project you liked working on most/ most challenging work etc- so you should be prepared well for at least one project with in-depth details.
Start with the naive approach for each question asked and then proceed with solutions with better space and time complexities.
Behavioral questions were also asked in each round – Some questions asked were :
Out of amazon leadership principles ,which one you identify yourself with and why ? Give real-life example.
Was there any situation in which you went out of your designated responsibilities?
All the best !
Amazon
Marketing
Off-Campus
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE-1
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
Oracle Interview Experience | Set 69 (Application Engineer)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Python | Split string in groups of n consecutive characters - GeeksforGeeks

24 Jun, 2020
Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character.
Examples:
Input : str = "Geeksforgeeks", n = 3
Output : ['Gee', 'ksf', 'oor', 'gee', 'ks']

Input : str = "1234567891234567", n = 4
Output : [1234, 5678, 9123, 4567]
 Method #1: Using list comprehension
# Python code to split string# by every 3rd number  # String initializationstring = "Geeksforgeeks"  # Defining splitting pointn = 3  # Using list comprehensionout = [(string[i:i+n]) for i in range(0, len(string), n)]  # Printing outputprint(out)
['Gee', 'ksf', 'org', 'eek', 's']

 Method #2: Using zip_longest
# Python code to split string of number# and character into every 4th number  # Importingfrom itertools import zip_longest  # Group function using zip_longest to splitdef group(n, iterable, fillvalue=None):    args = [iter(iterable)] * n    return zip_longest(fillvalue=fillvalue, *args)  # String initializationstr = '123GeeksForGeeks4567'  # Split pointn=4  # list of separated stringout_string = [''.join(lis) for lis in group(n, str, '')]  # Output list initializationout_no = []  # Converting list of string into list of integerfor a in out_string:    out_no.append(a)  # Printing listprint(out_no)
['123G', 'eeks', 'ForG', 'eeks', '4567']

nidhi_biet
Marketing
Python string-programs
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python?
Inserting the current datetime in MongoDB?

To insert current datetime in MongoDB, use the $setOnInsert operator. Let us first implement the following query to create a collection with documents
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"John","StudentAdmissionDate":new Date("2012-01-21") });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c97ae45330fd0aa0d2fe49f")
}
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2013-05-24") });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c97ae54330fd0aa0d2fe4a0")
}
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2019-07-26") });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c97ae5f330fd0aa0d2fe4a1")
}
Following is the query to display all documents from a collection with the help of find() method
> db.addCurrentDateTimeDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"),
   "StudentName" : "John",
   "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z")
}
{
   "_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"),
   "StudentName" : "Carol",
   "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z")
}
{
   "_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"),
   "StudentName" : "Carol",
   "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z")
}
Following is the query to insert current date time. We are inserting a new Student record and within that the current date time
> db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: "Robert" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } );
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
Following is the query to display all documents in order to verify that the current date time is inserted or not
> db.addCurrentDateTimeDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"),
   "StudentName" : "John",
   "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z")
}
{
   "_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"),
   "StudentName" : "Carol",
   "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z")
}
{
   "_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"),
   "StudentName" : "Carol",
   "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z")
}
{
   "_id" : 1,
   "StudentAdmissiondate" : ISODate("2019-03-24T16:21:21.269Z"),
   "StudentName" : "Robert"
}
Look at the above sample output, we have inserted current date time, which is “2019-03-24T16:21:21.269Z”.
Convert one base to other bases in a single Java Program

Let’s say we have an Octal number. To convert Octal to other bases like binary, hexadecimal, etc, the Java code is as follows −
 Live Demo
public class Demo{
   public static String base_convert(String num, int source, int destination){
      return Integer.toString(Integer.parseInt(num, source), destination);
   }
   public static void main(String[] args){
      String my_num = "345";
      int source = 8;
      int destination = 2;
      System.out.println("Converting the number from octal to binary: "+ base_convert (my_num, source, destination));
      destination = 10;
      System.out.println("Converting the number from octal to decimal : "+ base_convert (my_num, source, destination));
      destination = 16;
      System.out.println("Converting the number from octal to hexadecimal: "+ base_convert (my_num, source, destination));
   }
}
Converting the number from octal to binary: 11100101
Converting the number from octal to decimal : 229
Converting the number from octal to hexadecimal: e5
A class named Demo contains a function named ‘base_convert’ is defined. This function parses the integer from source base to the destination base, converts it into a string and returns it as output. In the main function, the value for number, for source base and for different destination bases are defined. The ‘base_convert’ function is called with the number, source and destination as parameters. Relevant output is displayed.
Jython - Functions

A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement.
Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear.
#definition of function
defSayHello():
   "optional documentation string"
   print "Hello World"
   return

#calling the function
SayHello()
A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception.
#defining function with two arguments
def area(l,b):
   area = l*b
   print "area = ",area
   return

#calling function
length = 10
breadth = 20
#with two arguments. This is OK
area(length, breadth)
#only one argument provided. This will throw TypeError
area(length)
The output will be as follows −
area = 200
Traceback (most recent call last):
   File "area.py", line 11, in <module>
   area(length)
TypeError: area() takes exactly 2 arguments (1 given)

After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function.
#defining function
def area(l,b):
   area = l*b
   print "area = ",area
   return area

#calling function
length = 10
breadth = 20
#calling function and obtaining its reurned value
result = area(length, breadth)
print "value returned by function : ", result
The following output is obtained if the above script is executed from the Jython prompt.
area = 200
value returned by function : 200

 Print
 Add Notes
 Bookmark this page
How to create String object in Java?

You can create a String by -
Assigning a string value wrapped in " " to a String type variable.
Assigning a string value wrapped in " " to a String type variable.
String message = "Hello Welcome to Tutorialspoint";
Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor.
Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor.
String message = new String ("Hello Welcome to Tutorialspoint");
Passing a character array to the String constructor.
Passing a character array to the String constructor.
char arr[] = {'H','e','l','l','o'};
String message = new String(arr);
Update array of objects with JavaScript?

Let’s say the following are our array of objects −
var studentDetails = [
   { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']},
   {firstName: "David", listOfSubject: ['Java', 'C']
}]
We need to add the following in the already created array of objects −
{firstName: "Bob", listOfSubject: ['JavaScript']};
var studentDetails = [
   { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']},
   {firstName: "David", listOfSubject: ['Java', 'C']}];
   updateThisObject = {firstName: "Bob", listOfSubject: ['JavaScript']};
   function forLoopExample(studentObjects, updateObj){
   for(var index = 0;index < studentObjects.length; index++) {
      if(updateObj.listOfSubject.join("") ===
         studentObjects[index].listOfSubject.join("")) {
         studentObjects[index] = updateObj;
         return;
      }
   }
   studentObjects.push(updateObj);
}
forLoopExample(studentDetails, updateThisObject);
console.log(studentDetails);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo100.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo100.js
[
   { firstName: 'John', listOfSubject: [ 'MySQL', 'MongoDB' ] },
   { firstName: 'David', listOfSubject: [ 'Java', 'C' ] },
   { firstName: 'Bob', listOfSubject: [ 'JavaScript' ] }
]
How to change the size of correlation coefficient value in correlation matrix plot using corrplot in R?

The correlation coefficient value size in correlation matrix plot created by using corrplot function ranges from 0 to 1, 0 referring to the smallest and 1 referring to the largest, by default it is 1. To change this size, we need to use number.cex argument. For example, if we want to decrease the size to half then we can use number.cex = 0.5.
Consider the below matrix −
 Live Demo
set.seed(99)
M<-matrix(rpois(100,10),ncol=10)
M
      [,1] [,2] [,3] [,4] [,5] [,6]  [,7]  [,8]  [,9] [,10]
[1,]    10  10   14   14    7    9    14    14    13    10
[2,]    11   8    9    13   9    9     5    12     7     6
[3,]    10  12    6    11   5    8    10     4    11    15
[4,]    11   7   12     9   5   10     7    10    10     9
[5,]     8   8    8    16   8    6     7    14    12     8
[6,]    10   4    5    10   6    8    14     9    14    11
[7,]     7  12    9     4   14  18     7    12    12     9
[8,]    11  16    8     6   18  12     9     9    10    16
[9,]     5   9   11    13   8   10    12    10    10     9
[10,]    7  14   13     9   7   10    10    15    11    16
Loading corrplot package and creating a correlation matrix plot −
library(corrplot) > corrplot(cor(M),addCoef.col="black")
Changing the size of correlation coefficient value to 0.75 −
corrplot(cor(M),addCoef.col="black",number.cex=0.75)
Changing the size of correlation coefficient value to 0.30 −
> corrplot(cor(M),addCoef.col="black",number.cex=0.30)
How to add transition on hover with CSS?

To add transition with hover on CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      padding: 20px;
   }
   .scaleBtn {
      display: inline-block;
      background-color: #0c1377;
      border: none;
      color: white;
      padding: 16px 32px;
      text-align: center;
      font-size: 16px;
      transition: 0.3s;
      margin: 20px;
   }
   .scaleBtn:hover {
      transform: scale(1.5);
   }
</style>
</head>
<body>
<h1>Transition on hover example</h1>
<button class="scaleBtn">Hover Here</button>
</body>
</html>
The above code will produce the following output −
On hovering above the “Hover Here” button −
How to use Thread in Tkinter Python?

With Tkinter, we can call multiple functions at a time using Threading. It provides
asynchronous execution of some functions in an application.
In order to use a thread in Python, we can import a module called threading and subclass its Thread class. Inside our new class, we need to overwrite the Run method and perform our logic in there.
So, basically with threading, we can do multiple work at a time. To achieve threading in our application, Tkinter provides the Thread() function.
Let us take an example and create a thread which will sleep for some time and then
execute another function in parallel.
For this example, we will import the Time module and the threading module defined in the Tkinter library.
#Import all the necessary libraries
from tkinter import *
import time
import threading

#Define the tkinter instance
win= Tk()

#Define the size of the tkinter frame
win.geometry("700x400")

#Define the function to start the thread
def thread_fun():
   label.config(text="You can Click the button or Wait")
   time.sleep(5)
   label.config(text= "5 seconds Up!")
   
label= Label(win)
label.pack(pady=20)
#Create button
b1= Button(win,text= "Start", command=threading.Thread(target=thread_fun).start())
b1.pack(pady=20)

win.mainloop()
Running the above code will create a button and a thread which works on a label.
After 5 seconds, the thread will automatically pause.