code-rag-bench/online-tutorials huggingface dataset:
Golang Program that uses String Switch

04 May, 2020
With the help of switch case we can implement the functionality of as many if statements. In Golang, switch cases can work with strings, list of variables including integer values as well as floating values.
Syntax:
switch optstatement; optexpression{case expression1: Statement..case expression2: Statement.....default: Statement..}
Example 1: In this example we can see that by using switch cases and assuming variable as a string type we can make use of switch cases.
// Golang program that uses string switchpackage main  // Here "fmt" is formatted IO which// is same as C’s printf and scanf.import "fmt"  // Main functionfunc main() {    day := "Tue"      // Use switch on the day variable.    switch {    case day == "Mon":        fmt.Println("Monday")    case day == "Tue":        fmt.Println("Tuesday")    case day == "Wed":        fmt.Println("Wednesday")    }}
Output :
Tuesday

Example 2:
// Golang program that uses string switchpackage main  // Here "fmt" is formatted IO which // is same as C’s printf and scanf.import "fmt"  // Main functionfunc main() {    gfg := "Geek"      // Use switch on the day variable.    switch {    case gfg == "Geek":        fmt.Println("Geek")    case gfg == "For":        fmt.Println("For")    case gfg == "Geeks":        fmt.Println("Geeks")    }}
Output:
Geek

Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How do we use easy_install to install Python modules?

easy_install was released in 2004, as part of setuptools. It was notable at the time for installing packages from PyPI using requirement specifiers, and automatically installing dependencies.
pip came later in 2008, as alternative to easy_install, although still largely built on top of setuptools components. You should be using pip instead of easy_install for installing python modules. If you have easy_install, you can use it to install pip. Type the following command:
$ easy_install pip
Now you can use pip to install the module you want. For example, To install the latest version of "SomeProject":
$ pip install 'SomeProject'
To install a specific version:
$ pip install 'SomeProject==1.4'
To install greater than or equal to one version and less than another:
$ pip install 'SomeProject>=1,<2'
Lines and Indentation in Python

Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −
if True:
print "True"
else:
print "False"
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.
#!/usr/bin/python
import sys
try:
   # open file stream
   file = open(file_name, "w")
except IOError:
   print "There was an error writing to", file_name
   sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
   file_text = raw_input("Enter text: ")
   if file_text == file_finish:
      # close the file
      file.close
      break
   file.write(file_text)
   file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
   print "Next time please enter something"
   sys.exit()
try:
   file = open(file_name, "r")
except IOError:
   print "There was an error reading file"
   sys.exit()
file_text = file.read()
file.close()
print file_text
Java Program for Common Divisors of Two Numbers - GeeksforGeeks

04 Dec, 2018
Given two integer numbers, the task is to find the count of all common divisors of given numbers?
Input : a = 12, b = 24
Output: 6
// all common divisors are 1, 2, 3, 
// 4, 6 and 12

Input : a = 3, b = 17
Output: 1
// all common divisors are 1

Input : a = 20, b = 36
Output: 3
// all common divisors are 1, 2, 4

// Java implementation of program  class Test {    // method to calculate gcd of two numbers    static int gcd(int a, int b)    {        if (a == 0)            return b;          return gcd(b % a, a);    }    // method to calculate all common divisors    // of two given numbers    // a, b --> input integer numbers    static int commDiv(int a, int b)    {        // find gcd of a, b        int n = gcd(a, b);          // Count divisors of n.        int result = 0;        for (int i = 1; i <= Math.sqrt(n); i++) {            // if 'i' is factor of n            if (n % i == 0) {                // check if divisors are equal                if (n / i == i)                    result += 1;                else                    result += 2;            }        }        return result;    }      // Driver method    public static void main(String args[])    {        int a = 12, b = 24;        System.out.println(commDiv(a, b));    }}
6

Please refer complete article on Common Divisors of Two Numbers for more details!
divisors
GCD-LCM
Java Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Java Program to Remove Duplicate Elements From the Array
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
How to delete different rows and columns of a matrix using a single line code in R?

Deletion or addition of rows and columns in a matrix of any size is mostly done by using single square brackets and it is also the easiest way. To delete rows and columns, we just need to use the column index or row index and if we want to delete more than one of them then we can separate them by commas by inserting them inside c as c(-1,-2). If we want to delete more than one rows or columns in a sequence then a colon can be used.
 Live Demo
