code-rag-bench/online-tutorials huggingface dataset:
MySQL – ON DELETE CASCADE Constraint

08 Feb, 2021
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id. All the courses in these online learning platforms had their own code, title, and name. Students can enroll in any course according to their wishes. 
There is no rule that all students must enroll in all courses, or they have to join the course on the same date. A student can enroll in one or more courses. Suppose you delete a row from the “Student” table, now you will also want to delete all rows in the “Enroll” table that references the row in the “Student” table. For that, we need ON DELETE CASCADE.  Below are the steps that explain how ON DELETE CASCADE referential action works.
Step 1: Create the Student table
CREATE TABLE Student (
    sno INT PRIMARY KEY,
    sname VARCHAR(20),
    age INT

);
Step 2: Insert rows into the Student table
INSERT INTO Student(sno, sname,age) 
 VALUES(1,'Ankit',17),
       (2,'Ramya',18),
       (3,'Ram',16);
Step 3: Execute the SELECT query to check the data in the STUDENT table.
SELECT *
FROM Student;
Output:
Step 4: Create the Course table
CREATE TABLE Course (
    cno INT PRIMARY KEY,
    cname VARCHAR(20)
);
Step 5: Insert rows into the Course table
INSERT INTO Course(cno, cname) 
 VALUES(101,'c'),
       (102,'c++'),
       (103,'DBMS');
Step 6: Execute the SELECT query to check the data in the Course table.
SELECT *
FROM Course;
Output:
Step 7: Create the Enroll table 
CREATE TABLE Enroll (
    sno INT,
    cno INT,
    jdate date,
    PRIMARY KEY(sno,cno),
    FOREIGN KEY(sno) 
        REFERENCES Student(sno)
        ON DELETE CASCADE
    FOREIGN KEY(cno) 
        REFERENCES Course(cno)
        ON DELETE CASCADE
);
Step 8: Insert rows into the Enroll table
INSERT INTO Enroll(sno,cno,jdate) 
 VALUES(1, 101, '5-jun-2021'),
       (1, 102, '5-jun-2021'),
       (2, 103, '6-jun-2021');
Step 9: Execute the SELECT query to check the data in the Enroll table.
SELECT *
FROM Enroll;
Output:
Step 10: Here the parent tables are Student and Course whereas the child table is Enroll. If a student drops from the course or a course is removed from the offering list it must affect the child table also. 
DELETE FROM Student
WHERE sname="Ramya";
Step 11: Execute the SELECT query to check the data.
Select * from Student;
Output: 
Select * from Enroll;
Output:
As you delete the contents of sno=2 in the parent table it automatically deletes the details of sno=2 from the child table also. In the same way, if you remove a course from the Course table it automatically deletes the rows of that course in the child table Enroll. This works out because the foreign key constraint ON DELETE CASCADE is specified.
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SAS - Strings

Strings in SAS are the values which are enclosed with in a pair of single quotes. Also the string variables are declared by adding a space and $ sign at the end of the variable declaration. SAS has many powerful functions to analyze and manipulate strings.
We can declare the string variables and their values as shown below. In the code below we declare two character variables of lengths 6 and 5. The LENGTH keyword is used for declaring variables without creating multiple observations.
data string_examples;
   LENGTH string1 $ 6 String2 $ 5;
   /*String variables of length 6 and 5 */
   String1 = 'Hello';
   String2 = 'World';
   Joined_strings =  String1 ||String2 ;
run;
proc print data = string_examples noobs;
run;

On running the above code we get the output which shows the variable names and their values.
Below are the examples of some SAS functions which are used frequently.
This function extracts a substring using the start and end positions. In case of no end position is mentioned it extracts all the characters till end of the string.
SUBSTRN('stringval',p1,p2)

Following is the description of the parameters used −
stringval is the value of the string variable.
p1 is the start position of extraction.
p2 is the final position of extraction.
data string_examples;
   LENGTH string1 $ 6 ;
   String1 = 'Hello';
   sub_string1 = substrn(String1,2,4) ;
   /*Extract from position 2 to 4 */
   sub_string2 = substrn(String1,3) ;
   /*Extract from position 3 onwards */
run;
proc print data = string_examples noobs;
run;

