code-rag-bench/online-tutorials huggingface dataset:
PHP | MySQL Delete Query

03 Mar, 2018
The DELETE query is used to delete records from a database table.It is generally used along with the “Select” statement to delete only those records that satisfy a specific condition.
Syntax :The basic syntax of the Delete Query is –
Let us consider the following table “Data” with four columns ‘ ID ‘, ‘ FirstName ‘, ‘ LastName ‘ and ‘ Age ‘.
To delete the record of the person whose ID is 201 from the ‘ Data ‘ table, the following code can be used.
Delete Query using Procedural Method :
<?php$link = mysqli_connect("localhost", "root", "", "Mydb");  if($link === false){    die("ERROR: Could not connect. " . mysqli_connect_error());}  $sql = "DELETE FROM Data WHERE ID=201";if(mysqli_query($link, $sql)){    echo "Record was deleted successfully.";} else{    echo "ERROR: Could not able to execute $sql. "                                    . mysqli_error($link);}mysqli_close($link);?>
Output :Table after updation –
The output on Web Browser :
Delete Query using Object Oriented Method :
<?php$mysqli = new mysqli("localhost", "root", "", "Mydb");   if($mysqli === false){    die("ERROR: Could not connect. " . $mysqli->connect_error);}  $sql = "DELETE FROM Data WHERE ID=201";if($mysqli->query($sql) === true){    echo "Record was deleted successfully.";} else{    echo "ERROR: Could not able to execute $sql. "                                          . $mysqli->error;}  $mysqli->close();?>
Output :Table After Updation –
The output on Web Browser :
Delete Query using PDO Method :
<?phptry{    $pdo = new PDO("mysql:host=localhost;                        dbname=Mydb", "root", "");    $pdo->setAttribute(PDO::ATTR_ERRMODE,                           PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){    die("ERROR: Could not connect. " . $e->getMessage());}  try{    $sql = "DELETE FROM Data WHERE ID=201";    $pdo->exec($sql);    echo "Record was deleted successfully.";} catch(PDOException $e){    die("ERROR: Could not able to execute $sql. "                                . $e->getMessage());}unset($pdo);?>
Output :Table After Updation –
The output on Web Browser :
mysql
PHP
SQL
Web Technologies
SQL
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ctime() Function in C/C++

28 Sep, 2018
The ctime() function is define in the time.h header file. The ctime() function returns the string representing the localtime based on the argument timer.
Syntax:
char *ctime(const time_t *timer)
Parameters: This function accepts single parameter time_ptr. It is used to set time_t object that contains a time value.
Return Value: This function returns a string that contains the date and time which is in human readable form.Example:
Www Mmm dd hh:mm:ss yyyy
Note: The description of results are given below:
Www: Day of week.
Mmm: Month name.
dd : Day of month.
hh : Hour digit.
mm : Minute digit.
ss : Second digit.
yyyy : Year digit.
Example:
// C program to demonstrate//  ctime() function.#include <stdio.h>#include <time.h>  int main () {    time_t curtime;          time(&curtime);          printf("Current time = %s", ctime(&curtime));          return(0);}
Current time = Fri Sep 28 08:13:09 2018

C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
Exit codes in C/C++ with Examples
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Program to concatenate two strings without using strcat
Conditional wait and signal in multi-threading
Groovy - exp()

The method returns the base of the natural logarithms, e, to the power of the argument.
double exp(double d)

d - Any primitive data type.
This method Returns the base of the natural logarithms, e, to the power of the argument.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      double x = 11.635;
      double y = 2.76;  
	  
      System.out.printf("The value of e is %.4f%n", Math.E); 
      System.out.printf("exp(%.3f) is %.3f%n", x, Math.exp(x));
   } 
}
When we run the above program, we will get the following result −
The value of e is 2.7183 
exp(11.635) is 112983.831


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
C# | Check if an element is in the Queue

01 Feb, 2019
Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue.Contains(T) Method is used to check whether an element is in the Queue.
Properties:
Enqueue adds an element to the end of the Queue.
Dequeue removes the oldest element from the start of the Queue.
Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
The capacity of a Queue is the number of elements the Queue can hold.
As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
Queue accepts null as a valid value for reference types and allows duplicate elements.
Syntax:
public virtual bool Contains(object obj);

