code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE CS 2010 | Question 23

28 Jun, 2021
Consider the methods used by processes P1 and P2 for accessing their critical sections whenever needed, as given below. The initial values of shared boolean variables S1 and S2 are randomly assigned.
Method Used by P1
while (S1 == S2) ;
Critica1 Section
S1 = S2;

Method Used by P2
while (S1 != S2) ;
Critica1 Section
S2 = not (S1);
Which one of the following statements describes the properties achieved?(A) Mutual exclusion but not progress(B) Progress but not mutual exclusion(C) Neither mutual exclusion nor progress(D) Both mutual exclusion and progressAnswer: (A)Explanation:Mutual Exclusion:A way of making sure that if one process is using a shared modifiable data, the other processes will be excluded from doing the same thing. while one process executes the shared variable, all other processes desiring to do so at the same time moment should be kept waiting; when that process has finished executing the shared variable, one of the processes waiting; while that process has finished executing the shared variable, one of the processes waiting to do so should be allowed to proceed. In this fashion, each process executing the shared data (variables) excludes all others from doing so simultaneously. This is called Mutual Exclusion.
Progress Requirement:If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection of the processes that will enter the critical section next cannot be postponed indefinitely.
Solution:
It can be easily observed that the Mutual Exclusion requirement is satisfied by the above solution, P1 can enter critical section only if S1 is not equal to S2, and P2 can enter critical section only if S1 is equal to S2. But here Progress Requirement is not satisfied. Suppose when s1=1 and s2=0 and process p1 is not interested to enter into critical section but p2 want to enter critical section. P2 is not able to enter critical section in this as only when p1 finishes execution, then only p2 can enter (then only s1 = s2 condition be satisfied). Progress will not be satisfied when any process which is not interested to enter into the critical section will not allow other interested process to enter into the critical section.
Reference :http://www.personal.kent.edu/~rmuhamma/OpSystems/Myos/mutualExclu.htmSee https://www.geeksforgeeks.org/operating-systems-set-7/
This solution is contributed by Nitika BansalQuiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
Sum of an array using pthreads

05 Jan, 2018
Sum of array is a small problem where we have to add each element in the array by traversing through the entire array. But when the number of elements are too large, it could take a lot of time. But this could solved by dividing the array into parts and finding sum of each part simultaneously i.e. by finding sum of each portion in parallel.
This could be done by using multi-threading where each core of the processor is used. In our case, each core will evaluate sum of one portion and finally we will add the sum of all the portion to get the final sum. In this way we could improve the performance of a program as well as utilize the cores of processor.
It is better to use one thread for each core. Although you can create as many thread as you want for better understanding of multi-threading.
Examples:
Input :  1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220
Output : sum is 600

Input :  10, 50, 70, 100, 120, 140, 150, 180, 200, 220, 250, 270, 300, 640, 110, 220
Output : sum is 3030

Note – It is advised to execute the program in Linux based system.Compile in linux using following code:
g++ -pthread program_name.cpp

Code –
// CPP Program to find sum of array#include <iostream>#include <pthread.h>  // size of array#define MAX 16  // maximum number of threads#define MAX_THREAD 4  using namespace std;  int a[] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };int sum[4] = { 0 };int part = 0;  void* sum_array(void* arg){      // Each thread computes sum of 1/4th of array    int thread_part = part++;      for (int i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)        sum[thread_part] += a[i];}  // Driver Codeint main(){      pthread_t threads[MAX_THREAD];      // Creating 4 threads    for (int i = 0; i < MAX_THREAD; i++)        pthread_create(&threads[i], NULL, sum_array, (void*)NULL);      // joining 4 threads i.e. waiting for all 4 threads to complete    for (int i = 0; i < MAX_THREAD; i++)        pthread_join(threads[i], NULL);      // adding sum of all 4 parts    int total_sum = 0;    for (int i = 0; i < MAX_THREAD; i++)        total_sum += sum[i];      cout << "sum is " << total_sum << endl;      return 0;}
Output:
sum is 600

cpp-multithreading
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Count of subarrays with average K
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
MongoDB query to match documents whose _id is in an array as part of a subdocument?