> M<-matrix(1:100,nrow=10)
> M
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1    11    21 31    41    51 61    71  81     91
[2,] 2    12    22 32    42    52 62    72  82     92
[3,] 3    13    23 33    43    53 63    73  83     93
[4,] 4    14    24 34    44    54 64    74 84      94
[5,] 5    15    25 35    45    55 65    75 85      95
[6,] 6    16    26 36    46    56 66    76 86      96
[7,] 7    17    27 37    47    57 67    77 87      97
[8,] 8    18    28 38    48    58 68    78 88      98
[9,] 9    19    29 39    49    59 69    79 89      99
[10,] 10  20    30 40    50    60 70    80  90     100
> M[-2:-3,-6:-7]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 11 21 31 41 71 81 91
[2,] 4 14 24 34 44 74 84 94
[3,] 5 15 25 35 45 75 85 95
[4,] 6 16 26 36 46 76 86 96
[5,] 7 17 27 37 47 77 87 97
[6,] 8 18 28 38 48 78 88 98
[7,] 9 19 29 39 49 79 89 99
[8,] 10 20 30 40 50 80 90 100
> M[-1:-3,-6:-10]
   [,1] [,2] [,3] [,4] [,5]
[1,] 4 14 24 34 44
[2,] 5 15 25 35 45
[3,] 6 16 26 36 46
[4,] 7 17 27 37 47
[5,] 8 18 28 38 48
[6,] 9 19 29 39 49
[7,] 10 20 30 40 50
> M[c(-1,-3),c(-6,-10)]
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 2 12 22 32 42 62 72 82
[2,] 4 14 24 34 44 64 74 84
[3,] 5 15 25 35 45 65 75 85
[4,] 6 16 26 36 46 66 76 86
[5,] 7 17 27 37 47 67 77 87
[6,] 8 18 28 38 48 68 78 88
[7,] 9 19 29 39 49 69 79 89
[8,] 10 20 30 40 50 70 80 90
> M[c(-5,-8),c(-2,-9)]
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 21 31 41 51 61 71 91
[2,] 2 22 32 42 52 62 72 92
[3,] 3 23 33 43 53 63 73 93
[4,] 4 24 34 44 54 64 74 94
[5,] 6 26 36 46 56 66 76 96
[6,] 7 27 37 47 57 67 77 97
[7,] 9 29 39 49 59 69 79 99
[8,] 10 30 40 50 60 70 80 100
> M[c(-5,-6:-8),c(-2,-9)]
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 21 31 41 51 61 71 91
[2,] 2 22 32 42 52 62 72 92
[3,] 3 23 33 43 53 63 73 93
[4,] 4 24 34 44 54 64 74 94
[5,] 9 29 39 49 59 69 79 99
[6,] 10 30 40 50 60 70 80 100
> M[c(-5),c(-2,-5:-9)]
   [,1] [,2] [,3] [,4]
[1,] 1 21 31 91
[2,] 2 22 32 92
[3,] 3 23 33 93
[4,] 4 24 34 94
[5,] 6 26 36 96
[6,] 7 27 37 97
[7,] 8 28 38 98
[8,] 9 29 39 99
[9,] 10 30 40 100
> M[c(-2,-5),c(-2:-4,-5,-9)]
   [,1] [,2] [,3] [,4] [,5]
[1,] 1 51 61 71 91
[2,] 3 53 63 73 93
[3,] 4 54 64 74 94
[4,] 6 56 66 76 96
[5,] 7 57 67 77 97
[6,] 8 58 68 78 98
[7,] 9 59 69 79 99
[8,] 10 60 70 80 100
GATE | GATE CS 2019 | Question 56 - GeeksforGeeks

19 Feb, 2019
Suppose Y is distributed uniformly in the open interval (1, 6). The probability that the polynomial 3x2 + 6xY + 3Y + 6 has only real roots is (rounded off to 1 decimal place) _________.
Note: This was Numerical Type question.(A) 0.80(B) 0.17(C) 0.20(D) 1Answer: (A)Explanation: For a quadratic polynomial ax2 + bx + c = 0. There are three condition:
b2 - 4ac > 0   {real and distinct root, i.e., two real roots}
b2 - 4ac = 0     {real and equal roots, i.e., only one real root}
b2 - 4ac < 0    {imaginary roots} 
Polynomial 3x2 + 6xY + 3Y + 6 has only real roots,
⇒ b2 – 4ax ≥ 0
⇒ (6Y)2 – 4(3) (3Y+ 6) ≥ 0
⇒ Y2 – Y + 2 ≥ 0

Y ∈ (–∞, – 1] ∩ [2, ∞)
⇒ Y ∈ [2, 6) 
Since y is uniformly distributed in (1, 6).
Probability distributed function,
 f(Y) = (1/5), 1 < y > 6