On running the above code we get the output which shows the result of substrn function.
This function removes the trailing space form a string.
TRIMN('stringval')

Following is the description of the parameters used −
stringval is the value of the string variable.
data string_examples;
   LENGTH string1 $ 7  ;
   String1='Hello  ';
   length_string1 = lengthc(String1);
   length_trimmed_string = lengthc(TRIMN(String1));
run;
proc print data = string_examples noobs;
run;
On running the above code we get the output which shows the result of TRIMN function.
Python | Pandas Series.str.index()

13 Jul, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.index() method is used to search and return lowest index of a substring in particular section (Between start and end) of every string in a series. This method works in a similar way to str.find() but on not found case, instead of returning -1, str.index() gives a ValueError.
Syntax: Series.str.index(sub, start=0, end=None)
Parameters:sub: String or character to be searched in the text value in seriesstart: String or character to be searched in the text value in seriesend: String or character to be searched in the text value in series
Return type: Series with least index of substring if found.
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Finding index when substring exists in every string
In this example, ‘e’ is passed as substring. Since ‘e’ exists in all 5 strings, least index of it’s occurrence is returned. Before applying any operations, null rows were removed using .dropna() method.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # extracting 5 rowsshort_data = data.head().copy()  # calling str.index() methodshort_data["Index Name"]= short_data["Name"].str.index("e")  # displayshort_data
Output:As shown in the output image, the least index of ‘e’ in series was returned and stored in new column. Example #2:
In this example, ‘a’ is searched in top 5 rows. Since ‘a’ doesn’t exist in every string, value error will be returned. To handle error, try and except is used.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # extracting 5 rowsshort_data = data.head().copy()  # calling str.index() methodtry:    short_data["Index Name"]= short_data["Name"].str.index("a")except Exception as err:    print(err)      # displayshort_data
Output:As shown in output image, the output data frame is not having the Index Name column and the error “substring not found” was printed. That is because str.index() returns valueError on not found and hence it must have gone to except case and printed the error.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | Window resizeTo() Method

26 Jul, 2019
The resizeTo() method is used to resizes a window to the specified width and height.
Syntax:
window.resizeTo(width, height)
Parameter Values:
width: Sets the width of the window, in pixels.
height: Sets the height of the window, in pixels.
Example: Resize the window.
<!DOCTYPE html><html>  <head>    <title>        Window resizeTo() Method    </title>    <style>        h1 {            color: green;        }    </style>  </head>  <body>    <center>        <h1>Geeks for Geeks</h1>        <button onclick="openWin()">            New window        </button>        <button onclick="resizeWin()">            Resize window        </button>          <script>            var myWindow;              function openWin() {                myWindow =                    window.open("", "",                        "width=100, height=100");            }              function resizeWin() {                myWindow.resizeTo(300, 300);                myWindow.focus();            }        </script>    </center></body>  </html>
Output:Initial:New window:Resize window:
Supported Browsers: The browser supported by Window resizeTo() Method are listed below:
Google Chrome
Internet Explorer
Mozilla Firefox
Opera
Safari
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Java program to accept an integer from user and print it

Scanner class of the util package class is used to read data from user The nextInt() method of this class reads an integer from the user.
import java.util.Scanner;
public class PrintInteger {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer:");
      int num = sc.nextInt();
      System.out.print("Given integer is :: "+num);
   }
}
Enter an integer:
123
Given integer is :: 123
numpy.einsum() Method - GeeksforGeeks

10 Aug, 2020
In NumPy, we can find Einstein’s summation convention of two given multidimensional arrays with the help of numpy.einsum(). We will pass two arrays as a parameter and it will return the Einstein’s summation convention.
Syntax: numpy.einsum()
Parameter: Two arrays.
Return : It will return the Einstein’s summation convention.
Example 1:
Python
import numpy as np    array1 = np.array([1, 2, 3])array2 = np.array([4, 5, 6])  # Original 1-d arraysprint(array1)print(array2)r = np.einsum("n,n", a, b)  # Einstein’s summation convention of # the said arraysprint(r)
Output:
[1 2 3]
[4 5 6]
32