Let us create a collection with documents −
> db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] });
{ "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo568.find();
This will produce the following output −
{ "_id" : 101, "details" : [ { "id" : 101 }, { "id" : 103 } ] }
Following is the query to create second collection:
> db.demo569.insertOne({ _id: 101, details: "John" })
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo569.insertOne({ _id: 102, details: "Chris" })
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo569.insertOne({ _id: 103, details: "David" })
{ "acknowledged" : true, "insertedId" : 103 }
Display all documents from a collection with the help of find() method −
> db.demo569.find();
This will produce the following output −
{ "_id" : 101, "details" : "John" }
{ "_id" : 102, "details" : "Chris" }
{ "_id" : 103, "details" : "David" }
Following is the query to match documents whose _id is in an array as part of a subdocument −
> db.demo569.find({ '_id': { '$in': db.demo568.distinct('details.id', {'_id': 101}) }})
This will produce the following output −
{ "_id" : 101, "details" : "John" }
{ "_id" : 103, "details" : "David" }
Output of C Program | Set 26 - GeeksforGeeks

27 Dec, 2016
Predict the output of following C programs.
Question 1
#include <stdio.h>   int main(){  int arr[] = {};  printf("%d", sizeof(arr));  return 0;}
Output: 0C (or C++) allows arrays of size 0. When an array is declared with empty initialization list, size of the array becomes 0.
Question 2
#include<stdio.h>  int main(){  int i, j;  int arr[4][4] = { {1, 2, 3, 4},                    {5, 6, 7, 8},                    {9, 10, 11, 12},                    {13, 14, 15, 16} };  for(i = 0; i < 4; i++)    for(j = 0; j < 4; j++)      printf("%d ", j[i[arr]] );    printf("\n");    for(i = 0; i < 4; i++)    for(j = 0; j < 4; j++)      printf("%d ", i[j[arr]] );    return 0;}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
Array elements are accessed using pointer arithmetic. So the meaning of arr[i][j] and j[i[arr]] is same. They both mean (arr + 4*i + j). Similarly, the meaning of arr[j][i] and i[j[arr]] is same.
Question 3
#include<stdio.h>int main(){    int a[2][3] = {2,1,3,2,3,4};    printf("Using pointer notations:\n");    printf("%d %d %d\n", *(*(a+0)+0), *(*(a+0)+1), *(*(a+0)+2));    printf("Using mixed notations:\n");    printf("%d %d %d\n", *(a[1]+0), *(a[1]+1), *(a[1]+2));    return 0;}
Output:
Using pointer notations:
2 1 3
Using mixed notations:
2 3 4 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to copy a string in C/C++
Runtime Errors
Output of Java Program | Set 3
unsigned specifier (%u) in C with Examples
Output of C++ Program | Set 1
Output of Java program | Set 5
Output of C Programs | Set 3
Output of Java Program | Set 7
How to show full column content in a PySpark Dataframe ?
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Passing Arrays as Subprogram Arguments

Pascal allows passing arrays as subprogram parameters. Following function will take an array as an argument and return average of the numbers passed through the array as follows −
program arrayToFunction;
const
   size = 5;
type
   a = array [1..size] of integer;
var
   balance:  a = (1000, 2, 3, 17, 50);
   average: real;  

function avg( var arr: a) : real;
var
   i :1..size;
   sum: integer;

begin
   sum := 0;
   for i := 1 to size do
      sum := sum + arr[i];
   avg := sum / size;
end;

begin  
   (*  Passing the array to the function  *)
   average := avg( balance ) ;
   
   (* output the returned value *)
   writeln( 'Average value is: ', average:7:2);
end.
When the above code is compiled and executed, it produces the following result −
Average value is: 214.40


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
halt, poweroff and reboot Commands in Linux - GeeksforGeeks

24 May, 2019
Below are typical uses of halt, poweroff and reboot.
halt : Instructs hardware to stop CPU functions.poweroff : Instructs the system to power down.reboot : Restarts or reboots the system.
halt : Instructs hardware to stop CPU functions.
poweroff : Instructs the system to power down.
reboot : Restarts or reboots the system.
The above mentioned commands can only be run by super user as these involve the actions to stop the system hardware. If the user is not logged in as super user then sudo command can be used to run these commands.
This instructs the hardware to stop all the CPU functions.
// syntax of halt command
halt [OPTION]...

The halt simply can be used to halt, poweroff and reboot the system :
//  Instructs hardware to stop CPU functions.
halt

//  Instructs hardware to stop CPU functions.
halt

// power off the system
halt -p

// power off the system
halt -p

// reboots the system 
halt --reboot

// reboots the system 
halt --reboot

Applications
This lets the user to power down the system from the command line.
Using halt all the CPU functions will be stopped and system will enter a state where user can perform low level maintenance.
poweroff Sends an ACPI signal which instructs the system to power down. Here’s the syntax of poweroff command :
// syntax of poweroff
poweroff [OPTION]...

The poweroff simply can be used to halt, poweroff and reboot the system as :
// Powers off the system
poweroff
// Powers off the system
poweroff
// Halts the system
poweroff --halt

// Halts the system
poweroff --halt

// Reboots the system 
poweroff --reboot

// Reboots the system 
poweroff --reboot

the reboot command instructs the system to restart or reboot. Here’s the syntax of reboot command :
// syntax of reboot
reboot [OPTION]...

The reboot simply can be used to halt, poweroff and reboot the system as :
// Halts the system
reboot --halt

// Halts the system
reboot --halt

// Powers off the system
reboot -p

// Powers off the system
reboot -p

// Reboots the system 
reboot

// Reboots the system 
reboot

linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
tee command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
Tail command in Linux with examples
echo command in Linux with Examples
How to implement Builder pattern in Kotlin?

In object-oriented programming, the creation of objects is very easy via
constructors when the object definitions are simple, but sometimes, it may so
happen that the constructors need more variables or functions in order to
initialize an object. In such cases, the "builder pattern" comes into picture
which helps programmers to create small units of different objects and create
a final object.
A builder pattern provides an API to construct an object step- by-step.
A builder pattern provides an API to construct an object step- by-step.
Builder patterns are particularly useful when objects need to be
created dynamically.
Builder patterns are particularly useful when objects need to be
created dynamically.
Note that it is not recommended to use builder patterns in Kotlin because we can get the same feature using default and named arguments.
In this article, we will take a simple example and demonstrate how we can
implement a design pattern using Kotlin.
Create a small builder object, which can be built in the main class and the builder class should have a public constructor .
Create a small builder object, which can be built in the main class and the builder class should have a public constructor .
Construct an object using multiple pieces; some variables can be set using getter, setter and some via constructor.
Construct an object using multiple pieces; some variables can be set using getter, setter and some via constructor.
The builder design pattern provides an API to create an object. We are creating build() to build the actual required object. We can name it differently whatever we need.
The builder design pattern provides an API to create an object. We are creating build() to build the actual required object. We can name it differently whatever we need.
The main class constructor will take the builder object as a parameter.
The main class constructor will take the builder object as a parameter.
class myBuilder{
  private var Name:String? = null

   fun setName(Name:String){
      this.Name = Name
   }
   fun getName():String?{
      return this.Name
   }
}

class myClass{
   var m:myBuilder
   constructor(myBuilder:myBuilder) {
      this.m = myBuilder
   } // implementing the builder class
   fun build():String{
      return ("This is the example of the builder pattern")
   }
}

fun main(args: Array<String>) {
   var myBuilder = myBuilder()
   myBuilder.setName("TutorialsPoint")

   // passing small unit of objects to create
   // another object step-by-step. This can be
   // applied to many class variable
   var mainObj = myClass(myBuilder)
   println(mainObj.build())
}
Once executed, the code will generate the following output
This is the example of the builder pattern
CSS | drop-shadow() Function - GeeksforGeeks

08 Aug, 2019
The drop-shadow() function is an inbuilt function which is used to apply a filter to the image to set the shadow of the image. The drop-shadow() function creates a blurred shadow in a given offset and color.
Syntax:
drop-shadow( offset-x offset-y blur-radius spread-radius color )
Parameters: This function accepts five parameters as mentioned above and described below:
offset-x: This parameter sets the horizontal offset of an image. The positive value creates the offset to the right side and negative value creates the offset to the left side.
offset-y: This parameter sets the vertical offset of an image. The positive value creates the offset to the bottom side and negative value creates the offset to the top side.
blur-radius: It sets the value of blur radius. It is an optional parameter.
spread-radius: It sets the value of spread radius. It is an optional parameter.
color: It sets the color of drop shadow. Its optional parameter.
Below examples illustrate the drop-shadow() function in CSS:
Example 1:
<!DOCTYPE html> <html>   <head>     <title>CSS drop-shadow() Function</title>           <style>        h1 {            color:green;        }        body {            text-align:center;        }        .drop_shadow_effect {            filter: drop-shadow(10px 10px 10px yellow)        }    </style></head>   <body>     <h1>GeeksforGeeks</h1>           <h2>CSS drop-shadow() function</h2>          <img class="drop_shadow_effect" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body>   </html>    
Output:
Example 2:
<!DOCTYPE html> <html>   <head>     <title>CSS drop-shadow() Function</title>           <style>        h1 {            color:green;        }        body {            text-align:center;        }        .drop_shadow_effect {            filter: drop-shadow(-10px -10px 20px yellow)        }    </style></head>   <body>     <h1>GeeksforGeeks</h1>           <h2>CSS drop-shadow() function</h2>          <img class="drop_shadow_effect" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body>   </html>
Output:
Supported Browsers: The browsers supported by drop-shadow() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Number of permutation with K inversions | Practice | GeeksforGeeks

Given an array, an inversion is defined as a pair a[i], a[j] such that a[i] > a[j] and i < j. Given two numbers N and K, the task is to find the count of the number of permutations of first N numbers have exactly K inversion.
Note: Answer can be large, output answer modulo 109 + 7
Example 1:
Input: N = 3, K = 1
Output: 2
Explanation: Total Permutation of first 
3 numbers, 123, 132, 213, 231, 312, 321
Permutation with 1 inversion : 132 and 213
Input: N = 3, K = 3
Output: 0
Explanation: No such permutation
 
0
Debarshi Maitra2 years ago
Debarshi Maitra
O(NK) Solution :https://ide.geeksforgeeks.o...
 https://uploads.disquscdn.c...
0
tattio2 years ago
tattio
wow nice
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Program to swap nodes in a linked list in Python

Suppose we have a list L and another value k. We have to swap kth node from start and kth node from end and return the final list at end.
So, if the input is like L = [1,5,6,7,1,6,3,9,12] k = 3, then the output will be [1,5,3,7,1,6,6,9,12], the 3rd node from start is 6 and from end is 3, so they are swapped.
To solve this, we will follow these steps −
temp := L
for i in range 0 to k-2, dotemp := next of temp
temp := next of temp
firstNode := temp
secondNode := L
while next of temp is not null, dosecondNode := next of secondNodetemp := next of temp
secondNode := next of secondNode
temp := next of temp
swap value of firstNode and value of secondNode
return L
Let us see the following implementation to get better understanding −
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next

def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head

def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
def solve(L, k):
   temp = L
   for i in range(k-1):
      temp = temp.next
   firstNode = temp
   secondNode = L
   while temp.next:
      secondNode = secondNode.next
      temp = temp.next
   firstNode.val , secondNode.val = secondNode.val , firstNode.val
   return L

L = [1,5,6,7,1,6,3,9,12]
k = 3
print_list(solve(make_list(L), k))
[1,5,6,7,1,6,3,9,12], 3
[1, 5, 3, 7, 1, 6, 6, 9, 12, ]
Linear Search

Linear searching techniques are the simplest technique. In this technique, the items are searched one by one. This procedure is also applicable for unsorted data set. Linear search is also known as sequential search. It is named as linear because its time complexity is of the order of n O(n).
Time Complexity: O(n)
Space Complexity: O(1)
Input:
A list of data:
20 4 89 75 10 23 45 69
the search key 10
Output:
Item found at location: 4
linearSearch(array, size, key)
Input − An sorted array, size of the array and the search key
Output − location of the key (if found), otherwise wrong location.
Begin
   for i := 0 to size -1 do
      if array[i] = key then
         return i
   done
   return invalid location
End
#include<iostream>
using namespace std;

int linSearch(int array[], int size, int key) {
   for(int i = 0; i<size; i++) {
      if(array[i] == key) //search key in each places of the array
         return i; //location where key is found for the first time
   }
   return -1; //when the key is not in the list
}

int main() {
   int n, searchKey, loc;
   cout << "Enter number of items: ";
   cin >> n;
   int arr[n]; //create an array of size n
   cout << "Enter items: " << endl;

   for(int i = 0; i< n; i++) {
      cin >> arr[i];
   }

   cout << "Enter search key to search in the list: ";
   cin >> searchKey;

   if((loc = linSearch(arr, n, searchKey)) >= 0)
      cout << "Item found at location: " << loc << endl;
   else
      cout << "Item is not found in the list." << endl;
}
Enter number of items: 8
Enter items:
20 4 89 75 10 23 45 69
Enter search key to search in the list: 10
Item found at location: 4
Dart - URIs - GeeksforGeeks

30 Aug, 2020
The Uri class supports functions to encode and decode strings for use in URIs (which you might know as URLs). These functions control characters that are unique for URIs, such as & and =. This class also parses and exposes the components of a URI—host, port, scheme, and so on.
The encodeFull() and decodeFull() methods are used to encode and decode characters except those with special meaning in a URI (such as /, :, &, #).
Example: 
Dart
void main(){    var uri = 'https://example.org/api?foo=some message';  var encoded = Uri.encodeFull(uri);assert(encoded ==    'https://example.org/api?foo=some%20message');  var decoded = Uri.decodeFull(encoded);print(uri == decoded);}
Output:
true

To encode and decode all of a string’s characters that have special meaning in a URI, including (but not limited to) /, &, and :, use the encodeComponent() and decodeComponent() methods.
Example:
Dart
void main(){    var uri = 'https://example.org/api?foo=some message';  var encoded = Uri.encodeComponent(uri);assert(encoded ==    'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message');  var decoded = Uri.decodeComponent(encoded);print(uri == decoded);}
Output:
true

If you have a URI object or a URI string, you can get its parts using URI fields such as path. To create a URI from a string, use the parse() static method.
Example:
Dart
void main(){    var uri =    Uri.parse('https://example.org:8080/foo/bar#frag');  assert(uri.scheme == 'https');assert(uri.host == 'example.org');assert(uri.path == '/foo/bar');assert(uri.fragment == 'frag');print(uri.origin == 'https://example.org:8080');}
Output:
true

You can  using the Uri() constructor is used to build up a URI from individual parts
Example:
Dart
void main(){    var uri = Uri(    scheme: 'https',    host: 'example.org',    path: '/foo/bar',    fragment: 'frag');print(    uri.toString() == 'https://example.org/foo/bar#frag');}
Output:
true

Dart-Classes
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Android Studio Setup for Flutter Development
What is widgets in Flutter?
Flutter - BorderRadius Widget
Format Dates in Flutter
Flutter - Positioned Widget
Flutter - Dialogs
HSQLDB - Update Query

Whenever you want to modify the values of a table, you can use the UPDATE command. This will modify any field value from any HSQLDB table.
Here is the generic syntax for UPDATE command.
UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause]

You can update one or more field altogether.
You can specify any condition using WHERE clause.
You can update values in a single table at a time.
Let us consider an example that updates the title of the tutorial from "Learn C" to "C and Data Structures" having an id "101". Following is the query for the update.
UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101;

After execution of the above query, you will receive the following output.
(1) Rows effected

Here is the JDBC program that will update a tutorial title from Learn C to C and Data Structures having an id 101. Save the following program into the UpdateQuery.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class UpdateQuery {
   
   public static void main(String[] args) {
      Connection con = null;
      Statement stmt = null;
      int result = 0;
      
      try {
         Class.forName("org.hsqldb.jdbc.JDBCDriver");
         con = DriverManager.getConnection(
            "jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
         stmt = con.createStatement();
         result = stmt.executeUpdate(
            "UPDATE tutorials_tbl SET title = 'C and Data Structures' WHERE id = 101");
      } catch (Exception e) {
         e.printStackTrace(System.out);
      }
      System.out.println(result+" Rows effected");
   }
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb

Compile and execute the above program using the following command.
\>javac UpdateQuery.java
\>java UpdateQuery

After execution of the above command, you will receive the following output −
1 Rows effected

 Print
 Add Notes
 Bookmark this page
How can I display an image using cv2 in Python?

To read an image in Python cv2, we can take the following steps−
Load an image from a file.
Display the image in the specified window.
Wait for a pressed key.
Destroy all of the HighGUI windows.
import cv2
img = cv2.imread("baseball.png", cv2.IMREAD_COLOR)
cv2.imshow("baseball", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
C++ program to find the probability of a state at a given time in a Markov chain

In this article, we will be discussing a program to find the probability of reaching from the initial state to the final state in a given time period in Markov chain.
Markov chain is a random process that consists of various states and the associated probabilities of going from one state to another. It takes unit time to move from one state to another.
Markov chain can be represented by a directed graph. To solve the problem, we can make a matrix out of the given Markov chain. In that matrix, element at position (a,b) will represent the probability of going from state ‘a’ to state ‘b’.
This would leave to a recursive approach to the probability distribution using the formula
P(t) = Matrix * P(t-1)
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define float_vec vector<float>
//to multiply two given matrix
vector<float_vec > multiply(vector<float_vec > A, vector<float_vec > B, int N) {
   vector<float_vec > C(N, float_vec(N, 0));
   for (int i = 0; i < N; ++i)
      for (int j = 0; j < N; ++j)
         for (int k = 0; k < N; ++k)
            C[i][j] += A[i][k] * B[k][j];
   return C;
}
//to calculate power of matrix
vector<float_vec > matrix_power(vector<float_vec > M, int p, int n) {
   vector<float_vec > A(n, float_vec(n, 0));
   for (int i = 0; i < n; ++i)
      A[i][i] = 1;
   while (p) {
      if (p % 2)
         A = multiply(A, M, n);
      M = multiply(M, M, n);
      p /= 2;
   }
   return A;
}
//to calculate probability of reaching from initial to final
float calc_prob(vector<float_vec > M, int N, int F, int S, int T) {
   vector<float_vec > matrix_t = matrix_power(M, T, N);
   return matrix_t[F - 1][S - 1];
}
int main() {
   vector<float_vec > G{
      { 0, 0.08, 0, 0, 0, 0 },
      { 0.33, 0, 0, 0, 0, 0.62 },
      { 0, 0.06, 0, 0, 0, 0 },
      { 0.77, 0, 0.63, 0, 0, 0 },
      { 0, 0, 0, 0.65, 0, 0.38 },
      { 0, 0.85, 0.37, 0.35, 1.0, 0 }
   };
   //number of available states
   int N = 6;
   int S = 4, F = 2, T = 100;
   cout << "Probability of reaching: " << F << " in time " << T << " after starting from: " << S << " is " << calc_prob(G, N, F, S, T);
   return 0;
}
Probability of reaching: 2 in time 100 after starting from: 4 is 0.271464
Python program to find Most Frequent Character in a String

When it is required to find the most frequent character in a string, an empty dictionary is created, and the elements in the string are iterated over. When a character is found in the dictionary, it is increment, else it is assigned to 1. The maximum of the values in the dictionary is found, and assigned to a variable.
Below is a demonstration of the same
my_string = "Python-Interpreter"

print ("The string is : ")
print(my_string)

max_frequency = {}
for i in my_string:
   if i in max_frequency:
      max_frequency[i] += 1
   else:
      max_frequency[i] = 1
my_result = max(max_frequency, key = max_frequency.get)

print ("The maximum of all characters is : ")
print(my_result)
The string is :
Python-Interpreter
The maximum of all characters in Python-Interpreter is :
e
A string is defined, and is displayed on the console.
A string is defined, and is displayed on the console.
An empty dictionary is created.
An empty dictionary is created.
The letters in the string are iterated over, and if it has been matched to a character, it is incremented.
The letters in the string are iterated over, and if it has been matched to a character, it is incremented.
Else, it is assigned to 1.
Else, it is assigned to 1.
The maximum of the values in the dictionary is determined.
The maximum of the values in the dictionary is determined.
It is assigned to a variable.
It is assigned to a variable.
This variable is displayed as output on the console.
This variable is displayed as output on the console.
Rotating axis text for each subplot in Matplotlib

To rotate axis text for each subplot, we can use text with rotation in the argument.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
Adjust the subplot layout parameters using subplots_adjust() method.
Adjust the subplot layout parameters using subplots_adjust() method.
Add a centered title to the figure using suptitle() method.
Add a centered title to the figure using suptitle() method.
Set the title of the axis.
Set the title of the axis.
Set the x and y label of the plot.
Set the x and y label of the plot.
Create the axis with some co-ordinate points.
Create the axis with some co-ordinate points.
Add text to the figure with some arguments like fontsize, fontweight and add rotation.
Add text to the figure with some arguments like fontsize, fontweight and add rotation.
Plot a single point and annotate that point with some text and arrowhead.
Plot a single point and annotate that point with some text and arrowhead.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
fig.subplots_adjust(top=0.85)
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.axis([0, 10, 0, 10])
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
   bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
ax.text(3, 2, 'unicode: Institut für Festkörperphysik')
ax.text(0.95, 0.01, 'colored text in axes coords',
   verticalalignment='bottom', horizontalalignment='right',
   transform=ax.transAxes,
   color='green', fontsize=15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
   arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
Python Program to Find All Nodes Reachable from a Node using BFS in a Graph

When it is required to find the sum of all the nodes of a tree, a class is created, and it contains methods to set the root node, add elements to the tree, search for a specific element, and add elements of the tree to find the sum and so on. An instance of the class can be created to access and use these methods.
Below is a demonstration of the same −
 Live Demo
from collections import deque

def add_edge(v, w):

   global visited_node, adj
   adj[v].append(w)
   adj[w].append(v)

def BFS_operation(component_num, src):

   global visited_node, adj
   queue = deque()

   queue.append(src)

   visited_node[src] = 1
   reachableNodes = []

   while (len(queue) > 0):

      u = queue.popleft()
      reachableNodes.append(u)
      for itr in adj[u]:
         if (visited_node[itr] == 0):

            visited_node[itr] = 1
            queue.append(itr)

   return reachableNodes

def displayReachableNodes(m):

   for i in m:
      print(i, end = " ")
   print()

def findReachableNodes(my_list, n):

   global V, adj, visited_node

   a = []

   component_num = 0

   for i in range(n):
      u = my_list[i]

      if (visited_node[u] == 0):
         component_num += 1

      a = BFS_operation(component_num, u)

   print("The reachable nodes from ", u, " are")
   displayReachableNodes(a)

V = 7
adj = [[] for i in range(V + 1)]
visited_node = [0 for i in range(V + 1)]
add_edge(1, 2)
add_edge(2, 3)
add_edge(3, 4)
add_edge(3, 1)
add_edge(5, 6)
add_edge(5, 7)

my_list = [ 2, 4, 5, 7 ]

arr_len = len(my_list)
findReachableNodes(my_list, arr_len)
The reachable nodes from 2 are
2 1 3 4
The reachable nodes from 4 are
2 1 3 4
The reachable nodes from 5 are
5 6 7
The reachable nodes from 7 are
5 6 7
The required packages are imported.
The required packages are imported.
A method named ‘add_edge’ is defined that helps add elements to the tree.
A method named ‘add_edge’ is defined that helps add elements to the tree.
The ‘BFS_operation’ method helps traverse the tree using breadth first search approach.
The ‘BFS_operation’ method helps traverse the tree using breadth first search approach.
A method named ‘displayReachableNodes’ is defined, that helps display the nodes that can be reached from a specific node.
A method named ‘displayReachableNodes’ is defined, that helps display the nodes that can be reached from a specific node.
A method named ‘findReachableNodes’ is defined, that iterates through the nodes, and performs ‘BFS_operation’ on the elements.
A method named ‘findReachableNodes’ is defined, that iterates through the nodes, and performs ‘BFS_operation’ on the elements.
The ‘add_edge’ methods adds nodes to the graph.
The ‘add_edge’ methods adds nodes to the graph.
A list is defined and displayed on the console.
A list is defined and displayed on the console.
The method is called and the output is displayed on the console.
The method is called and the output is displayed on the console.
JavaScript - Date getSeconds() Method

Javascript date getSeconds() method returns the seconds in the specified date according to local time. The value returned by getSeconds() is an integer between 0 and 59.
Its syntax is as follows −
Date.getSeconds()

Returns the seconds in the specified date according to local time.
Try the following example.
<html>
   <head>
      <title>JavaScript getSeconds Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date( "December 25, 1995 23:15:20" );
         document.write("getSeconds() : " + dt.getSeconds() ); 
      </script>      
   </body>
</html>
getSeconds() : 20 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! + ...... n/n!

Here we will see how we can get the sum of the given series. The value of n will be given by user. We can solve this problem by making a factorial function, and get factorial in each step in the loop. But factorial calculation is costlier task than normal addition. We will use the previous factorial term in the next one. Like 3! is (3 * 2 * 1), and 4! is 4 * 3!. So if we store 3! into some variable, we can use that and add the next number only to get the next factorial easily.
begin
   res := 0
   denominator := 1
   for i in range 1 to n, do
      denominator := denominator * i
      res := res + i / denominator
   done
return res
end
 Live Demo
#include<iostream>
using namespace std;
float series_result(int n) {
   float denominator = 1;
   float res = 0;
   for(int i = 1; i<= n; i++) {
      denominator *= i;
      res += float(i/denominator);
   }
   return res;
}
main() {
   int n;
   cout << "Enter number of terms: ";
   cin >> n;
   cout << "Result: " << series_result(n);
}
Enter number of terms: 5
Result: 2.70833
Enter number of terms: 3
Result: 2.5
Aptitude | GATE CS 1998 | Question 22 - GeeksforGeeks

11 Oct, 2017
Give the correct matching for the following pairs:
A. O(log n)     1. Selection sort
B. O(n)         2. Insertion sort
C. O(nlog n)    3. Binary search
D. O(n^2)       4. Merge sort

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

(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Puzzle | How much money did the man have before entering the bank?
7 Best Tips to Prepare for Aptitude Test For Campus Placements
Puzzle | Splitting a Cake with a Missing Piece in two equal portion
Geometry and Co-ordinates
Program to find the last two digits of x^y
Order and Ranking Questions & Answers
Maximum GCD of all subarrays of length at least 2
Aptitude | Arithmetic Aptitude 5 | Question 1
Aptitude | Arithmetic Aptitude | Question 1
10 Tips and Tricks to Crack Internships and Placements
CSS - elevation

The elevation property describes the position of a sound source along the vertical axis of the listener's environment.
angle − Angle values are in the range -90deg to 90deg. An angle value of 0deg corresponds to a point which is level with the listener, whereas 90deg corresponds to a point directly above, and -90deg directly below.
angle − Angle values are in the range -90deg to 90deg. An angle value of 0deg corresponds to a point which is level with the listener, whereas 90deg corresponds to a point directly above, and -90deg directly below.
above − Equivalent to the value 90deg.
above − Equivalent to the value 90deg.
level − Equivalent to the value 0deg.
level − Equivalent to the value 0deg.
below − Equivalent to the value -90deg.
below − Equivalent to the value -90deg.
higher − Causes the sound source to be shifted upwards by 10deg.
higher − Causes the sound source to be shifted upwards by 10deg.
lower − Causes the sound source to be shifted downwards by 10deg.
lower − Causes the sound source to be shifted downwards by 10deg.
All the HTML elements 
object.style.elevation = "above";

Here is one example −
<style type = "text/css">
   <!--
      h1   { elevation: above }
      tr.a { elevation: 60deg }
      tr.b { elevation: 30deg }
      tr.c { elevation: level }
   -->
</style>

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
What is a constant and how to define constants in Java?

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants.
A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.
To define a variable as a constant, we just need to add the keyword “final” in front of the variable declaration.
final float pi = 3.14f;
The above statement declares the float variable “pi” as a constant with a value of 3.14f. We cannot change the value of "pi" at any point in time in the program. Later if we try to do that by using a statement like “pi=5.25f”, Java will throw errors at compile time itself. It is not mandatory that we need to assign values of constants during initialization itself.
In the below example, we can define the primitive data type (byte, short, int, long, float, double, boolean and char) variables as constants by just adding the keyword “final” when we declare the variable.
Live Demo
public class ConstantsDemo {
   public static void main(String args[]) {
      final byte var1 = 2;
      final byte var2;
      var2 = -3;
      final short var3 = 32;
      final short var4;
      var4 = -22;
      final int var5 = 100;
      final int var6;
      var6 = -112;
      final long var7 = 20000;
      final long var8;
      var8 = -11223;
      final float var9 = 21.23f;
      final float var10;
      var10 = -121.23f;
      final double var11 = 20000.3223;
      final double var12;
      var12 = -11223.222;
      final boolean var13 = true;
      final boolean var14;
      var14 = false;
      final char var15 = 'e';
      final char var16;
      var16 = 't';
     // Displaying values of all variables
      System.out.println("value of var1 : "+var1);
      System.out.println("value of var2 : "+var2);
      System.out.println("value of var3 : "+var3);
      System.out.println("value of var4 : "+var4);
      System.out.println("value of var5 : "+var5);
      System.out.println("value of var6 : "+var6);
      System.out.println("value of var7 : "+var7);
      System.out.println("value of var8 : "+var8);
      System.out.println("value of var9 : "+var9);
      System.out.println("value of var10 : "+var10);
      System.out.println("value of var11 : "+var11);
      System.out.println("value of var12 : "+var12);
      System.out.println("value of var13 : "+var13);
      System.out.println("value of var14 : "+var14);
      System.out.println("value of var15 : "+var15);
      System.out.println("value of var16 : "+var16);
   }
}
value of var1 : 2
value of var2 : -3
value of var3 : 32
value of var4 : -22
value of var5 : 100
value of var6 : -112
value of var7 : 20000
value of var8 : -11223
value of var9 : 21.23
value of var10 : -121.23
value of var11 : 20000.3223
value of var12 : -11223.222
value of var13 : true
value of var14 : false
value of var15 : e
value of var16 : t
Show decimal places and scientific notation on the axis of a Matplotlib plot

To show decimal places and scientific notation on the axis of a matplotlib, we can use scalar formatter by overriding _set_format() method.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot x and y using plot() method.
Plot x and y using plot() method.
Using gca() method, get the current axis.
Using gca() method, get the current axis.
Instantiate the format tick values as a number class, i.e., ScalarFormatter.
Instantiate the format tick values as a number class, i.e., ScalarFormatter.
Set size thresholds for scientific notation, using set_powerlimits((0, 0)) method.
Set size thresholds for scientific notation, using set_powerlimits((0, 0)) method.
Using set_major_formatter() method, set the formatter of the major ticker.
Using set_major_formatter() method, set the formatter of the major ticker.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib.ticker import ScalarFormatter
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

class ScalarFormatterClass(ScalarFormatter):
   def _set_format(self):
      self.format = "%1.2f"

x = np.linspace(1, 10)
y = np.linspace(2,10)
y = x * y
plt.plot(x, y)
ax = plt.gca()
yScalarFormatter = ScalarFormatterClass(useMathText=True)
yScalarFormatter.set_powerlimits((0,0))
ax.yaxis.set_major_formatter(yScalarFormatter)
plt.show()
How to create a date picker using JavaFX?

Typically, a date picker displays a calendar, from which you can browse through different months and pick a date. The picked date is formatted and inputs into the system.
In JavaFX the javafx.scene.control.DatePicker class represents the date picker. This contains a text (date) filed and a date chooser. You can either enter the date manually or choose a date using the date chooser.
To create a date picker in your application, you need to instantiate this class. You can get the chosen date from the date picker by invoking the getValue() method.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class DatePickerExample extends Application {
   public void start(Stage stage) {
      //Creating label
      Text dobLabel = new Text("Date Of Birth:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      dobLabel.setFont(font);
      //Creating a date picker
      DatePicker datePicker = new DatePicker();
      //Creating HBox
      HBox box = new HBox(5);
      box.setPadding(new Insets(15, 50, 50, 50));
      box.getChildren().addAll(dobLabel, datePicker);
      //Setting the stage
      Scene scene = new Scene(box, 595, 260, Color.BEIGE);
      stage.setTitle("Date Picker Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}