Hence,
So, answer is 0.8.Quiz of this Question
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-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
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
Construct a DataFrame in Pandas using string data in Python

Here we will see how we can construct a pandas dataframe using string type data. Pandas supports csv files, but we can do the same using string also. For string type data, we have to use one wrapper, that helps to simulate as the data is taken as csv reader.
Here we are using a string that takes data and separated by semicolon.
Let us see the following implementation to get better understanding −
import pandas as pd
from io import StringIO
str_data = StringIO("""Id;Subject;Course_Fee
   10;DBMS;3000
   11;Basic Maths;2000
   12;Data Science;40000
   13;Algorithm;5000
   """)
df = pd.read_csv(str_data, sep =";")
print(df)
Id Subject Course_Fee
0 10 DBMS 3000
1 11 Basic Maths 2000
2 12 Data Science 40000
3 13 Algorithm 5000
How to remove the mapped network drive using PowerShell?

To remove mapped drives from PowerShell on windows systems, you can use both PowerShell and cmd commands.
You can use the below command for a single mapped drive-by specifying the disk drive letter or by using the wildcard character (*).
To remove a single mapped drive.
net use K: /delete
PS C:\WINDOWS\system32> net use K: /delete
K: was deleted successfully.
To remove multiple mapped drives together.
net use * /delete
You need to confirm removing multiple mapped disks together.
PS C:\WINDOWS\system32> net use * /delete
You have these remote connections:

    K:              \\remoteshare\shared
    M:              \\remoteshare\shared folder
Continuing will cancel the connections.

Do you want to continue this operation? (Y/N) [N]: Y
The command completed successfully.

To remove the mapped network drive with PowerShell command, you need to provide the drive letter in the cmdlet. If you want to remove the multiple drives together then separate them by comma (,).
Remove-PSDrive K,M –Force -Verbose

PS C:\WINDOWS\system32> Remove-PSDrive K,M -Force -Verbose
VERBOSE: Performing the operation "Remove Drive" on target "Name: K Provider: Microsoft.PowerShell.Core\FileSystem Root: K:\".
VERBOSE: Performing the operation "Remove Drive" on target "Name: M Provider: Microsoft.PowerShell.Core\FileSystem Root: M:\".


Alternatively, you can get the mapped drive using Get-PSDrive and pipeline Remove-PSDrive command to remove them.
Get-PSDrive K,M | Remove-PSDrive -Force -Verbose
PS C:\WINDOWS\system32> Get-PSDrive K,M | Remove-PSDrive -Force -Verbose
VERBOSE: Performing the operation "Remove Drive" on target "Name: K Provider: Microsoft.PowerShell.Core\FileSystem Root: K:\".
VERBOSE: Performing the operation "Remove Drive" on target "Name: M Provider: Microsoft.PowerShell.Core\FileSystem Root: M:\".
C program to explain the goto statement

The C program evaluates the square root for five numbers. The variable count stores the count of numbers read. When count is less than or equal to 5, goto read statement directs the control to the label read. Otherwise, the program prints a message and stops.
It is used after the normal sequence of program execution by transferring the control to some other part of program.
Following is the C program for usage of goto statement −
#include <math.h>
main(){
   double x, y;
   int count;
   count = 1;
   printf("Enter FIVE real values in a LINE \n");
   read:
   scanf("%lf", &x);
   printf("\n");
   if (x < 0)
      printf("Value - %d is negative\n",count);
   else{
      y = sqrt(x);
      printf("%lf\t %lf\n", x, y);
   }
   count = count + 1;
   if (count <= 5)
      goto read;
   printf("\nEnd of computation");
}
When the above program is executed, it produces the following result −
Enter FIVE real values in a LINE
2.3 -4.5 2 6.8 -44.7
2.300000 1.516575
Value - 2 is negative
2.000000 1.414214
6.800000 2.607681
Value - 5 is negative
End of computation
The 6 Steps of a SQL Select Statement Process | by Wendy Navarrete | Towards Data Science