Example 2:
Python
import numpy as np    ar1 = np.arange(9).reshape(3, 3)ar2 = np.arange(10, 19).reshape(3, 3)  # Original Higher dimensionprint(ar1)  print(ar2)print("")r = np.einsum("mk,kn", ar1, ar2)  # Einstein’s summation convention of # the said arraysprint(r)
 Output:
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[10 11 12]
 [13 14 15]
 [16 17 18]]

[[ 45  48  51]
 [162 174 186]
 [279 300 321]]
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
wxPython - Change Background colour of Button - GeeksforGeeks

18 Jun, 2020
In this article we are going to learn about how can we change background colour of a button present in a frame. We use SetBackgroundColour() function to set background colour of the button to some different colour.It takes a wx.Colour class object as an argument.
Syntax: wx.Button.SetBackgroundColour(self, colour)
Parameters:
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()      def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)        self.pnl = wx.Panel(self)        font = wx.Font(10, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90,                        underline = False, faceName ="", encoding = wx.FONTENCODING_DEFAULT)          self.btn = wx.Button(self.pnl, id = 1, label ="Click", pos =(20, 20),                                size = wx.DefaultSize, name ="statictext")        self.btn.SetFont(font)                  # SET BACKGROUND COLOUR        self.btn.SetBackgroundColour((255, 230, 200, 255))        self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre()  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output Widow:
Python wxPython-Button
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
2’s compliment for a given string using XOR ?

In this section we will see how we can find the 2’s complement using the XOR operation on a binary string. The 2’s complement is actually the 1’s complement + 1. We will use XOR operation to get the 1’s complement.
We will traverse the string from LSb, and look for 0. We will flip all 1’s to 0 until we get a 0. Then flip the found 0.
We will traverse from LSb. Then ignoring all 0’s until we get 1. Ignoring the first 1, we will toggle all bits using the XOR operation.
begin
   len := length of the binary string
   flag := false
   for i := len-1 down to 0, do
      if bin[i] is 0, and flag is not set, then
         ignore the next part, jump to next iteration
      else
         if flag is set, then
            bin[i] := flip of bin[i]
         end if
         flag := true
      end if
   done
   if the flag is not set, then
      attach 1 with bin and return
   else
      return bin
   end if
end
 Live Demo
#include <iostream>
using namespace std;
string get2sComplement(string bin) {
   int n = bin.length();
   bool flag = false; //flag is used if 1 is seen
   for (int i = n - 1; i >= 0; i--) { //traverse from last bit
      if (bin[i] == '0' && !flag) {
         continue;
      } else {
         if (flag)
            bin[i] = (bin[i] - '0') ^ 1 + '0'; //flip bit using XOR, then convert to ASCII
         flag = true;
      }
   }
   if (!flag) //if no 1 is there, just insert 1
      return "1" + bin;
   else
      return bin;
}
int main() {
   string str;
   cout << "Enter a binary string: ";
   cin >> str;
   cout << "2's complement of " << str <<" is " << get2sComplement(str);
}
Enter a binary string: 10110110
2's complement of 10110110 is 01001010
What is autoboxing in Java?

Autoboxing refers to the automatic conversion of a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is −
Passed as an argument to a function which is expecting a wrapper class object. assigned to a variable of the type of wrapper class.
 Live Demo
public class Test{
   public static void main(String[] args) {
      int num = 122;
      Integer dat = num;
      System.out.println(dat);
   }
}
122
Dart Programming - Parameterized Function

Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.
Let us now discuss the ways in which parameters can be used by functions.
It is mandatory to pass values to required parameters during the function call.
Function_name(data_type param_1, data_type param_2[...]) { 
   //statements 
}

The following code snippet declares a function test_param with two parameters namely, n1 and s1
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime.
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
void main() { 
   test_param(123,"this is a string"); 
}  
test_param(int n1,String s1) { 
   print(n1); 
   print(s1); 
} 
The output of the above code is as follows −
123 
this is a string 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Aggregation in MongoDB using Python - GeeksforGeeks

10 Jul, 2020
MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is most recently used database which provide mechanism for storage and retrieval of data. Instead of using tables and rows as in relational databases, mongodb architechture is made up of collections and documents. 
Aggregation operation groups the values from multiple documents(rows in case of MongoDB) together to perform a variety of operations on the grouped data and is going to return a single result for each grouped data after aggregation. 
Syntax:
db.collection_name.aggregate(aggregate operations)