Return Value: The function returns True if the element exists in the Queue and returns False if the element doesn’t exist in the Queue.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to Check if a Queue// contains an elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Queue of Integers        Queue<int> myQueue = new Queue<int>();          // Inserting the elements into the Queue        myQueue.Enqueue(5);        myQueue.Enqueue(10);        myQueue.Enqueue(15);        myQueue.Enqueue(20);        myQueue.Enqueue(25);          // Checking whether the element is        // present in the Queue or not        // The function returns True if the        // element is present in the Queue, else        // returns False        Console.WriteLine(myQueue.Contains(7));    }}
False

Example 2:
// C# code to Check if a Queue// contains an elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Queue of strings        Queue<string> myQueue = new Queue<string>();          // Inserting the elements into the Queue        myQueue.Enqueue("Geeks");        myQueue.Enqueue("Geeks Classes");        myQueue.Enqueue("Noida");        myQueue.Enqueue("Data Structures");        myQueue.Enqueue("GeeksforGeeks");          // Checking whether the element is        // present in the Queue or not        // The function returns True if the        // element is present in the Queue, else        // returns False        Console.WriteLine(myQueue.Contains("GeeksforGeeks"));    }}
True

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.contains?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-Namespace
CSharp-Generic-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript RangeError - Invalid date - GeeksforGeeks

23 Aug, 2020
This JavaScript exception invalid date occurs if the string that has been provided to Date or Date.parse() is not valid.
Message:
RangeError: invalid date (Edge)
RangeError: invalid date (Firefox)
RangeError: invalid time value (Chrome)
RangeError: Provided date is not in valid range (Chrome)

Error Type:
RangeError

Cause of the Error: An invalid date string is provided to Date or Date.parse() method in the code.
Example 1: In this example, the invalid string is provided, so the error has occurred.
HTML
<script>new Date('2014-55-26').toISOString();</script>
Output(In console):
RangeError: invalid time value

Example 2: In this example, the invalid string is provided, so the error has occurred.
HTML
<script>var date = new Date('2020-57-16'); // Error heredate.toISOString();</script>
Output(In console):
RangeError: invalid time value

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Apache POI Word - Tables

In this chapter, you will learn how to create a table of data in a document. You can create a table data by using XWPFTable class. By adding each Row to table and adding each cell to Row, you will get table data.
The following code is used to creating table in a document −
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class CreateTable {

   public static void main(String[] args)throws Exception {

      //Blank Document
      XWPFDocument document = new XWPFDocument();
        
      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
        
      //create table
      XWPFTable table = document.createTable();
		
      //create first row
      XWPFTableRow tableRowOne = table.getRow(0);
      tableRowOne.getCell(0).setText("col one, row one");
      tableRowOne.addNewTableCell().setText("col two, row one");
      tableRowOne.addNewTableCell().setText("col three, row one");
		
      //create second row
      XWPFTableRow tableRowTwo = table.createRow();
      tableRowTwo.getCell(0).setText("col one, row two");
      tableRowTwo.getCell(1).setText("col two, row two");
      tableRowTwo.getCell(2).setText("col three, row two");
		
      //create third row
      XWPFTableRow tableRowThree = table.createRow();
      tableRowThree.getCell(0).setText("col one, row three");
      tableRowThree.getCell(1).setText("col two, row three");
      tableRowThree.getCell(2).setText("col three, row three");
	
      document.write(out);
      out.close();
      System.out.println("create_table.docx written successully");
   }
}
Save the above code in a file named CreateTable.java. Compile and execute it from the command prompt as follows −
$javac CreateTable.java
$java CreateTable

It generates a Word file named createtable.docx in your current directory and display the following output on the command prompt −
createtable.docx written successfully

The createtable.docx file looks as follows −

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Difference between Arrival Time and Burst Time in CPU Scheduling - GeeksforGeeks