In this article, I will describe step by step the logical process phases during the execution of a query into a relational database. For doing that, I am going to use two simple unnormalized form tables: Citizen and City. They are described as followed:
Citizen table contains data of distinguished citizens and the identification number of the city they live on, and City is the table with city names and their respective identification number.
Let’s say that we want to know the name of only two city names, except San Bruno, where two or more citizens are living on. We also want the result ordered alphabetically.
This is the query to get the required information.
SELECT city.city_name AS "City"FROM citizenJOIN city ON citizen.city_id = city.city_id WHERE city.city_name != 'San Bruno'GROUP BY city.city_nameHAVING COUNT(*) >= 2ORDER BY city.city_name ASCLIMIT 2
1. Getting Data (From, Join) 2. Row Filter (Where) 3. Grouping (Group by) 4. Group Filter (Having) 5. Return Expressions (Select) 6. Order & Paging (Order by & Limit / Offset)
FROM citizenJOIN city 
The first step in the process is the execution of the statements in From clause followed by the Join clause. The result of these operations is getting a cartesian product of our two tables.
Once the From and Join were executed, the processor will get the qualified rows based on the condition On.
ON citizen.city_id = city.city_id
After getting qualified rows, it is passed on to the Where clause. This evaluates every row using conditional expressions. When rows do not evaluate to true, they will be removed from the set.
WHERE city.city_name != 'San Bruno'
The next step is to execute Group by clause, it will group rows that have the same values into summary rows. After this point, all Select expressions will be evaluated per group, instead of being evaluated per row.
GROUP BY city.city_name
The Having clause consists of a logical predicate, it is processed after the Group by and it can no longer refer to individual rows, only to groups of rows.
HAVING COUNT(*) >= 2
The result of executing this operation will keep the set as the figure above. This is because there are two or more elements in every group.
During this step, the processor evaluates what will be printed as a result of the query, and if there are some functions to run on data like Distinct, Max, Sqrt, Date, Lower, etc. In this case, the select clause just prints the city names and alias the city_name column with the identifier “City”.
SELECT city.city_name AS "City"
The final processing steps of the query deal with presentation ordering and the ability to limit the size of the result set. In our example, it is required to present a maximum of two records ordered alphabetically.
ORDER BY city.city_name ASCLIMIT 2
A better understanding of how things work, better results can be obtained. Having fundamental understandings of how a Select statement is executed, it will make easier to get the expected result-set.
Hopefully, this article is helpful for you as well.
Program to find area of largest square of 1s in a given matrix  in python

Suppose we have a binary matrix, we have to find largest square of 1s in that given matrix.
So, if the input is like
then the output will be 16.
To solve this, we will follow these steps −
res := 0
for i in range 0 to size of matrix, dores := maximum of res and matrix[i, 0]
res := maximum of res and matrix[i, 0]
for i in range 0 to size of matrix[0], dores := maximum of res and matrix[0, i]
res := maximum of res and matrix[0, i]
for i in range 1 to row count of matrix, dofor j in range 1 to column count of matrix, doif matrix[i, j] is same as 1, thenmatrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1res = maximum of res and matrix[i, j]
for j in range 1 to column count of matrix, doif matrix[i, j] is same as 1, thenmatrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1res = maximum of res and matrix[i, j]
if matrix[i, j] is same as 1, thenmatrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1
matrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1
res = maximum of res and matrix[i, j]
return res^2
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
   def solve(self, matrix):
      res = 0
      for i in range(len(matrix)):
         res = max(res, matrix[i][0])
      for i in range(len(matrix[0])):
         res = max(res, matrix[0][i])

      for i in range(1, len(matrix)):
         for j in range(1, len(matrix[0])):
            if matrix[i][j] == 1:
               matrix[i][j] = min(matrix[i - 1][j], matrix[i - 1][j - 1], matrix[i][j - 1]) + 1

               res = max(res, matrix[i][j])

      return res * res

ob = Solution()
matrix = [
   [1, 0, 0, 0, 0, 1, 1],
   [0, 0, 0, 0, 0, 1, 1],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0]
]
print(ob.solve(matrix))
matrix = [  
[1, 0, 0, 0, 0, 1, 1],  
[0, 0, 0, 0, 0, 1, 1],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0] ]
16
Python 3 - time localtime() Method

The method localtime() is similar to gmtime() but it converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
Following is the syntax for localtime() method −
time.localtime([ sec ])

sec − These are the number of seconds to be converted into structure struct_time representation. 
This method does not return any value.
The following example shows the usage of localtime() method.
#!/usr/bin/python3
import time

print ("time.localtime() : %s" , time.localtime())
When we run the above program, it produces the following result:
time.localtime() : time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, 
   tm_hour = 10, tm_min = 13, tm_sec = 50, tm_wday = 0, tm_yday = 46, tm_isdst = 0)


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
What is Metapackage in C# Asp.net Core?