Sample Database used in all the below examples:
Example 1:
Python3
from pymongo import MongoClient  my_client = MongoClient('localhost', 27017)db = my_client["GFG"]coll = db["Student"]  # Aggregationcursor = coll.aggregate([{"$group":       {"_id":"$Branch",       "similar_branches":{"$sum":1}       }       }])  for document in cursor:       print(document)
Output:
Here, we use “$group” command for grouping then by “_id”:”branches” we are grouping ids according to the branches. “similar_branches” is the keyword used for the total number of similar branches,we can use any keyword here. “$sum:1” is used as a counter of total number of each branches. The sum is incrementing by 1. 
Example 2:  We can also use the aggregation query for counting the number of document in the database.
Python3
from pymongo import MongoClient  my_client = MongoClient('localhost', 27017)db = my_client["GFG"]coll = db["Student"]  # Aggregationcursor = coll.aggregate([{"$group":       {"_id":"$None",       "total collections":{"$sum": 1}       }       }])  for document in cursor:       print(document)
Output:
{'_id': None, 'total collections': 8}
Python-mongoDB
Python
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 ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Convert number string to integers in C++

Here we will see how to convert a number string to integer type data. We can solve this problem by using the atoi() function. This function takes string as input and converts into integer data.
The atoi() function is present in the <cstdlib> library.
Input: A number string “1234”
Output: 1234
Step 1: Take a number string
Step 2: Convert it to integer using atoi() function
Step 3: Print the result.
Step 4: End
 Live Demo
#include<iostream>
#include<cstdlib>
using namespace std;
main() {
   int n;
   char num_string[20] = "1234";
   n = atoi(num_string);
   cout << n;
}
1234
How to hide HTML element with JavaScript?

Use the visibility property in JavaScript to hide an element. You can try to run the following code to learn how to work with visibility property to hide an element −
<!DOCTYPE html>
<html>
   <body>
      <p id = "pid">Demo Text</p>

      <button type = "button" onclick = "displayHide()">Hide</button>
      <button type = "button" onclick = "displayShow()">Show</button>
     
      <script>
         function displayHide() {
            document.getElementById("pid").style.visibility = "hidden";
         }
         function displayShow() {
            document.getElementById("pid").style.visibility = "visible";
         }
      </script>
   </body>
</html>
How can we drop UNIQUE constraint from a MySQL table?

For dropping UNIQUE constraint from a MySQL table, first of all, we must have to check the name of the index created by the UNIQUE constraint on the table. As we know that SHOW INDEX statement is used for this purpose. The ‘key_name’ in the result set of SHOW INDEX statement contains the name of the index. Now either with the help of DROP INDEX statement or ALTER TABLE statement, we can drop the UNIQUE constraint. The syntax for both the statements is as follows −
DROP INDEX index_name ON table_name;
OR
ALTER TABLE table_name DROP INDEX index_name;
Suppose we have the table ‘empl’ which have a UNIQUE constraint on column ‘empno’. The index name can be checked as follows −
mysql> Show Index from empl\G
*************************** 1. row ***************************
Table: empl
Non_unique: 0
Key_name: empno
Seq_in_index: 1
Column_name: empno
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
1 row in set (0.02 sec)
Now for dropping the UNIQUE constraint, we can write the following query −
mysql> ALTER TABLE empl DROP INDEX empno;
Query OK, 0 rows affected (0.26 sec)
Records: 0 Duplicates: 0 Warnings: 0
The result set of the query below will show that there is no UNIQUE constraint on column ‘empno’ −
mysql> describe empl;

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| empno | int(11) | YES | | NULL | |
| F_name | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec)
Even if we will run the SHOW INDEX from empl query then MySQL will result in an empty set as follows −
mysql> Show index from empl;
Empty set (0.00 sec)
The UNIQUE constraint can also be dropped from ‘empl’ table with the help of DROP INDEX statement as follows −
mysql> DROP INDEX empno on empl;
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0
Embedded or internal Style Sheets in CSS