10 May, 2020
CPU scheduling algorithms require CPU time and IO time required for its execution. CPU time is time taken by CPU to carry out the process while I/O time illustrates the time required for I/O operation by the process.
The execution of multiple processes in an optimised way is based on different kinds of algorithms, like FCFS, Shortest Job First etc., which depend on the time frame values, like the Arrival Time, Burst Time, Waiting Time etc.
1. Arrival Time (AT) :Arrival time is the point of time in milli seconds at which a process arrives at the ready queue to begin the execution. It is merely independent of the CPU or I/O time and just depicts the time frame at which the process becomes available to complete its specified job.The process is independent of which process is there in the Running state. Arrival Time can be calculated as the difference of the Completion Time and the Turn Around Time of the process.
Arrival Time (A.T.) 
= Completion Time (C.T.) - Turn Around Time (T.A.T) 
2. Burst Time (BT) :Burst Time refers to the time required in milli seconds by a process for its execution. The Burst Time takes into consideration the CPU time of a process. The I/O time is not taken into consideration. It is called as the execution time or running time of the process. The process makes a transition from the Running state to the Completion State during this time frame. Burst time can be calculated as the difference of the Completion Time of the process and the Waiting Time, that is,
Burst Time (B.T.) 
= Completion Time (C.T.) - Waiting Time (W.T.) 
The following table illustrates the Arrival and Burst time of three processes P1, P2 and P3. A single CPU is allocated for the execution of these processes.
If we compute the Gantt chart, based on FCFS scheduling where the process that comes first in the ready queue is executed first. The processes arrival decides the order of execution of the process for time equal to its Burst time.
Since, the process P2 arrives at 4ms, and process P1 requires 3ms for its execution (=Burst Time), CPU waits for 1ms, that is the idle time for the CPU, where it doesn’t perform any process execution. The last process to get executed is P3.
The following table illustrates the key differences in the Arrival and Burst Time respectively :
Picked
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Internal and External fragmentation
Difference between Top down parsing and Bottom up parsing
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Importing External Style Sheets in CSS

We can import additional CSS files inside another CSS declaration. The @import rule is used for this purpose as it links a stylesheet in a document. This is generally used when one stylesheet is dependent upon another. It is specified at the top of the document after @charset declaration inside <head>.
The syntax of @import rule is as follows
@import /*url or list-of-media-queries*/
The media queries can be compound statements which may specify the behavior of the document in different media.
The following examples implement the @import rule −
HTML document −
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
@import url(style.css);
body {
   background-color: honeydew;
}
</style>
</head>
<body>
<p>This is demo paragraph one. </p>
<p class="two">This is demo paragraph two.</p>
<p>This is demo paragraph three</p>
</body>
</html>
CSS document: style.css
p { color: navy; font-style: italic; }
.two { color: darkgreen; font-size: 24px; }
This produces the following output −
HTML document −
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>
</html>
CSS document−
div {
   height: 50px;
   width: 100px;
   border-radius: 20%;
   border: 2px solid blueviolet;
   box-shadow: 22px 12px 3px 3px lightblue;
   position: absolute;
   left: 30%;
   top: 20px;
}
This gives the following output −
Split Character String at Whitespace in R

23 Sep, 2021
In this article, we are going to discuss how to split character strings at white space in R programming language.
strsplit() function is used to split the string based on some condition.
Syntax:
strsplit(input_string, ” +”)
where 
input_string is the string
” +” represents to be split at white space
Example: R program to split a given string
R
# consider a string with white spacesstring1="Hello Geeks we are in   Java  Python  R and    CPP"  # split the string by using strsplit() functionprint(strsplit(string1, " +"))  
Output:
[[1]]
[1] “Hello”  “Geeks”  “we”     “are”    “in”     “Java”   “Python” “R”      
[9] “and”    “CPP” 
It is stored in index 1 in a list so we can modify our code a little by using the index 1 position.
Example: R program to split a given string
R
# consider a string with white spacesstring1="Hello Geeks we are in   Java  Python  R and    CPP"  # split the string by using strsplit() functionprint(strsplit(string1, " +")[[1]])  
Output:
[1] “Hello”  “Geeks”  “we”     “are”    “in”     “Java”   “Python” “R”      
[9] “and”    “CPP”
This function is also used to split the string by scanning the elements.
Syntax:
scan(text = input_string, what = “”)
Where,
the text parameter is used to store input string
what is a parameter that can take white space which specifies the string to be split at whitespace
It will also display how many times is scanned (It will return the number of split words).
Example: R program to split a string at white space using scan() function
R
# consider a string with white spacesstring1="Hello Geeks we are in   Java  Python  R and    CPP"  # split the string by using scan() functionprint(scan(text = string1, what = ""))  
Output:
Read 10 items
[1] “Hello”  “Geeks”  “we”     “are”    “in”     “Java”   “Python” “R”      
[9] “and”    “CPP”
Example: R program to split a string at white space using scan() function
R
# consider a string with white spacesstring1="There are big branches in India"  # split the string by using scan() functionprint(scan(text = string1, what = ""))  
Output:
Read 6 items
[1] “There”    “are”      “big”      “branches” “in”       “India” 
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Validate Email address in Java