It is known that Microsoft.AspNetCore package is one of the packages added to
many ASP.NET Core templates.
The Microsoft.AspNetCore package is repeatedly included as one of the usual project
dependencies when opening a new ASP.NET Core project. It delivers many of the
crucial packages to position up a basic ASP.NET Core application.
Though, this package does not contain any actual dlls or code itself, it merely contains
a series of dependencies on additional packages. By adding this package to your
project, you bring in all the relevant packages along with their dlls on which it
depends and it is called a metapackage.
Specifically, the packages it lists are −
Microsoft.AspNetCore.Diagnostics
Microsoft.AspNetCore.Hosting
Microsoft.AspNetCore.Routing
Microsoft.AspNetCore.Server.IISIntegration
Microsoft.AspNetCore.Server.Kestrel
Microsoft.Extensions.Configuration.EnvironmentVariables
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Options.ConfigurationExtensions
NETStandard.Library
The versions of these packages you will receive depends on which version of the Microsoft.AspNetCore package you install.
These dependencies deliver the primary basic libraries for setting up a basic
ASP.NET Core server that uses the Kestrel web server and includes IIS Integration.
In terms of the application itself, with the help of this package alone you can load
application settings and environment variables into configuration, use the IOptions
interface, and configure logging to the console.
For middleware, only the Microsoft.AspNetCore.Diagnostics package is included,
which would allow adding middleware such as the ExceptionHandlerMiddleware, the
DeveloperExceptionPageMiddleware and the StatusCodePagesMiddleware.
To complete an application, we cannot use only Metapackage because it does not
provide sufficient controls but we can use Microsoft.AspNetCore.Mvc or
Microsoft.AspNetCore.MvcCore package to add MVC capabilities to our application,
and also some other packages would be needed.
The metapackage just try to use a number of packages that can be applied to many
applications so that we don’t need to load more dependencies but it actual does not do
that because it requires other packages as well. Thus, if the number of packages is
large then the dependencies increases which impacts the real use of metapackage. For
example, one of the dependencies on which the Microsoft.AspNetCore depends is the
NETStandard.Library package, which is also a metapackage and hence the
dependencies increases.
Java Program to validate if a String contains only numbers

To validate if a String has only numbers, you can try the following codes. We have used the matches() method in Java here to check for number in a string.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "978";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}
Checking for string that has only numbers...
String: 978
String has only numbers!
Let us see another example, wherein our string has numbers as well as characters.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "s987jyg";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}
Checking for string that has only numbers...
String: s987jyg
String consist of characters as well!
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks

29 Sep, 2021
A half adder is implemented with XOR and AND gates. A full adder is implemented with two half adders and one OR gate. The propagation delay of an XOR gate is twice that of an AND/OR gate. The propagation delay of an AND/OR gate is 1.2 microseconds. A 4-bit ripple-carry binary adder is implemented by using full adders. The total propagation time of this 4-bit binary adder in microseconds is(A) 19.2 microsecondsAnswer: (A)Explanation: A Ripple Carry Adder allows to add two n-bit numbers. It uses half and full adders. Following diagram shows a ripple adder using full adders.

Let us first calculate propagation delay of a single
1 bit full adder.

Propagation Delay by n bit full adder is (2n + 2) 
gate delays.
[See this for formula].

Here n = 1, so total delay of a 1 bit full adder 
is (2 + 2)*1.2 = 4.8 ms

Delay of 4 full adders is = 4 * 4.8 = 19.2 ms
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersCombinational Circuits Part-2 with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0030:03 / 37:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fhyTnWhFIpA" 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-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
ES6 - while loop

The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.
Following is the syntax for the while loop.
while (expression) {
   Statement(s) to be executed if expression is true
}

var num = 5;
var factorial = 1;
while(num >=1) {
   factorial = factorial * num;
   num--;
}
console.log("The factorial is "+factorial);

The above code uses a while loop to calculate the factorial of the value in the variable num.
The following output is displayed on successful execution of the code.
The factorial is 120


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Explain the difference between a table, view and synonym in SQL

Let us understand what table, view and synonym in the structured query language (SQL) are.
A table is a repository of data, where in the table it is a physical entity. A table resides physically in the database.
A view is not a part of the database’s physical representation. It is precompiled, so that data retrieval behaves faster and also provides a secure accessibility mechanism.
A synonym is an alternate name assigned to a table, view, sequence or program unit.
Create table employee (empID integer primary key, name varchar2(30), skill varchar2(30), salary number(20), DOB datetime).
Let’s say there is a scenario where salary is not shown to a group of users, a view may be created to display allowable information.
Create view emp_some_details as (select empID,name,skill,DOB from employee);
Given below is an program for creating a table, view and synonym in the SQL for the above mentioned example −
create table employee (empID integer primary key, name varchar2(30), skill varchar2(30), salary number(20), DOB datetime);
insert into employee values(100,'AAA','JAVA',30000,2020-08-20);
insert into employee values(101,'BBB','PHP',35000,2020-07-02);
select * from employee;