CSS files can be embedded internally by declaring them in <style> tag. This decreases the load time of the webpage. Although embedded CSS declarations allow dynamic styles, it should be downloaded at every page request as internal CSS can’t be cached. Internal CSS are declared in <style>tag inside <head> tag.
The syntax for embedding CSS files is as follows −
<style>
   /*declarations*/
</style>
The following examples illustrate how CSS files are embedded −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
article {
   font-size: 1.3em;
   font-family: cursive;
}
div {
   float: left;
   margin-left: 20px;
   width: 30px;
   height: 30px;
   background-color: lightgreen;
   box-shadow: 8px 5px 0 2px lightcoral;
}
</style>
</head>
<body>
<article>Demo text</article>
<div></div>
<div></div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
   float: left;
   margin-left: 20px;
   width: 60px;
   height: 30px;
   border-top-right-radius: 50px;
   border-bottom-right-radius: 50px;
   background-color: lightgreen;
   box-shadow: inset 5px 0 lightcoral;
}
div + div {
   background-color: lightblue;
   border-top-left-radius: 50px;
   border-bottom-left-radius: 50px;
}
</style>
</head>
<body>
<div></div>
<div></div>
</body>
</html>
This gives the following output −
How to get yesterday’s date in JavaScript?

To get the yesterday date, first of all get the current date and subtract 1 from the current and
use the function setDate(). The syntax is as follows −
yourCurrentDateVariableName.setDate(yourCurrentDateVariableName.getDate() - 1);
At first, get the current date −
var currentDate = new Date();
Now, get yesterday’s date with the following code −
var currentDate = new Date();
console.log("The current date="+currentDate);
var yesterdayDate = currentDate.setDate(currentDate.getDate()- 1);
console.log("The yesterday date ="+new Date(yesterdayDate));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo137.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo137.js
The current date=Fri Jul 31 2020 18:57:17 GMT+0530 (India Standard Time)
The yesterday date =Thu Jul 30 2020 18:57:17 GMT+0530 (India Standard Time)
Null Pointer Exception in C#

NullReferenceException is a C# version of NullPointerException. To handle and catch it in C#, use try-catch.
The below example shows that a variable is set to null and when we try to print it, it throws an exception that gets caught in the catch −
Try {
   a = null;
   Console.WriteLine(a);
}catch (NullPointerException ex) {
   Console.WriteLine("Variable is Null!");
}
The above will allow the exception to be caught and use catch for it.
Console Class in C#

The Console class in C# is used to represent the standard input, output, and error streams for console applications.
Let us see some examples of Console class properties in C# −
To change the CursorLeft of the Console in C#, use the Console.CursorLeft property.
Let us see an example −
using System;
class Demo {
   public static void Main (string[] args) {
      Console.BackgroundColor = ConsoleColor.Blue;
      Console.WriteLine("Background color changed = "+Console.BackgroundColor);
      Console.ForegroundColor = ConsoleColor.Yellow;
      Console.WriteLine("\nForeground color changed = "+Console.ForegroundColor);
      Console.CursorLeft = 30;
      Console.Write("CursorLeft position: "+Console.CursorLeft);
   }
}

This will produce the following output −
To change the CursorSize of the Console in C#, use the Console.CursorSize property in C#.
Let us see an example −
using System;
class Demo {
   public static void Main (string[] args) {
      Console.BackgroundColor = ConsoleColor.Blue;
      Console.WriteLine("Background color changed = "+Console.BackgroundColor);
      Console.ForegroundColor = ConsoleColor.Yellow;
      Console.WriteLine("\nForeground color changed = "+Console.ForegroundColor);
      Console.CursorSize = 1;
      Console.WriteLine("\nCursorSize = "+Console.CursorSize);
   }
}

This will produce the following output −
To change the BufferWidth of the Console, use the Console.BufferWidth property.
Let us now see an example −
using System;
class Demo {
   public static void Main (string[] args) {
      Console.BufferHeight = 200;
      Console.WriteLine("Buffer Height = "+Console.BufferHeight);
      Console.BufferHeight = 250;
      Console.WriteLine("Buffer Width = "+Console.BufferWidth);
   }
}
This will produce the following output −
Buffer Height = 200
Buffer Width = 200
How can I subtract a day from a Python date?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date. 
from datetime import datetime
from datetime import timedelta
today = datetime.today()
yesterday = today - timedelta(days=1)
print(today)
print()
print(yesterday)
This will give the output −
2017-12-29 12:28:06.531791
2017-12-28 12:28:06.531791
Explain Python Matrix with examples