The Email address can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the E-mail and the given input Email and returns true if they match and false otherwise.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   static boolean isValid(String email) {
      String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
      return email.matches(regex);
   }
   public static void main(String[] args) {
      String email = "john123@gmail.com";
      System.out.println("The E-mail ID is: " + email);
      System.out.println("Is the above E-mail ID valid? " + isValid(email));
   }
}
The E-mail ID is: john123@gmail.com
Is the above E-mail ID valid? true
Now let us understand the above program.
In the main() method, The Email ID is printed. Then the isValid() method is called to validate the Email ID. A code snippet which demonstrates this is as follows:
public static void main(String[] args) {
   String email = "john123@gmail.com";
   System.out.println("The E-mail ID is: " + email);
   System.out.println("Is the above E-mail ID valid? " + isValid(email));
}
In the isValid() method, Pattern.matches() method matches the regular expression for the Email ID and the given input Email ID and the result is returned. A code snippet which demonstrates this is as follows:
static boolean isValid(String email) {
   String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
   return email.matches(regex);
}
PyQt5 QRadioButton

21 May, 2021
Radio button has a circular shape and used when one choice is to be selected from multiple options. This button is in the selected state when the circle is filled and deselected when the circle is hollow. QRadioButton class is used to add a radio button in an application. 
Example:A window asking the user to select user’s gender. According to the user’s choice, it shows a message: “You are male/female” and which will change if the user changes his/her selection.Below is the code:  
Python3
import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object):    def setupUi(self, MainWindow):        MainWindow.setObjectName("MainWindow")        MainWindow.resize(466, 299)        self.centralwidget = QtWidgets.QWidget(MainWindow)                 # Radio button for male        self.radioButton_male = QtWidgets.QRadioButton(self.centralwidget)        self.radioButton_male.setGeometry(QtCore.QRect(180, 120, 95, 20))         # adding signal and slot        self.radioButton_male.toggled.connect(self.maleselected)                # Radio button for female        self.radioButton_female = QtWidgets.QRadioButton(self.centralwidget)        self.radioButton_female.setGeometry(QtCore.QRect(180, 150, 95, 20))         # adding signal and slot        self.radioButton_female.toggled.connect(self.femaleselected)                 self.label = QtWidgets.QLabel(self.centralwidget)        self.label.setGeometry(QtCore.QRect(170, 90, 211, 20))        MainWindow.setCentralWidget(self.centralwidget)         self.retranslateUi(MainWindow)        QtCore.QMetaObject.connectSlotsByName(MainWindow)         def maleselected(self, selected):        if selected:            self.label.setText("You are male")                 def femaleselected(self, selected):        if selected:            self.label.setText("You are female")                        def retranslateUi(self, MainWindow):        _translate = QtCore.QCoreApplication.translate         MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))        self.radioButton_male.setText(_translate("MainWindow", "Male"))        self.label.setText(_translate("MainWindow", "Select your gender:"))        self.radioButton_female.setText(_translate("MainWindow", "Female")) # Driver Codeif __name__ == "__main__":    app = QtWidgets.QApplication(sys.argv)       MainWindow = QtWidgets.QMainWindow()    ui = Ui_MainWindow()    ui.setupUi(MainWindow)    MainWindow.show()    sys.exit(app.exec_())
Output: 
According to user’s choice a message will appear “You are male” or “You are female” and which will change as user changes his/her selection.  
 
surinderdawra388
Python-gui
Python-PyQt
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
turtle.screensize() function in Python

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to resize the canvas the turtles are drawing on. If no arguments are given, this function returns the current (canvaswidth, canvasheight).
Syntax :
turtle.screensize(canvwidth=None, canvheight=None, bg=None)

Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle    # check the screensize by default# it varies ide to ideprint(turtle.screensize())
Output :
(400, 300)

Example 2 :
Python3
# import packageimport turtle    # set screenturtle.screensize(canvwidth=400, canvheight=400,                  bg="yellow")
Output :
Example 3 :
Python3
# import packageimport turtle  # set turtleturtle.width(2)turtle.speed(10)  # loop for patternfor i in range(10):    turtle.circle(40)    turtle.right(36)  # set screen and drawing remain as it is.turtle.screensize(canvwidth=400, canvheight=300,                  bg="blue")
Output :
Python-turtle
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Find maximum element of each column in a matrix in C++