create view [salary_hide] as select empID,name,skill,DOB from employee ;
select * from salary_hide;
You will get the following output −
100|AAA|JAVA|30000|1992
101|BBB|PHP|35000|2011
100|AAA|JAVA|1992
101|BBB|PHP|2011
The advantages of using a view are as follows −
It may access data from a table, multiple tables, view, multiple views or combinations of these.
It may access data from a table, multiple tables, view, multiple views or combinations of these.
A view connects to the data of its base table(s).
A view connects to the data of its base table(s).
Provides a secure mechanism of data accessibility.
Provides a secure mechanism of data accessibility.
A view can be updated with the CREATE OR REPLACE VIEW statement.
The syntax is as follows −
sql create or replace view view-name As
SELECT column1, column2, ...
FROM table_name
WHERE condition;
To delete view, we can use drop view command −
DROP view view-name;
Synonym is used as an alternate name assigned to a table or view. It may be used to shadow the original name and owner of the actual entity. It extends the reach of tables, by allowing public access to the synonym.
ES6 - Array Method splice()

splice() method changes the content of an array, adding new elements while removing old elements.
array.splice(index, howMany, [element1][, ..., elementN]);     

index − Index at which to start changing the array.
index − Index at which to start changing the array.
howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Returns the extracted array based on the passed parameters.
var arr = ["orange", "mango", "banana", "sugar", "tea"];  
var removed = arr.splice(2, 0, "water");  
console.log("After adding 1: " + arr );  
console.log("removed is: " + removed); 

removed = arr.splice(3, 1);  
console.log("After adding 1: " + arr );  
console.log("removed is: " + removed);   
On compiling, it will generate the same code in JavaScript.
After adding 1: orange,mango,water,banana,sugar,tea 
removed is:  
After adding 1: orange,mango,water,sugar,tea 
removed is: banana 


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How to convert decimal to hexadecimal in JavaScript?

The number class has a toString method that accepts base as argument. We can pass base 16(hex numbers) to get the desired number converted to hexadecimal string.
console.log(Number(255).toString(16))
console.log(Number(17).toString(16))
ff
11
We can convert these numbers back to decimal using the parseInt function. The parseInt function available in JavaScript has the following signature −
parseInt(string, radix);

Where, the paramters are the following −
string −The value to parse. If this argument is not a string, then it is converted to one using the ToString method. Leading whitespace in this argument is ignored.
radix −An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string.
So we can pass the string and the radix and convert any numbner with base from 2 to 36 to integer using this method.
console.log(parseInt("ff", 16))
console.log(parseInt("11", 16))
255
17
Python – Create a string made of the first and last two characters from a given string

12 Nov, 2020
Here we are going to see the approach of forming a string made from the first and last 2 characters of a given string.
Input: Geeksforgeeks
Output: Geks

Input: Hi, There
Output: Hire

Method #1: Using list slicing
In this example, we are going to loop through the string and store the length of the string in the count variable and then make the new substring by taking the first 2 characters and the last two characters with the help of the count variable.
Python
# Taking input from the userinputString = "Geeksforgeeks"  count = 0  # Loop through the stringfor i in inputString:      count = count + 1newString = inputString[ 0:2 ] + inputString [count - 2: count ]   # Printing the new Stringprint("Input string = " + inputString)print("New String = "+ newString)
Output:
Input string = Geeksforgeeks
New String = Geks

Methods #2: Using a loop
In this example we are going to store the length of the string in a variable and break the loop if its length is less than 4 characters otherwise we will store the characters if the variable matches the defined conditions and make a new string out of it.
Python
# Taking input from userinputString = "Geeksforgeeks"  l = len(inputString)newString = ""  # looping through the stringfor i in range(0, len(inputString)):    if l < 3:        break    else:        if i in (0, 1, l-2, l-1):            newString = newString + inputString[i]        else:            continue  # Printing New Stringprint("Input string : " + inputString)print("New String : " + newString)
Output:
Input string : Geeksforgeeks
New String : Geks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
MySQL | CAST( ) Function