A matrix in Python is a two-dimensional array having a specific number of rows and columns. The data elements in Python matrix can be numbers, strings or symbols etc.
Matrix or two-dimensional list is an important data structure. Various operations associated with matrix involve transpose, addition or multiplication of two matrices.
We will discuss how to declare a matrix in python with a specific number of rows and columns and then input data items from the user and finally print the matrix.
A matrix in Python can be declared as a nested list. The number of rows and columns needs to be specified. Suppose number of rows is 3 and number of columns is 4. We will declare the matrix as follows
Matrix=[[0]*4 for i in range(3)]
col=4
rows=3
matrix=[[0]*col for i in range(rows)]
for i in range(rows):
   print("Enter","row",i+1,"elements")
   for j in range(col):
      matrix[i][j]=int(input())

def rowvise(matrix):
   for i in range(rows):
      print(matrix[i])
print("print as nested list")
print(matrix)
print("print each row in separate line")
rowvise(matrix)
Enter row 1 elements
1
2
3
4
Enter row 2 elements
5
6
7
8
Enter row 3 elements
1
2
3
4
print as nested list
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]
print each row in separate line
[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4]
These are the basic operations on matrix, which involve declaring a matrix, assigning data element values and printing a matrix. The other operations such as transpose can be achieved by applying specific logic to the given matrix.
How to validate given date formats like MM-DD-YYYY using regex in java?

The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −
compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object.
compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
Following is the regular expression to match date in dd-MM-yyyy format:
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
Therefore, to validate a date String of the format MM-DD-YYYY −
Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object.
Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object.
Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method.
Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method.
The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step.
The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingDate {
   public static void main(String[] args) {
      String date = "01/12/2019";
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(date);
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
   }
}
Date is valid
Walmart Interview Experience - GeeksforGeeks

22 Jun, 2021
Round 1: It was an online round hosted by Walmart on dare2dare. It consisted of 2 coding questions. The coding question goes like this : 
1: This question is also asked in the onsite 2nd intuit interview of SDE-1. Exactly one swap 
Given a string S containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap. 
In one swap,Geek can pick two distinct indexes i and j (i.e 1 < i < j < |S| ) of the string, then swap the characters at the position i and j. 
 
Example 1:
Input:
S = "geek"
Output:
6
Explanation:
After one swap, there are only 6 distinct strings possible.
(i.e "egek","eegk","geek","geke","gkee" and "keeg")
 
2: This question is also asked in the Hackwithinfy online round. 
Partition the array 
Given an array A[] of N integers. The task is to partition the array into four non-empty parts P,Q,R and S. 
Let W,X,Y and Z be the sum of the elements in P,Q,R and S respectively. The absolute difference of the maximum and the minimum among W,X,Y and Z should be smallest. Find the smallest absolute difference of the maximum and the minimum among W,X,Y and Z. 
 
Example 1: Input: N = 5 A[] = [4,2,2,5,1] Output: 4 Explanation: let partition the array P,Q,R,S = [4],[2,2],[5],[1] W = 4, X = 4, Y = 5, Z = 1 Difference = max(W,X,Y,Z) – min(W,X,Y,Z) = 5 – 1 = 4
 
 
Marketing
Walmart
Interview Experiences
Walmart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience (Off-Campus) 2022
Goldman Sachs Interview Experience (2021-2022)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Infosys DSE Interview Experience 2021
How to write an Interview Experience?
Infosys DSE Interview Experience 2021
yum - Unix, Linux Command

yum is an interactive, rpm based, package manager. It can automatically
perform system updates, including dependency analysis and obsolete processing
based on "repository" metadata. It can also perform installation of new
packages, removal of old packages and perform queries on the installed and/or
available packages among many other commands/services (see below). yum
is similar to other high level package managers like apt-get and smart.


While there are some graphical interfaces directly to the yum code, more
recent graphical interface development is happening with PackageKit and the
gnome-packagekit application.