Consider we have a matrix, our task is to find the maximum element of each column of that matrix and print them. This task is simple. For each column, reset the max, and find the max element, and print it. Let us see the code for better understanding.
#include<iostream>
#define MAX 10
using namespace std;
void largestInEachCol(int mat[][MAX], int rows, int cols) {
   for (int i = 0; i < cols; i++) {
      int max_col_element = mat[0][i];
   for (int j = 1; j < rows; j++) {
      if (mat[j][i] > max_col_element)
         max_col_element = mat[j][i];
   }
   cout << max_col_element << endl;
   }
}
int main() {
   int row = 4, col = 4;
   int mat[][MAX] = { { 3, 4, 1, 81 },
      { 1, 84, 9, 11 },
      { 23, 7, 21, 1 },
      { 2, 1, 44, 5 }
   };
   largestInEachCol(mat, row, col);
}
23
84
44
81
Construct Turing Machine for L = {a^i b^j | i<j, i>0} - GeeksforGeeks

23 Sep, 2020
Prerequisite – Turing Machine
Task :We have to design a Turing machine for a^i b^j where i<j and i>0.
Analysis :Here the main thing to notice that i<j. It means that the count of ‘b’ in the string is always greater than the count of ‘a’. Therefore we can write a^i b^j like that –
a^i b^j = a^n b^n + extra number of b.
Examples –
Input: aabbbb
Output: Accepted

Input: aaabb
Output: Not Accepted
Approach :Let us understand the approach by taking a string “aabbb”.
Scan the input from the left.First, replace an ‘a’ with ‘X’ and move 1 step right. Then skip all the a’s and b’s and move right.When the pointer reaches Blank(B) it scans the input from the right and replaces the first ‘b’ with ‘Y’.Again the pointer reaches Blank(B). It now scans the input from left to right. The pointer moves forward and replaces ‘a’ with ‘X’.Again the pointer reaches Blank(B). It now scans the input from the right to left. The pointer moves forward and replaces ‘b’ with ‘y’.We repeat the same steps until we convert all the a’s to ‘X’. b’s equal to the count of a’s will also convert to ‘Y’ and we will be left with some of the remaining b’s.
Scan the input from the left.
First, replace an ‘a’ with ‘X’ and move 1 step right. Then skip all the a’s and b’s and move right.
When the pointer reaches Blank(B) it scans the input from the right and replaces the first ‘b’ with ‘Y’.
Again the pointer reaches Blank(B). It now scans the input from left to right. The pointer moves forward and replaces ‘a’ with ‘X’.
Again the pointer reaches Blank(B). It now scans the input from the right to left. The pointer moves forward and replaces ‘b’ with ‘y’.
We repeat the same steps until we convert all the a’s to ‘X’. b’s equal to the count of a’s will also convert to ‘Y’ and we will be left with some of the remaining b’s.
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construct a Turing Machine for language L = {ww | w ∈ {0,1}}
Arden's Theorem in Theory of Computation
Proof that vertex cover is NP complete
Boyer-Moore Majority Voting Algorithm
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Construct a Turing Machine for language L = {wwr | w ∈ {0, 1}}
CYK Algorithm for Context Free Grammar
Decidable and Undecidable problems in Theory of Computation
Halting Problem in Theory of Computation
Introduction To Grammar in Theory of Computation
How to set the font size of Entry widget in Tkinter?

The Entry widget in tkinter is a basic one-line character Entry box that accepts single line user input. To configure the properties of the Entry widget such as its font-size and width, we can define an inline widget constructor.
Here is an example of how you can define the font-size of the Entry widget.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Create an Entry widget
entry=Entry(win, width=35, font=('Georgia 20'))
entry.pack()

win.mainloop()
Run the above code to display a window with a customized Entry widget.
iOS - Actions and Outlets

Actions and outlets in iOS are referred to as ibActions and ibOutlets respectively, where ib stands for interface builder. These are related to the UI elements and we will explore them after knowing visually how to implement them.
Step 1 − Let's use our First iPhone Application.
Step 2 − Select the ViewController.xib file from the files in the navigator section.
Step 3 − Now, you can select the UI elements from the library pane in the right hand side of our window, which is shown below.
Step 4 − You can drag and drop the UI elements to our view in our interface builder.
Step 5 − Let us add a Label and Round Rect Button to our view.
Step 6 − From the Editor Selector button in the workspace toolbar found on the top right corner as shown below.
Select Assistant editor button.
Step 7 − We will see two windows in our editor area in the center, one is ViewController.xib file and the other is ViewController.h.
Step 8 − Now, right click on the label and select, hold and drag the new referencing outlet as shown below.
Step 9 − Drop in the ViewController.h in between the curly braces. In case there are no curly braces in the file, add the ViewController before doing this. You will find a pop-up as shown below.
Step 10 − Type the label name for the outlet, here we have used the label myTitleLabel. Click connect and the ibOutlet will be complete.
Step 11 − Similarly, to add an action, right click the Round rect button, select touch up inside and drag it below the curly braces.
Step 12 − Drop it and name it setTitleLabel.
Step 13 − Select ViewController.m file, you'll find a method as shown below.
-(IBAction) setTitleLabel:(id)sender {
}

