code-rag-bench/online-tutorials huggingface dataset:
How to show image in alert box using JavaScript?

To show an image in alert box, try to run the following code. Here, an alert image is added to the custom alert box −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #FFFFFF;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 80px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message">This is a warning message.</div>
         <button class="yes">OK</button>
         <img src = "https://encrypted-tbn0.gstatic.com/images?q=
                     tbn:ANd9GcSNjyHBjM74KLxvROpx34zsT4zPzMWHMHz4zzJwAtemXGglsjtA"
                      width="120" height="70"/>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>
How to create hardlink of a file using Python?

The method os.link(src, dst) creates a hard link pointing to src named dst. This method is very useful to create a copy of existing file.
For example, if you have a file called photo.jpg and want to create a  hard link to it called my_photo.jpg, then you could simply use:
>>> import os
>>> os.link('photo.jpg', 'my_photo.jpg')
 Now if you list the files in that directory, you'll get the my_photo
Difference between regular functions and arrow functions - GeeksforGeeks

24 May, 2019
This article discusses the major differences between the regular functions and the arrow functions.
Arrow functions – a new feature introduced in ES6 – enable writing concise functions in JavaScript. While both regular and arrow functions work in a similar manner, yet there are certain interesting differences between them, as discussed below.
Syntax
Syntax of regular functions:-
let x = function function_name(parameters){   // body of the function};
Example of regular functions:-
let square = function(x){  return (x*x);};console.log(square(9));
Output:
The syntax of arrow functions:-
let x = (parameters) => {    // body of the function};
Example of arrow functions:-
var square = (x) => {    return (x*x);};console.log(square(9));
Output:
Use of this keyword
Unlike regular functions, arrow functions do not have their own this.For example:-
let user = {    name: "GFG",    gfg1:() => {        console.log("hello " + this.name); // no 'this' binding here    },    gfg2(){               console.log("Welcome to " + this.name); // 'this' binding works here    }   };user.gfg1();user.gfg2();
Output:
Availability of arguments objects
Arguments objects are not available in arrow functions, but are available in regular functions.
Example using regular ():-
let user = {          show(){        console.log(arguments);    }};user.show(1, 2, 3);
Output:
Example using arrow ():-
let user = {             show_ar : () => {        console.log(...arguments);    }};user.show_ar(1, 2, 3);
Output:
Using new keyword
Regular functions created using function declarations or expressions are ‘constructible’ and ‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible. Thus, we will get a run-time error on trying to construct a non-constructible arrow functions using the new keyword.
Example using regular function:-
let x = function(){    console.log(arguments);};new x =(1,2,3);
Output:Example using arrow function:-
let x = ()=> {    console.log(arguments);};new x(1,2,3);
Output:For more information on arrow functions, refer this link.
shubham_singh
javascript-functions
Web technologies
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between DFA and NFA
Web 1.0, Web 2.0 and Web 3.0 with their difference
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Form validation using HTML and JavaScript
File uploading in React.js
Kth Smallest Number in Multiplication Table in C++

Suppose we know about one Multiplication Table. But could we find out the k-th smallest number quickly from the multiplication table? So if we have to height m and the length n of a m * n Multiplication Table, and one positive integer k, we have need to find the k-th smallest number in this table.
So if m = 3 and n = 3 and k is 6, then the output will be 4., this is because the multiplication table is like −
6th smallest element is 4 as [1,2,2,3,3,4,6,6,9]
To solve this, we will follow these steps −
Define a function ok(), this will take m, n, x,
ret := 0
for initialize i := 1, when i <= n, update (increase i by 1), do −temp := minimum of x / i and mret := ret + temp
temp := minimum of x / i and m
ret := ret + temp
return ret
From the main method, do the following −
ret := -1, low := 1, high := m * n
while low <= high, do −mid := low + (high - low) / 2cnt := ok(m, n, mid)if cnt >= k, then −high := mid - 1ret := midOtherwiselow := mid + 1
mid := low + (high - low) / 2
cnt := ok(m, n, mid)
if cnt >= k, then −high := mid - 1ret := mid
high := mid - 1
ret := mid
Otherwiselow := mid + 1
low := mid + 1
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int ok(int m, int n, int x){
      int ret = 0;
      for(int i = 1; i <= n; i++){
         int temp = min(x / i, m);
         ret += temp;
      }
      return ret;
   }
   int findKthNumber(int m, int n, int k) {
      int ret = -1;
      int low = 1;
      int high = m * n ;
      while(low <= high){
         int mid = low + (high - low)/ 2;
         int cnt = ok(m, n, mid);
         if(cnt >= k){
            high = mid - 1;
            ret = mid;
         }else low = mid + 1;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.findKthNumber(3,3,6));
}
“2*”
4
How to change the color and add grid lines to a Python Matplotlib surface plot?

To change the color and add grid lines to a Python surface plot, 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 x, y and h data points using numpy.
Create x, y and h data points using numpy.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Get 3D axes object, with figure (from Step 3).
Get 3D axes object, with figure (from Step 3).
Create a surface plot, with orange color, edgecolors and linewidth.
Create a surface plot, with orange color, edgecolors and linewidth.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

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

x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)

x, y = np.meshgrid(x, y)
h = np.sin(x)*np.cos(y)

fig = plt.figure()

ax = Axes3D(fig)
ax.plot_surface(x, y, h, rstride=10, cstride=10, color='orangered', edgecolors='yellow', lw=0.6)

plt.show()
Apache Presto - current_date()

presto:default> select current_date as date;
   Date 
------------ 
 2016-07-06 

The query returns the current date.

    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
Containers in C++ STL

In this tutorial, we will be discussing a program to understand containers in C++ STL.
Containers are the objects used to store multiple elements of the same type or different. Depending on that they can be further classified as −
Sequence containers (array, vector, list)
Sequence containers (array, vector, list)
Associative containers (set, map, multimap)
Associative containers (set, map, multimap)
Unordered Associative containers (unordered_set, unordered_map)
Unordered Associative containers (unordered_set, unordered_map)
Container Adapters (stack, queue)
Container Adapters (stack, queue)
 Live Demo
#include <iostream>
using namespace std;
int main(){
   int array[10] = {1,2,3,4};
   for(int i=0; i<10; i++){
      cout << array[i] << " ";
   }
   return 0;
}
1 2 3 4 0 0 0 0 0 0
Maximum Weight Difference in C++ Program

In this problem, we are given an array arr[] and a number M. Our task is to
create a program to calculate the Maximum Weight Difference in C++.
We will find M elements from the array such that the absolute difference
between the sum and the sum of the rest elements is maximum.
Let’s take an example to understand the problem,
arr[] = {3, 1, 6, 9, 4} M = 3
15
We will consider 4,6,9. The sum is 19. The absolute difference with the sum
of rest numbers is
|19 − 4| = 15
A simple solution to the problem is by finding all subsequences of the array,
finding the sum elements of the subarray, and the rest. And return the
maximum difference.
A more efficient solution is found by using the fact that maximum weight
difference i.e. difference of the sum of elements and the rest is maximum if
we consider m maximum elements or m minimum elements for
subsequence.
So, we will check for the maximum sum difference for a subsequence of m
largest elements and rest array or subsequence of m smallest elements and
rest array.
And return the maximum of both.
Initialize −
maxSum , maxSumDiff, minSumDiff
Step 1 −
sort the array in descending order.
Step 2 −
Loop for i −> 0 to n
Step 2.1 −
if (i < m) −> maxSumDiff += arr[i]
Step 2.2 −
else −> maxSumDiff −= arr[i]
Step 2 −
Loop for i −> n to 0
Step 2.1 −
if (i > m) −> minSumDiff += arr[i]
Step 2.2 −
else −> minSumDiff −= arr[i]
Step 3 −
if maxSumDiff > minSumDiff −> maxSum = maxSumDiff.
Step 4 −
if maxSumDiff < minSumDiff −> maxSum = minSumDiff.
Step 5 −
return maxSum.
Program to illustrate the working of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int maxWeightDifference(int arr[], int N, int M){
   int maxabsDiff = −1000;
   sort(arr, arr + N);
   int sumMin = 0, sumMax = 0, arrSum = 0;
   for(int i = 0; i < N; i++){
      arrSum += arr[i];
      if(i < M)
         sumMin += arr[i];
      if(i >= (N−M))
         sumMax += arr[i];
   }
   maxabsDiff = max(abs(sumMax − (arrSum − sumMax)), abs(sumMin −
   (arrSum − sumMin)));
   return maxabsDiff;
}
int main(){
   int arr[] = {3, 1, 6, 9, 4} ;
   int M = 3;
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum weight difference is "<<maxWeightDifference(arr,N, M);
   return 0;
}
The maximum weight difference is 15
Insertion Sort Program in C

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it is to be inserted there. Hence the name insertion sort.
#include <stdio.h>
#include <stdbool.h>

#define MAX 7

int intArray[MAX] = {4,6,3,2,1,9,7};

void printline(int count) {
   int i;
	
   for(i = 0;i < count-1;i++) {
      printf("=");
   }
	
   printf("=\n");
}

void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf("%d ",intArray[i]);
   }
	
   printf("]\n");
}

void insertionSort() {

   int valueToInsert;
   int holePosition;
   int i;
  
   // loop through all numbers 
   for(i = 1; i < MAX; i++) { 
	
      // select a value to be inserted. 
      valueToInsert = intArray[i];
		
      // select the hole position where number is to be inserted 
      holePosition = i;
		
      // check if previous no. is larger than value to be inserted 
      while (holePosition > 0 && intArray[holePosition-1] > valueToInsert) {
         intArray[holePosition] = intArray[holePosition-1];
         holePosition--;
         printf(" item moved : %d\n" , intArray[holePosition]);
      }

      if(holePosition != i) {
         printf(" item inserted : %d, at position : %d\n" , valueToInsert,holePosition);
         // insert the number at hole position 
         intArray[holePosition] = valueToInsert;
      }

      printf("Iteration %d#:",i);
      display();
		
   }  
}

void main() {
   printf("Input Array: ");
   display();
   printline(50);
   insertionSort();
   printf("Output Array: ");
   display();
   printline(50);
}
If we compile and run the above program, it will produce the following result −
Input Array: [4 6 3 2 1 9 7 ]
==================================================
Iteration 1#:[4 6 3 2 1 9 7 ]
 item moved : 6
 item moved : 4
 item inserted : 3, at position : 0
Iteration 2#:[3 4 6 2 1 9 7 ]
 item moved : 6
 item moved : 4
 item moved : 3
 item inserted : 2, at position : 0
Iteration 3#:[2 3 4 6 1 9 7 ]
 item moved : 6
 item moved : 4
 item moved : 3
 item moved : 2
 item inserted : 1, at position : 0
Iteration 4#:[1 2 3 4 6 9 7 ]
Iteration 5#:[1 2 3 4 6 9 7 ]
 item moved : 9
 item inserted : 7, at position : 5
Iteration 6#:[1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C Program to Compute Quotient and Remainder?

Given two numbers dividend and divisor. The task is to write a program to find the quotient and remainder of these two numbers when the dividend is divided by the divisor.
In division, we will see the relationship between the dividend, divisor, quotient, and remainder. The number which we divide is called the dividend. The number by which we divide is called the divisor. The result obtained is called the quotient. The number left over is called the remainder.
55 ÷ 9 = 6 and 1
Dividend Divisor Quotient Remainder
Input:
Dividend = 6
Divisor = 2
Output:
Quotient = 3,
Remainder = 0
Then, the variables Dividend and Divisor are divided using the arithmetic operator / to get the quotient as result stored in the variable quotient; and using the arithmetic operator % to get the remainder as result stored in the variable remainder.
#include <stdio.h>
int main() {
   int dividend, divisor, quotient, remainder;
   dividend= 2;
   divisor= 6;
   // Computes quotient
   quotient = dividend / divisor;
   // Computes remainder
   remainder = dividend % divisor;
   printf("Quotient = %d\n", quotient);
   printf("Remainder = %d", remainder);
   return 0;
}
wxPython - Multiple Document Interface

A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden.
One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (Single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc.
MDI framework in wxPython provides a wx.MDIParentFrame class. Its object acts as a container for multiple child windows, each an object of wx.MDIChildFrame class.
Child windows reside in the MDIClientWindow area of the parent frame. As soon as a child frame is added, the menu bar of the parent frame shows a Window menu containing buttons to arrange the children in a cascaded or tiled manner.
The following example illustrates the uses of MDIParentFrame as top level window. A Menu button called NewWindow adds a child window in the client area. Multiple windows can be added and then arranged in a cascaded or tiled order.
The complete code is as follows −
import wx 
 
class MDIFrame(wx.MDIParentFrame): 
   def __init__(self): 
      wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size = (600,400)) 
      menu = wx.Menu() 
      menu.Append(5000, "&New Window") 
      menu.Append(5001, "&Exit") 
      menubar = wx.MenuBar() 
      menubar.Append(menu, "&File") 
		
      self.SetMenuBar(menubar) 
      self.Bind(wx.EVT_MENU, self.OnNewWindow, id = 5000) 
      self.Bind(wx.EVT_MENU, self.OnExit, id = 5001) 
		
   def OnExit(self, evt): 
      self.Close(True)  
		
   def OnNewWindow(self, evt): 
      win = wx.MDIChildFrame(self, -1, "Child Window")
      win.Show(True) 
		
app = wx.App() 
frame = MDIFrame() 
frame.Show() 
app.MainLoop()
The above code produces the following output −
 Print
 Add Notes
 Bookmark this page
Can we define an abstract class with no abstract methods in Java?

Yes, we can declare an abstract class with no abstract methods in Java.
An abstract class means that hiding the implementation and showing the function definition to the user.
An abstract class having both abstract methods and non-abstract methods.
For an abstract class, we are not able to create an object directly. But Indirectly we can create an object using the subclass object.
A Java abstract class can have instance methods that implement a default behavior.
An abstract class can extend only one class or one abstract class at a time.
Declaring a class as abstract with no abstract methods means that we don't allow it to be instantiated on its own.
An abstract class used in Java signifies that we can't create an object of the class directly.
abstract class AbstractDemo { // Abstract class
   private int i = 0;
   public void display() { // non-abstract method
      System.out.print("Welcome to Tutorials Point");
   }
}
public class InheritedClassDemo extends AbstractDemo {
   public static void main(String args[]) {
      AbstractDemo demo = new InheritedClassDemo();
      demo.display();
   }
}
In the above example, we have not defined an abstract method in AbstractDemo class. The compiler doesn't throw any compile-time error.
Welcome to Tutorials Point
How to BIND a DBRM directly into a PLAN?

A DBRM is a DB2 object which is generated from the pre-compilation of the source code. It contains all the SQL statements/queries of the source code. DBRM could not be executed directly due to its format, hence it is binded into a plan first. There can be multiple DBRM which can be binded in a single plan.
Whenever there is a source code change, corresponding DBRM has to be generated again with changed SQL statements/queries. Then the entire plan (which contains the old DBRM) has to be bound again.
Using the below JCL step we can BIND a DBRM directly into a PLAN.
//BIND EXEC PGM=IKJEFT01
//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(TB3)
BIND PLAN(PLANA) -
MEMBER(DBRM1) -
LIB(‘DIS.TEST.DBRM’)
/*
The BIND PLAN parameter has the name of the plan which needs to be binded. The MEMBER parameter is the name of the DBRM PDS member residing in the PDS DIS.TEST.DBRM.
Guidelines for asymptotic analysis - GeeksforGeeks

09 Jul, 2021
In this article, the focus is on learning some rules that can help to determine the running time of an algorithm.
Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation. In Asymptotic Analysis, the performance of an algorithm in terms of input size (we don’t measure the actual running time) is evaluated. How the time (or space) taken by an algorithm increases with the input size is also calculated.
(g(n)) = {f(n)   such that g(n) is a curve which approximates f(n) at higher values of input size, n}
This curve is called asymptotic curve and the algorithm analysis for such a curve is called Asymptotic analysis.
Loops: The running time of a loop is, at most, the running time of the statements inside the loop, including tests) multiplied number of iterations.
Below is the python program that demonstrates the above concept:
Python3
# Python program to implement# the above concept# execute n times for in# range(0.00); for i in range(0, n):print ('Current Number:', i, sep = "")
#constant time 
Total time a constant cx n = cn = O(n).
Nested loops: Analyze from the inside out. The total running time is the product of the sizes of all the loops.
Below is a python program that demonstrates the above concept:
Python3
# Python program to implement# the above concept# outer loop executed n timesfor i in range(0, n):     # inner loop executes n times    for j in range(0, n):      print("i value % d  and j value % d" % (i, j))
# constant time 
Total time = C x n x n = cn^2 =0(n2).
Consecutive statements: Add the time complexity of each statement.
Below is a python program that demonstrates the above concept:
Python3
# Python program that implements# the above conceptn = 100 # executes n timesfor i in range (0, n):    print (Current Number: i, sep = "")         # outer loop executed n times    for i in range (0, n):             # inner loop executes n times      for j in range(0, n):        print(" i value % d and j value % d"%(i, j)) X
  
Total time = co + c1n + c2n^2 = 0(n^2).
 
If-then-else statements: Worst-case running time: the test, plus either the then part of the else part whichever is the largest. 
 
Below is a python program that demonstrates the above concept:
 
Python3
# Python program that implements# the above conceptif n == I:  print ("Incorrect Value")  print (n) else:  for i in range(0, n):         # constant time    print (CurrNumber:, i, sep = "")
Total time = co + c1*n = 0(n).
kalrap615
Algorithms
Analysis
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Time Complexity and Space Complexity
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Practice Questions on Time Complexity Analysis
CURRENT_TIMESTAMP() Function in SQL Server - GeeksforGeeks

18 Jan, 2021
CURRENT_TIMESTAMP() function :This function in SQL Server is used to return the current date as well as time. And the format of the output is as follows.
'YYYY-MM-DD hh:mm:ss.mmm'
Features :
This function is used to find the current date and time.
This function comes under Date Functions.
This function doesn’t accept any parameter.
This function can also be used as a default value in some codes.
Syntax :
CURRENT_TIMESTAMP
Parameter :This method doesn’t accept any parameter.
Returns :It returns the current date as well as time and the format of the output returned is ‘YYYY-MM-DD hh:mm:ss.mmm’.
Example-1 :Using CURRENT_TIMESTAMP function and getting the current date as well as time.
SELECT CURRENT_TIMESTAMP 
AS current_date_and_time;
Output :
current_date_and_time
--------------------------
2020-12-31 12:32:24.100
So, here the output may vary every time you run this code as this function returns the current date and time.
Example-2 :Using CURRENT_TIMESTAMP as a default value in the below example and getting the output.
CREATE TABLE current_time_stamp
(
    id_num INT IDENTITY, 
    message VARCHAR(150) NOT NULL, 
    generated_at DATETIME NOT NULL
    DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY(id_num)
);

Inserting data into table –
INSERT INTO current_time_stamp(message)
VALUES('Its the first message.');

INSERT INTO current_time_stamp(message)
VALUES('current_time_stamp');

Reading data from table –
SELECT 
    id_num, 
    message, 
    generated_at
FROM 
    current_time_stamp;
Output :
Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_TIMESTAMP function as a default value.
Note –For running the above code use SQL server compiler, you can also use an online compiler.
Application :This function is used to find the current date as well as time.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

30 Sep, 2021
An instruction pipeline has five stages, namely, instruction fetch (IF), instruction decode and register fetch (ID/RF), instruction execution (EX), memory access (MEM), and register writeback (WB) with stage latencies 1 ns, 2.2 ns, 2 ns, 1 ns, and 0.75 ns, respectively (ns stands for nanoseconds). To gain in terms of frequency, the designers have decided to split the ID/RF stage into three stages (ID, RF1, RF2) each of latency 2.2/3 ns. Also, the EX stage is split into two stages (EX1, EX2) each of latency 1 ns. The new design has a total of eight pipeline stages. A program has 20% branch instructions which execute in the EX stage and produce the next instruction pointer at the end of the EX stage in the old design and at the end of the EX2 stage in the new design. The IF stage stalls after fetching a branch instruction until the next instruction pointer is computed. All instructions other than the branch instruction have an average CPI of one in both the designs. The execution times of this program on the old and the new design are P and Q nanoseconds, respectively. The value of P/Q is __________.
(A) 1.5(B) 1.4(C) 1.8(D) 2.5Answer: (A)Explanation:
Each one takes average 1CPI.

In 1st case 80% take 1 clock and 20% take 3 clocks so total time:

p = (.8*1 + .2*3)*2.2=3.08.
q = (.8*1 + 6*.2)*1=2
p/q = 1.54 
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:26 / 40:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h-14CfDEprU" 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-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Solidity - View and Pure Functions - GeeksforGeeks

11 May, 2022
The view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not ‘view or pure’, using low-level calls, etc are present in view functions then the compiler throw a warning in such cases. By default, a get method is view function.
Example: In the below example, the contract Test defines a view function to calculate the product and sum of two unsigned integers.
Solidity
// Solidity program to // demonstrate view// functionspragma solidity ^0.5.0;  // Defining a contractcontract Test {          // Declaring state     // variables    uint num1 = 2;     uint num2 = 4;     // Defining view function to     // calculate product and sum    // of 2 numbers   function getResult(   ) public view returns(     uint product, uint sum){       uint num1 = 10;       uint num2 = 16;      product = num1 * num2;      sum = num1 + num2;    }}
Output :  
The pure functions do not read or modify the state variables, which returns the values only using the parameters passed to the function or local variables present in it. If the statements which read the state variables, access the address or balance, accessing any global variable block or msg, calling a function which is not pure, etc are present in pure functions then the compiler throws a warning in such cases.
Example: In the below example, the contract Test defines a pure function to calculate the product and sum of two numbers.
Solidity
// Solidity program to  // demonstrate pure functionspragma solidity ^0.5.0;  // Defining a contractcontract Test {      // Defining pure function to     // calculate product and sum   // of 2 numbers   function getResult(   ) public pure returns(     uint product, uint sum){      uint num1 = 2;       uint num2 = 4;      product = num1 * num2;      sum = num1 + num2;    }}
Output :  
Solidity-Functions
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Storage vs Memory in Solidity
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
How to Become a Blockchain Developer?
How to connect ReactJS with MetaMask ?
Proof of Work (PoW) Consensus
Storage vs Memory in Solidity
Mathematical Operations in Solidity
Solidity - Inheritance
How to Install Solidity in Windows?
Introduction to Solidity
How to change pagefile settings from custom to system managed using PowerShell?

To change the pagefile settings to system managed, we need to set InitialSize and MaximumSize parameters to 0. In the below example, we have E: has custom pagefile, not system managed and we need to convert it to the system managed.
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
$pagefileset.InitialSize = 0
$pagefileset.MaximumSize = 0
$pagefileset.Put() | Out-Null
Now when you check the pagefile setting on E: it should be System managed.
To change the settings on the remote computer use -ComputerName parameter in the Get-WmiObject method.
How to detect the value change of a JSlider in Java?

A JSlider is a subclass of JComponent class and it is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. A JSlider has a knob which can slide on a range of values and can be used to select a particular value. and it can generate a ChangeListener interface.
We can detect the value changed when the slider is moved horizontally using the Graphics2D class and override paint() method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ValueChangeJSliderTest extends JFrame {
   private JSlider slider;
   public ValueChangeJSliderTest() {
      setTitle("ValueChangeJSlider Test");
      slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
      slider.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            repaint();
         }
      });
      setLayout(new BorderLayout());
      slider.setBackground(Color.white);
      slider.setMajorTickSpacing(1);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      add(slider, BorderLayout.NORTH);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public void paint(Graphics g) {
      super.paint(g);
      Graphics2D g2d = (Graphics2D) g;
      g2d.setFont(new Font("Serif", Font.ITALIC, 25));
      g2d.drawString(""+slider.getValue(), 200, 130);
   }
   public static void main(String[] args) {
      new ValueChangeJSliderTest();
   }
}
T-SQL - INSERT Statement

The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database.
Following are the two basic syntaxes of INSERT INTO statement.
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]   
VALUES (value1, value2, value3,...valueN); 

Where column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Following statements will create six records in CUSTOMERS table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
  
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );  

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );  

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); 
 
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );  

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table using second syntax as follows −
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

All the above statements will produce the following records in CUSTOMERS table −
ID  NAME       AGE         ADDRESS              SALARY 
1   Ramesh     32          Ahmedabad            2000.00 
2   Khilan     25          Delhi                1500.00 
3   kaushik    23          Kota                 2000.00 
4   Chaitali   25          Mumbai               6500.00 
5   Hardik     27          Bhopal               8500.00 
6   Komal      22          MP                   4500.00 
7   Muffy      24          Indore               10000.00 

You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −
INSERT INTO first_table_name  
   SELECT column1, column2, ...columnN  
      FROM second_table_name 
      [WHERE condition];


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
Ruby | Hash flatten() function - GeeksforGeeks

07 Jan, 2020
Hash#flatten() is a Hash class method which returns the one-dimensional flattening hash array.
Syntax: Hash.flatten()
Parameter: Hash values
Return: one-dimensional flattening hash array
Example #1 :
# Ruby code for Hash.flatten() method  # declaring Hash valuea = {a:100, b:200}  # declaring Hash valueb = {a:100, c:[300, 45], b:200}  # declaring Hash valuec = {a:100}    # flatten Valueputs "Hash a flatten form : #{a.flatten()}\n\n"  puts "Hash b flatten form : #{b.flatten()}\n\n"  puts "Hash c flatten form : #{c.flatten()}\n\n"
Output :
Hash a flatten form : [:a, 100, :b, 200]

Hash b flatten form : [:a, 100, :c, [300, 45], :b, 200]

Hash c flatten form : [:a, 100]


Example #2 :
# Ruby code for Hash.flatten() method  # declaring Hash valuea = { "a" => 100, "b" => 200 }  # declaring Hash valueb = {"a" => 100}  # declaring Hash valuec = {"a" => 100, "c" => [300, 200, 500], "b" => 200}    # flatten Valueputs "Hash a flatten form : #{a.flatten()}\n\n"  puts "Hash b flatten form : #{b.flatten()}\n\n"  puts "Hash c flatten form : #{c.flatten()}\n\n"
Output :
Hash a flatten form : ["a", 100, "b", 200]

Hash b flatten form : ["a", 100]

Hash c flatten form : ["a", 100, "c", [300, 200, 500], "b", 200]


Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
HTML | DOM onmouseover event - GeeksforGeeks

04 Aug, 2021
The DOM onmouseover event in HTML occurs when the mouse pointer is moved onto an element or its children.Supported Tags: It supports All HTML elements, EXCEPT: 
<base>
<bdo>
<br>
<head>
<html>
<iframe>
 <meta>
<param>
<script>
<style>
<title>
Syntax:  
In HTML:  
<element onmouseover="myScript">
In JavaScript:  
object.onmouseover = function(){myScript};
In JavaScript, using the addEventListener() method:  
object.addEventListener("mouseover", myScript);
Example:  
html
<!DOCTYPE html><html> <head>    <title>      DOM onmouseover event  </title></head> <body>    <center>         <h1 id="hID">          GeeksforGeeks      </h1>        <h2>          HTML DOM onmouseover event      </h2>         <script>            document.getElementById(              "hID").addEventListener(              "mouseover", over);                       document.getElementById(              "hID").addEventListener(              "mouseout", out);             function over() {                document.getElementById(                  "hID").style.color = "green";            }             function out() {                document.getElementById(                  "hID").style.color = "black";            }        </script>    </center></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML DOM onmouseover event are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
How to create an HTML button that acts like a link?
How to position a div at the bottom of its container using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
Interactive Network Visualization | by Himanshu Sharma | Towards Data Science

Pyviz is a python module that is used to create networks that can be customized on per node or per edge basis. It contains different customizations like the size of the node, edges, user-defined labels. The graphs created using pyviz are highly interactive which allows dragging, hovering, and selecting different nodes and edges.
Each graph created using Pyviz can have a custom layout that can be tweaked for user-defined requirements.
Pyviz is a wrapper built around the amazing VisJS library. In this article, we will be exploring Pyviz for creating network graphs using python.
Let’s get started...
Like any other python library, we will install the Pyviz library using pip. The command for which is given below.
pip install pyvis
In order to create a graph network, we will be using the network class instance of Pyviz which can be imported using the code given below.
from pyvis.network import Network
Now that we have imported the network class instance we will start building our graph network by adding nodes. We can add nodes one by one or we can also create a list of nodes.
net = Network()#Adding node one by onenet.add_node(1, label="Node 1")net.add_node(2) #Adding node as a listnodes = ["a", "b", "c", "d"]net.add_nodes(nodes) net.add_nodes("hello")
Next, we will create edges that will connect these nodes with specified weights given to each edge. The code for which is given below.
net.add_edge(0, 1, weight=.87)
The final step is to visualize the graph we have created as a static HTML file as we know this file will be highly interactive.
net.toggle_physics(True)net.show('mygraph.html')
We can dynamically alter the settings of our network using the configuration UI. It will add buttons to the UI. So that we can tweak our graphs to find out the most optimal physics parameters and the layouts.
net.show_buttons(filter_=['physics'])
So this is how you can create your own graph network visualization. Go ahead try this and let me know if you face any issues in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
Semaphore in Java

A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread.
Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly.
If the count of semaphore is greater than 0, the thread gets access to shared resource. The count of the semaphore will be decrement simultaneously. Otherwise, if the count of semaphore is not0, the thread would be blocked from accessing the shared resource until the semaphore releases the other thread’s access. When the thread doesn’t need the shared resource, it gives away its permission. At this point in time, the semaphore’s count would be increment. If a different thread also requires access to shared resource, it can compete to access the shared resource.
Following is an example −
public class Demo {
   private boolean my_signal = false;
   public synchronized void accept() {
      this.my_signal = true;
      this.notify();
   }
   public synchronized void give_it() throws InterruptedException {
      while(!this.my_signal) wait();
      this.my_signal = false;
   }
}
The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed.
PostgreSQL - Exit - GeeksforGeeks

08 Feb, 2021
In PostgreSQL, The EXIT statement is used to terminate all types of loops like unconditional loops, a while loop, or a for loop or terminate a block of code specified by the begin..end keywords.
We can use the exit to terminate looping statements using the following syntax:
exit [label] [when condition]
If we analyze the above syntax:
Label: The label is used to signify the loop which we want to exit. It is often used in the case of nested looping. If a label is not present, the current loop is terminated. 
Condition: The condition is a simple boolean expression that determines when we want to terminate the loop. When the value of the boolean expression becomes true, the loop is terminated.
Both of the above are optional. We can use exit with a condition like:
exit when cnt < 5;
Without using the condition in exit, we can rewrite the same code using the IF statement as:
if cnt < 5 then
  exit;
end if;
Suppose we a have loop that is used to print all numbers from 1 to 10. We can use the EXIT statement in the following manner to limit printing the numbers up to 7 only.
do $$
declare
 n integer:= 8;
 cnt integer := 1 ;  
begin
loop  
exit when cnt = n ;
raise notice '%', cnt;  
cnt := cnt + 1 ;  
end loop;  
end; $$;
Output:
In the above example, we terminate our loop as soon as the value of our cnt variable reaches n(here 8) and thus, only values up to 7 are printed.
We can then the exit statement to terminate a block of code specified by the begin..end keywords. In this case, the exit directly passes the flow of the program to after the end keyword, thus ending the current block.
<<block_label>>
BEGIN
   Statements
   EXIT [block_label] [WHEN condition];
   Statements
END block_label;
Using this syntax, we can terminate the block of code prematurely, thus preventing the statements after the exit to be run.
The following example shows how we can use EXIT to exit a block.
do
$$
begin
 raise notice '%', 'Before block';
 <<normalblock>>  
  begin
 raise notice '%', 'Before exit ; inside block';
   exit normalblock;
    raise notice '%', 'After exit ; inside block';
  end;
  raise notice '%', 'End of block';
end;
$$;
Output:
In the above example, the statement after exit was not printed as the block was terminated using EXIT before the statement. Thus inside the block, only statements before EXIT were executed and after that, the flow simply passes after the block ended.
Picked
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
Most efficient method to groupby on an array of objects in Javascript

The most efficient method to group by a key on an array of objects in js is to use the reduce function.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
const people = [
   { name: 'Lee', age: 21 },
   { name: 'Ajay', age: 20 },
   { name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
   return objectArray.reduce((acc, obj) => {
      const key = obj[property];
      if (!acc[key]) {
         acc[key] = [];
      }
      // Add object to list for given key's value
      acc[key].push(obj);
      return acc;
   }, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);
This will give the output −
{ 20: [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ],
21: [ { name: 'Lee', age: 21 } ] }