command is one of:

 * install package1 [package2] [...] 
 * update [package1] [package2] [...] 
 * check-update 
 * upgrade [package1] [package2] [...] 
 * remove | erase package1 [package2] [...] 
 * list [...] 
 * info [...] 
 * provides | whatprovides feature1 [feature2] [...] 
 * clean [ packages | headers | metadata | dbcache | all ] 
 * makecache 
 * groupinstall group1 [group2] [...] 
 * groupupdate group1 [group2] [...] 
 * grouplist [hidden] [groupwildcard] [...] 
 * groupremove group1 [group2] [...] 
 * groupinfo group1 [...] 
 * search string1 [string2] [...] 
 * shell [filename] 
 * resolvedep dep1 [dep2] [...] 
 * localinstall rpmfile1 [rpmfile2] [...] 
 * localupdate rpmfile1 [rpmfile2] [...] 
 * reinstall package1 [package2] [...] 
 * downgrade package1 [package2] [...] 
 * deplist package1 [package2] [...] 
 * repolist [all|enabled|disabled] 
 * help [command] 

Unless the --help or -h option is given, one of the above commands
must be present.


Repository configuration is honored in all operations.




If the main obsoletes configure option is true (default) or the --obsoletes
flag is present yum will include package
obsoletes in its calculations - this makes it better for distro-version
changes, for example: upgrading from somelinux 8.0 to somelinux 9.




















1. The plugin module file must be installed in the plugin path as just
described.


2. The global plugins option in /etc/yum/yum.conf must be set to ‘1’.


3. A configuration file for the plugin must exist in
/etc/yum/pluginconf.d/<plugin_name>.conf and the enabled setting in this
file must set to ‘1’. The minimal content for such a configuration file is:





/etc/yum.conf
/etc/yum.repos.d/
/etc/yum/pluginconf.d/
/var/cache/yum/









See the Authors file included with this program.






Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Difference between singleton and prototype bean scope.

Spring framework supports five types of bean scope −
Singleton
Singleton
Prototype
Prototype
Request
Request
Session
Session
Global Session
Global Session
As per the spring documentation −
Singleton − It returns a single bean instance per Spring IoC container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.
Spring singleton is different than Java singleton. In java, one instance of the bean is created per JVM whereas in spring, one instance of the bean is created per application context.
Proptype −
As per the spring documentation −
Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
<bean id="xyzService" class="com.xyz.XyzService" scope="singleton"/>

<bean id="xyzService" class="com.xyz.XyzService" scope="prototype"/>
How to get the POST values from serializeArray in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
Let’s say we have the PHP content in serialize.php file:
<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
   $age = $_REQUEST['age'];
   echo "<br />Your age : ". $age;
   $sex = $_REQUEST['sex'];
   echo "<br />Your gender : ". $sex;
}
?>
The following is an example showing the usage of this method:
Live Demo
<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               
               $.post(
                  "/jquery/serialize.php",
                  $("#testform").serializeArray(),
                  function(data) {
                     $('#stage1').html(data);
                  }
               );
                   
               var fields = $("#testform").serializeArray();
               $("#stage2").empty();
                   
               jQuery.each(fields, function(i, field){
                  $("#stage2").append(field.value + " ");
               });
                   
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage1" style = "background-color:maroon;color:white;">
         STAGE - 1
      </div>
       
      <br />
       
      <div id = "stage2" style = "background-color:maroon;color:white;">
         STAGE - 2
      </div>
       
      <form id = "testform">
       
         <table>
           
            <tr>
               <td><p>Name:</p></td>
               <td><input type = "text" name = "name" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Age:</p></td>
               <td><input type = "text" name = "age" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Sex:</p></td>
               <td> <select name = "sex">
                  <option value = "Male" selected>Male</option>
                  <option value = "Female" selected>Female</option>
               </select></td>
            </tr>
               
            <tr>
               <td colspan = "2">
                  <input type = "button" id = "driver" value = "Load Data" />
               </td>
            </tr>  
               
         </table>
           
      </form>
       
   </body>
   
</html>
C++ Program to Add Two Matrix Using Multi-dimensional Arrays