Step 14 − Add a statement as shown below inside the above method.
[myTitleLabel setText:@"Hello"];

Step 15 − Let us now run the program by selecting the run button. You will see the following output.
Step 16 − Now click the button.
Step 17 − The label that we created have been changed by the action on the button.
Step 18 − From the above example, we can conclude that IBOutlet creates a reference to the UIElement (here for the UILabel). Similarly, the IBAction links the UIButton with a method, which is called on the event touch up inside.
Step 19 − You can play around with actions by selecting different events while creating the action.

    23 Lectures 
     1.5 hours 

 Ashish Sharma

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson

    69 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
C# Program to Print Hello World Without Using WriteLine - GeeksforGeeks

01 Nov, 2021
Hello World program is the most basic program of any programming language. It prints “Hello world” on the screen. In this article, we will display “Hello World” without using WriteLine Method. So to do this task we use the following methods:
Console.OpenStandardOutput(): This method is used to acquire the standard output stream.
Console.ReadKey(): This method is used to get the next character pressed by the user and this press key will be displayed in the console window.
BeginWrite(): This method is used to begin an asynchronous write operation.
AsyncWaitHandle.WaitOne(): This method is used to wait for an asynchronous operation to complete.
For writing Hello World we are taking each separate character in ASCII format and then we are displaying these characters together. 
1. Inside if condition, Write OpenStandardOutput() to display the Hello World.
2. This method is followed by BeginWrite() method that takes integer Bytes.
BeginWrite(new byte[] { 072, 101, 108, 108, 111, 032, 087, 111, 
                        114, 108, 100, 0 }, 0, 12, null, null)
3. Finally we are using AsyncWaitHandle.WaitOne() method followed by BeginWrite() method.
BeginWrite(new byte[] { 072, 101, 108, 108, 111, 032, 087, 111, 
                        114, 108, 100, 0 }, 0, 12, null, 
                        null).AsyncWaitHandle.WaitOne()) 
Example:
C#
// C# program to display Hello World without// using WriteLine() methodusing System;  class GFG{  static void Main(string[] args){          // ASCII values for Hello World    if (System.Console.OpenStandardOutput().BeginWrite(new byte[] {         072, 101, 108, 108, 111, 032, 087, 111, 114, 108, 100, 0 },         0, 12, null, null).AsyncWaitHandle.WaitOne())     {     }}}
Output:
Hello World
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Matplotlib – How to show the count values on the top of a bar in a countplot?

To show the count values on the top of a bar in a countplot, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a Pandas dataframe with one column.
Create a Pandas dataframe with one column.
A countplot can be thought of as a histogram across a categorical, instead of a quantitative, variable.
A countplot can be thought of as a histogram across a categorical, instead of a quantitative, variable.
Iterate the returned axes of the countplot and show the count values at the top of the bars.
Iterate the returned axes of the countplot and show the count values at the top of the bars.
To display the figure, use Show() method.
To display the figure, use Show() method.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(dict(col1=np.array([2, 4, 1, 1, 1, 4])))

ax = sns.countplot(x="col1", data=df)

for p in ax.patches:
   ax.annotate('{:.1f}'.format(p.get_height()), (p.get_x()+0.25, p.get_height()+0.01))

plt.show()
It will produce the following output −
Java Program to initialize a HashMap with Lambda Expressions

To initialize a HashMap with Lambda, at first create a HashMpa and use Callable −
HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>()
For key-value pair, you need to initialize them in the following way −
HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
   {
      put(0, () -> {
         return 10;
      });
      put(1, () -> {
         return 20;
      });
   }
};
import java.util.HashMap;
import java.util.concurrent.Callable;
public class Demo {
   public static void main(String[] args) throws Exception {
      HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
         {
            put(0, () -> {
               return 10;
            });
            put(1, () -> {
               return 20;
            });
            put(2, () -> {
               return 30;
            });
            put(3, () -> {
               return 40;
            });
         }};
         System.out.println(map.get(0).call());
         System.out.println(map.get(1).call());
         System.out.println(map.get(2).call());
         System.out.println(map.get(3).call());
      }
   }
}
10
20
30
40
Compute sum of all elements in 2 D array in C