25 Nov, 2019
The MySQL CAST() function is used for converting a value from one datatype to another specific datatype. The CAST() function accepts two parameters which are the value to be converted and the datatype to which the value needs to be converted.
The datatypes in which a given value can be converted are:
DATE : It is used to convert a value to the DATE datatype. The Format returned is “YYYY-MM-DD”.
DATETIME : It is used to convert a value to the DATETIME datatype. The Format returned is “YYYY-MM-DD HH:MM:SS”.
TIME : It is used to convert a value to the TIME datatype. The Format returned is “HH:MM:SS”.
CHAR : It is used to convert a value to the CHAR datatype.
SIGNED : It is used to convert a value to SIGNED datatype.
UNSIGNED : It is used to convert a value to UNSIGNED datatype.
BINARY : It is used to convert a value to BINARY datatype.
Syntax:
CAST(input_value AS datatype)
Parameters Used:
input_value – It is used to specify the value which needs to be converted.
datatype – It is used to specify the datatype in which the value needs to be converted.
Return Value:The MySQL CAST() function returns a value in the desired datatype after conversion.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing CAST() function to convert a value to DATE datatype.
SELECT CAST("2019-11-21" AS DATE); 
Output:
2019-11-21 
Example-2: Implementing CAST() function to convert a value to CHAR datatype.
SELECT CAST(121 AS CHAR); 
Output:
121 
Example-3: Implementing CAST() function to convert a value to SIGNED datatype.
SELECT CAST(2-4 AS SIGNED); 
Output:
-2 
Example-4: Implementing CAST() function to convert a value to UNSIGNED datatype.
SELECT CAST(2-4 AS UNSIGNED); 
Output:
18446744073709551614 
mysql
SQLmysql
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?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
File createNewFile() method in Java with Examples

12 May, 2020
The createNewFile() function is a part of File class in Java . This function creates new empty file. The function returns true if the abstract file path does not exist and a new file is created. It returns false if the filename already exists.
Function signature:
public boolean createNewFile()
Syntax:
boolean var = file.createNewFile();
Parameters: This method does not accept any parameter.
Return Type: The function returns boolean data type representing whether the new file is created or not.
Exception: This method throws following exceptions:
IO Exception: if input output error occurs
Security Exception: if the write access to the file is denied
Below programs illustrates the use of createNewFile() function:
Example 1: The file “F:\\program1.txt” does not exist
// Java program to demonstrate// createNewFile() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          try {              // Get the file            File f = new File("F:\\program.txt");              // Create new file            // if it does not exist            if (f.createNewFile())                System.out.println("File created");            else                System.out.println("File already exists");        }        catch (Exception e) {            System.err.println(e);        }    }}
Output:
File created
Example 2: The file “F:\\program.txt” is a existing file in F: Directory.
// Java program to demonstrate// createNewFile() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          try {              // Get the file            File f = new File("F:\\program1.txt");              // Create new file            // if it does not exist            if (f.createNewFile())                System.out.println("File created");            else                System.out.println("File already exists");        }        catch (Exception e) {            System.err.println(e);        }    }}
Output:
File already exists
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
vikas_vaibhav
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Remove first and last character of a string in Java
Program to print ASCII Value of a character
Traverse Through a HashMap in Java
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Gerrit - Make & Commit Your Change

When you modify the code in the local file system, you can check for the changes within the directory using the following command.
$ git diff

In the project directory, we will modify some changes in the file called Example/Example.hooks.php and run the above command. We will get the result as shown in the following screenshot.
You can check the changes made to the files or the directory using the following command.
$ git status

The above command allows to see which changes have been staged, which have not, and which files are not tracked by Git.
Next, you can add the changes in the working directory and update the file in the next commit using following command.
$ git add Example/Example.hooks.php

After adding the file, again run the git status command to review the changes added to the staging area as shown in the following screenshot.
You can see the difference between the index and your last commit, and what contents have been staged, using the following command.
$ git diff --cached

You can push the changes to the remote directory from the local repository using the following command.
$ git commit

When you run the above command, it will ask to add the commit message for your changes. This message will be seen by other people when you push the commit to the other repository.
Add the commit message and run the command again as git commit, which will display the commit message as shown in the following screenshot.
 Print
 Add Notes
 Bookmark this page
Dart Programming - Calling a Function

A function must be called to execute it. This process is termed as function invocation.
function_name()

The following example illustrates how a function can be invoked −
void main() { 
   test(); 
}  
test() { 
   //function definition 
   print("function called"); 
} 
It will produce the following output −
function called


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
What is the difference between Declaring and Initializing a variable in JavaScript?