A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 4*3 matrix has 4 rows and 3 columns as shown below −
3 5 1
7 1 9
3 9 4
1 6 7
A program that adds two matrices using multidimensional arrays is as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int r=2, c=4, sum[2][4], i, j;
   int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
   int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
   cout<<"The first matrix is: "<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<a[i][j]<<" ";
      cout<<endl;
   }
   cout<<endl;
   cout<<"The second matrix is: "<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<b[i][j]<<" ";
      cout<<endl;
   }
   cout<<endl;
   for(i=0;i<r;++i)
   for(j=0;j<c;++j)
   sum[i][j]=a[i][j]+b[i][j];
   cout<<"Sum of the two matrices is:"<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<sum[i][j]<<" ";
      cout<<endl;
   }
   return 0;
}
The first matrix is:
1 5 9 4
3 2 8 3

The second matrix is:
6 3 8 2
1 5 2 9

Sum of the two matrices is:
7 8 17 6
4 7 10 12
In the above program, first the two matrices a and b are defined. This is shown as follows.
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<a[i][j]<<" ";
   cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<b[i][j]<<" ";
   cout<<endl;
}
The two matrices are added using a nested for loop and the result is stored in matrix sum[][]. This is shown in the following code snippet.
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
After the sum of the two matrices is obtained, it is printed on screen. This is done as follows −
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<sum[i][j]<<" ";
   cout<<endl;
}
Substring check in JavaScript - GeeksforGeeks

14 Mar, 2019
The includes() method can be used to check whether a string contains a specified substring. It returns true if substring is present. This method is case sensitive.
Syntax:
string.includes(searchvalue, start)

Parameters: This method requires 2 parameters :-
searchvalue: Required. It specifies the substring that needs to be searched.
start: Optional. It specifies the index from where the searching is performed. By default it is 0.
Return Value: True if the specified substring is present in string else returns false.
Example:
<!DOCTYPE html><html>    <body>        <h1>Welcome to GeeksforGeeks</h1>        <p>Click the button to check whether             <b>Geeks</b> is present in the below string.        </p>        Hello there! Welcome to GeeksforGeeks.<br><br>        <button onclick="myFunction()">Try it</button>        <p id="display"></p>          <!--script to check string contains the specified substring.-->        <script>            function myFunction() {              var str = "Hello there! Welcome to GeeksforGeeks.";                               var flag = str.includes("Geeks");              document.getElementById("display").innerHTML = flag;            }        </script>    </body></html>
Output:Before clicking try it button:After clicking try it button:Supported Browsers: The browser supported by includes() Method are listed below:
Google Chrome 41
Apple Safari 9
Firefox 40
Opera 28
Edge 12.0
javascript-string
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
Lodash _.debounce() Method
Angular File Upload
How to get selected value in dropdown list using JavaScript ?
Python | Extract Combination Mapping in two lists - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let’s discuss certain way in which this problem can be solved.
Method : Using zip() + product()With these functions this problem can be solved and would require two steps to perform it. In the 1st step, we find all the combinations of elements using product() and as a part of 2nd step, we perform the possible pairing with the result of step 1 using zip() and output the desired result.
# Python3 code to demonstrate working of# Extract Combination Mapping in two lists# using zip() + product()from itertools import product  # initialize liststest_list1 = [3, 4, 5]test_list2 = ['x', 'y']  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Extract Combination Mapping in two lists# using zip() + product()res = list(list(zip(test_list1, ele)) for ele in product(test_list2, repeat = len(test_list1)))  # printing resultprint("Mapped Combination result : " + str(res))
The original list 1 is : [3, 4, 5]The original list 2 is : [‘x’, ‘y’]Mapped Combination result : [[(3, ‘x’), (4, ‘x’), (5, ‘x’)], [(3, ‘x’), (4, ‘x’), (5, ‘y’)], [(3, ‘x’), (4, ‘y’), (5, ‘x’)], [(3, ‘x’), (4, ‘y’), (5, ‘y’)], [(3, ‘y’), (4, ‘x’), (5, ‘x’)], [(3, ‘y’), (4, ‘x’), (5, ‘y’)], [(3, ‘y’), (4, ‘y’), (5, ‘x’)], [(3, ‘y’), (4, ‘y’), (5, ‘y’)]]
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()