Calculate the sum of all elements of a two-dimensional array by using run-time initialization.
Two-dimensional Array is used in situations where a table of values have to be stored (or) in matrices applications
The syntax is as follows −
datatype array_ name [rowsize] [column size];
For example, int a[4] [4];
Number of elements in an array = rowsize *columnsize = 4*4 = 16
Following is the C program to calculate the sum of all elements of a two-dimensional array by using run-time initialization −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring array and variables//
   int A[4][3],i,j,even=0,odd=0;
   //Reading elements into the array//
   printf("Enter elements into the array A :\n");
   for(i=0;i<4;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] : ",i,j);
         scanf("%d",&A[i][j]);
      }
   }
   //Calculating sum of even and odd elements within the array using for loop//
   for(i=0;i<4;i++){
      for(j=0;j<3;j++){
         if((A[i][j])%2==0){
            even = even+A[i][j];
         }
         else{
            odd = odd+A[i][j];
         }
      }
   }
   printf("Sum of even elements in array A is : %d\n",even);
   printf("Sum of odd elements in array A is : %d",odd);
}
When the above program is executed, it produces the following result −
Enter elements into the array A:
A[0][0] : 01
A[0][1] : 02
A[0][2] : 03
A[1][0] : 04
A[1][1] : 10
A[1][2] : 20
A[2][0] : 30
A[2][1] : 40
A[2][2] : 22
A[3][0] : 33
A[3][1] : 44
A[3][2] : 55
Sum of even elements in array A is: 172
Sum of odd elements in array A is: 92
PyTorch - Linear Regression

In this chapter, we will be focusing on basic example of linear regression implementation using TensorFlow. Logistic regression or linear regression is a supervised machine learning approach for the classification of order discrete categories. Our goal in this chapter is to build a model by which a user can predict the relationship between predictor variables and one or more independent variables.
The relationship between these two variables is considered linear i.e., if y is the dependent variable and x is considered as the independent variable, then the linear regression relationship of two variables will look like the equation which is mentioned as below −
Y = Ax+b

Next, we shall design an algorithm for linear regression which allows us to understand two important concepts given below −
Cost Function
Gradient Descent Algorithms
The schematic representation of linear regression is mentioned below
Y=ax+b
The value of a is the slope.
The value of a is the slope.
The value of b is the y − intercept.
The value of b is the y − intercept.
r is the correlation coefficient.
r is the correlation coefficient.
r2 is the correlation coefficient.
r2 is the correlation coefficient.
The graphical view of the equation of linear regression is mentioned below −
Following steps are used for implementing linear regression using PyTorch −
Import the necessary packages for creating a linear regression in PyTorch using the below code −
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import seaborn as sns
import pandas as pd
%matplotlib inline

sns.set_style(style = 'whitegrid')
plt.rcParams["patch.force_edgecolor"] = True
Create a single training set with the available data set as shown below −
m = 2 # slope
c = 3 # interceptm = 2 # slope
c = 3 # intercept
x = np.random.rand(256)

noise = np.random.randn(256) / 4

y = x * m + c + noise

df = pd.DataFrame()
df['x'] = x
df['y'] = y

sns.lmplot(x ='x', y ='y', data = df)
Implement linear regression with PyTorch libraries as mentioned below −
import torch
import torch.nn as nn
from torch.autograd import Variable
x_train = x.reshape(-1, 1).astype('float32')
y_train = y.reshape(-1, 1).astype('float32')

class LinearRegressionModel(nn.Module):
   def __init__(self, input_dim, output_dim):
      super(LinearRegressionModel, self).__init__()
      self.linear = nn.Linear(input_dim, output_dim)

   def forward(self, x):
      out = self.linear(x)
      return out
input_dim = x_train.shape[1]
output_dim = y_train.shape[1]
input_dim, output_dim(1, 1)
model = LinearRegressionModel(input_dim, output_dim)
criterion = nn.MSELoss()
[w, b] = model.parameters()

def get_param_values():
   return w.data[0][0], b.data[0]

def plot_current_fit(title = ""):
plt.figure(figsize = (12,4))
plt.title(title)
plt.scatter(x, y, s = 8)
w1 = w.data[0][0]
b1 = b.data[0]
x1 = np.array([0., 1.])
y1 = x1 * w1 + b1
plt.plot(x1, y1, 'r', label = 'Current Fit ({:.3f}, {:.3f})'.format(w1, b1))
plt.xlabel('x (input)')
plt.ylabel('y (target)')
plt.legend()
plt.show()
plot_current_fit('Before training')
The plot generated is as follows −
 Print
 Add Notes
 Bookmark this page