The following is stated about declaration and initialization of a variable in ECMAScript specification −
A var statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
The above defines the difference:
All variables are initialized with the value undefined.
Variables declarations are initialized with undefined upon the initialization of their lexical environment.
This initialization does not work as an assignment.
How to set default value for empty row in MySQL?

To set default value for empty row, use the concept of COALESCE(). Let us first create a table −
mysql> create table DemoTable1863
     (
     FirstName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1863 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values(NULL);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1863;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Chris     |
| NULL      |
| David     |
| NULL      |
+-----------+
4 rows in set (0.00 sec)
Following is the query to set default value for empty row −
mysql> select coalesce(FirstName,'UNKNOWN NAME') from DemoTable1863;
This will produce the following output −
+------------------------------------+
| coalesce(FirstName,'UNKNOWN NAME') |
+------------------------------------+
| Chris                              |
| UNKNOWN NAME                       |
| David                              |
| UNKNOWN NAME                       |
+------------------------------------+
4 rows in set (0.00 sec)
Node.js fs.promise.readdir() Method

08 Oct, 2021
The fs.promise.readdir() method defined in the File System module of Node.js. The file System module is basically to interact with the hard disk of the users computer. The readdir() method is used to read the files and folders names. The fs.promise.readdir() method returns a resolved or rejected promise and hence avoid the callback nesting or callback hell problems that may occur in fs.readdir() method.
Syntax
fs.promise.readdir(path, options)
Parameter: This method accepts two parameters as mentioned above and described below:
path: It is a string, buffer or url that specifies the path to the directory, whose contents is to be read.
options: It is an optional parameter and used to specify encoding techniques (default-utf8) etc.
Return Value: It returns a resolved or rejected promise. The promise is resolved with the list of the names of files and folders if a directory is successfully read otherwise rejected with an error object if any error is occurred (example-specified directory not exist or does not have permissions to read files etc).
Example 1:
// Node.js program to demonstrate the   // fs.promise.readdir() Method   // Importing File System moduleconst fs = require('fs')  // The process.cwd() gives current// working directoryfs.promises.readdir(process.cwd())      // If promise resolved and    // datas are fetched    .then(filenames => {        for (let filename of filenames) {            console.log(filename)        }    })      // If promise is rejected    .catch(err => {        console.log(err)    })
Output: Read and display the contents of current working directory ‘gfgExamples’
Example 2:
// Node.js program to demonstrate the   // fs.promise.readdir() Method   // Importing File System moduleconst fs = require('fs')  // process.cwd() gives current// working directoryconst targetDir = process.argv[2] || process.cwd()  fs.promises.readdir(targetDir)      // If promise resolved and     // datas are fetched    .then(filenames => {        for (let filename of filenames) {            console.log(filename)        }    })      // If promise is rejected    .catch(err => {        console.log(err)    })
Output: Read and display the contents of one directory back to current working directory ‘gfgExamples’.
Reference: https://nodejs.org/docs/latest/api/fs.html#fs_fspromises_readdir_path_options
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UTC_TIMESTAMP() function in MySQL

13 Oct, 2020
UTC_TIMESTAMP() function in MySQL is used to check current Coordinated Universal Time (UTC) date and time value. It returns the current UTC date and time value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuu format, depending on whether the function is used in string or numeric context.
Syntax :
UTC_TIMESTAMP
 OR
UTC_TIMESTAMP()

Parameter :This method does not accept any parameter.
Returns :It returns the current UTC date and time value.
Example-1 :Getting the current UTC date and time using UTC_TIMESTAMP Function.
SELECT UTC_TIMESTAMP as CurrUtcDateAndTime ;

Output :
Example-2 :Getting the current UTC date and time using UTC_TIMESTAMP Function in numeric format.
SELECT UTC_TIMESTAMP + 0 as CurrUtcDateAndTime ;

Output :
Example-3 :The UTC_TIMESTAMP function can be used to set value of columns. To demonstrate create a table named DeliveryDetails.
CREATE TABLE DeliveryDetails (
DeliveryId INT AUTO_INCREMENT,
ProductId INT NOT NULL,
ProductName VARCHAR(20) NOT NULL,
Delivered_At TIMESTAMP NOT NULL,
PRIMARY KEY(DeliveryId)
);

Here, we will use UTC_TIMESTAMP function when a delivery will be completed. The value in Delivered_At column will be the value given by UTC_TIMESTAMP Function.
INSERT INTO  
DeliveryDetails(ProductId, ProductName, Delivered_At)
VALUES
(1010001, 'Dell  Inspirion', UTC_TIMESTAMP );

Now, checking the DeliveryDetails table :
SELECT * FROM DeliveryDetails;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.