Python Program to Remove the nth Index Character from a Non-Empty String

When it is required to remove a specific index character from a string which isn’t empty, it can be iterated over, and when the index doesn’t match, that character can be stored in another string.
Below is the demonstration of the same −
 Live Demo
my_string = "Hi there how are you"

print("The string is :")
print(my_string)
index_removed = 2

changed_string = ''

for char in range(0, len(my_string)):
   if(char != index_removed):
      changed_string += my_string[char]

print("The string after removing ", index_removed, "nd character is : ")
print(changed_string)
The string is :
Hi there how are you
The string after removing 2 nd character is :
Hithere how are you
A string is defined, and is displayed on the console.
A string is defined, and is displayed on the console.
An index value is defined.
An index value is defined.
The string is iterated over, and if the character in the string is not same as the index value that needs to be removed, the character is placed in a new string.
The string is iterated over, and if the character in the string is not same as the index value that needs to be removed, the character is placed in a new string.
This new string is displayed as output on the console.
This new string is displayed as output on the console.
SQL Wildcard Characters

A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the 
LIKE 
operator. The LIKE operator is used in a 
WHERE clause to search for a specified pattern in a column.
All the wildcards can also be used in combinations!
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
The table below shows the complete "Customers" table from the Northwind sample database:
The following SQL statement selects all customers with a City starting with 
"ber":
The following SQL statement selects all customers with a City containing the 
pattern "es": 
The following SQL statement selects all customers with a City starting with 
any character, followed by "ondon":
The following SQL statement selects all customers with a City starting with 
"L", followed by any character, followed by "n", followed by any character, 
followed by "on":
The following SQL statement selects all customers with a City starting with 
"b", "s", or "p":
The following SQL statement selects all customers with a City starting with 
"a", "b", or "c":
The two following SQL statements select all customers with a City NOT starting 
with "b", "s", or "p":
Or:
Select all records where the second letter of the City is an "a".
SELECT * FROM Customers
WHERE City LIKE '%';

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.
Creating multiple process using fork() in C

In this section we will see how to use the fork() to make child process in C. We also do some different tasks in each process. So in our parent process we will print different values.
When fork() is called, it returns a value. If the value is greater than 0, then currently it is in parent process, otherwise it is in child process. So using this we can distinguish between the processes.
#include <stdio.h>
#include <unistd.h>
int main() {
   int n = fork(); //subdivide process
   if (n > 0) { //when n is not 0, then it is parent process
      printf("Parent process \n";
   } else { //when n is 0, then it is child process
      printf("Child process \n");
   }
   return 0;
}
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Parent process
soumyadeep@soumyadeep-VirtualBox:~$ Child process
soumyadeep@soumyadeep-VirtualBox:~$
What are different types of quotes in Python?

Quotation symbols are used to create string object in Python. Python recognizes single, double and triple quoted strings. String literals are written by enclosing a sequence of characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").
>>> var1='hello'
>>> var1
'hello'
>>> var2="hello"
>>> var2
'hello'
>>> var3='''hello'''
>>> var3
'hello'
>>> var4="""hello"""
>>> var4
'hello'
If it is required to embed double quotes as a part of string, the string itself should be put in single quotes. On the other hand, if single quoted text is to be embedded, string should be written in double quotes.
>>> var1='Welcome to "Python training" from Tutorialspoint'
>>> var1
'Welcome to "Python training" from Tutorialspoint'
>>> var2="Welcome to 'Python training' from Tutorialspoint"
>>> var2
"Welcome to 'Python training' from Tutorialspoint"
GATE | GATE-CS-2004 | Question 90 - GeeksforGeeks

28 Jul, 2021
Consider the following set of processes, with the arrival times and the CPU-burst times given in milliseconds
  Process   Arrival Time    Burst Time
    P1          0              5
    P2          1              3
    P3          2              3
    P4          4              1
What is the average turnaround time for these processes with the preemptive shortest remaining processing time first (SRPT) algorithm ?(A) 5.50(B) 5.75(C) 6.00(D) 6.25Answer: (A)Explanation: The following is Gantt Chart of execution
 
Turn Around Time = Completion Time – Arrival Time
 
Avg Turn Around Time  =  (12 + 3 + 6+  1)/4 = 5.50
Watch GeeksforGeeks Video Explanation :
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0046:47 / 49:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63