code-rag-bench/online-tutorials huggingface dataset:
Java Program to convert positive int to negative and negative to positive

To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.
Let us first initialize a positive int −
int positiveVal = 200;
Now, let us convert it to negative −
int negativeVal = (~(positiveVal - 1));
Now, let’s say we have the following negative int −
int negativeVal = -300;
The following will convert the negative to positive int −
positiveVal = ~(negativeVal - 1);
 Live Demo
public class Demo {
   public static void main(String[] args) throws java.lang.Exception {
      int positiveVal = 100;
      int negativeVal = (~(positiveVal - 1));
      System.out.println("Result: Positive value converted to Negative = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Actual Positive Value = "+positiveVal);
      negativeVal = -200;
      System.out.println("Actual Negative Value = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Result: Negative value converted to Positive = "+positiveVal);
   }
}
Result: Positive value converted to Negative = -100
Actual Positive Value = 100
Actual Negative Value = -200
Result: Negative value converted to Positive = 200
How to get the index of selected option in Tkinter Combobox?

If you want to create a dropdown list of items and enable the items of list to be selected by the user, then you can use the Combobox widget. The Combobox widget allows you to create a dropdown list in which the list of items can be selected instantly. However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item.
Let’s take an example to see how it works. In this example, we have created a list of days of weeks in a dropdown list and whenever the user selects a day from the dropdown list, it will print and display the index of selected item on a Label widget. To print the index, we can concatenate the string by typecasting the given index into string.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

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

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define Days Tuple
days= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')

# Function to print the index of selected option in Combobox
def callback(*arg):
   Label(win, text= "The value at index " + str(cb.current()) + " is" + " "+ str(var.get()), font= ('Helvetica 12')).pack()
   
# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= days
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

# Set the tracing for the given variable
var.trace('w', callback)

# Create a button to clear the selected combobox text value
button= Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()
Running the above code will display a combobox widget with a list of days. Whenever you select a day from the list, it will print the index and the corresponding item on the label widget.
Time & Work - Solved Examples

Q 1 - A can do a bit of work in 8 days, which B alone can do in 10 days in how long . In how long both cooperating can do it?
A - 40/9 days
B - 41/9 days
C - 42/9 days
D - 43/9 days
Answer - A
Explanation
A's 1 day work= 1/8, B`s 1 day work = 1/10
∴ (A+B) 1 day work = (1/8+1/10) = 9/40
Both cooperating can complete it in 40/9 days.

Q 2 - A and B together can dive a trench in 12 days, which an alone can dive in 30 days. In how long B alone can burrow it?
A - 18 days
B - 19 days
C - 20 days
D - 21 days
Answer - C
Explanation
(A+B)'s 1 day work = 1/12, A's 1 day work =1/30 
∴ B's 1 day work = (1/12-1/30) = 3/60 = 1/20 
Henceforth, B alone can dive the trench in 20 days. 

Q 3 - A can do a bit of work in 25 days which B can complete in 20 days. Both together labor for 5 days and afterward A leaves off. How long will B take to complete the remaining work?
A - 7 days
B - 8 days
C - 9 days
D - 11 days
Answer - D
Explanation
(A+B)'s 5 days work = 5(1/25+1/20) = (5*9/100) = 9/20 
Remaining work = (1-9/20) = 11/20 
1/20 work is finished by B in 1 day 
11/20 work is finished by B in (1*20*11/20) = 11 days

Q 4 - A and B can do a bit of work in 12 days. B and C can do it in 15 days while C and A can do it in 20 days. In how long will they complete it cooperating? Additionally, in how long can A alone do it?
A - 10 days, 30 days.
B - 15 days, 20 days.
C - 20 days, 40 days.
D - 10 days, 50 days.
Answer - A
Explanation
(A+B)'s 1 day work = 1/12, 
(B+C)'s 1 day work = 1/15,
(C+A)'S 1 day work = 1/20 
Including: 2(A+B+C)'s 1 day work = (1/12+ 1/15+ 1/20)= 12/60 = 1/5 
∴ (A+B+C) `s 1 day work = (1/2 *1/5) = 1/10 
∴ working together they can complete the work in 10 days. 
A's 1 day work = (1/10-1/15) = 1/30, B`s 1 day work = (1/10-1/20) = 1/20 
C's 1 day work = (1/10-1/12) = 1/60 
∴ A alone can take the necessary steps in 30 days.

Q 5 - A can fabricate a divider in 30 days , while B alone can assemble it in 40 days, If they construct it together and get an installment of RS. 7000, what B's offer?
A - 2000
B - 3000
C - 4000
D - 6500
Answer - B
Explanation
A's 1 days work = 1/30,
B's 1 day work = 1/40,
Proportion of their shares = 1/30:1/40 = 4:3
B's offer = (7000*3/7) = Rs. 3000

Q 6 - A can do a bit of work in 10 days while B alone can do it in 15 days. They cooperate for 5 days and whatever remains of the work is finished by C in 2 days. On the off chance that they get Rs. 4500 for the entire work, by what means if they partition the cash?
A -  Rs 1250, Rs 1200, Rs 550
B - Rs 2250, Rs 1500, Rs 750
C - Rs 1050, Rs 1000, Rs 500
D - Rs 650, Rs 700, Rs 500
Answer - B
Explanation
(A+B)'s 5 days work = 5(1/10+ 1/15)= (5* 1/6)= 5/6 
Remaining work = (1-5/6) = 1/6 
C's 2 days work = 1/6 
(A's 5 day work): (B's 5 day work): (C's 2 days work) 
= 5/10: 5/15: 1/6 
= 15: 10:5 = 3:2:1 
A's offer = (4500*3/6) = Rs. 2250
B's offer = (4500*2/6) = Rs. 1500 
C's share= (4500*1/6) = Rs. 750


    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
How to create our own Listener interface in android?

This example demonstrate about How to create our own Listener interface in android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:text = "click"
      android:textSize = "30sp" />
</LinearLayout>
In the above code, we have taken text view to show listener data.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements sampleInterFace {
   sampleInterFace interFace;
   TextView textView;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      this.interFace = (sampleInterFace) this;
      interFace.sample("sairamkrishna Mammahe");
   }
   @Override
   public void sample(String text) {
      textView.setText(text);
   }
}
interface sampleInterFace {
   public void sample(String text);
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
How to take screenshots using python? - GeeksforGeeks

17 May, 2021
Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be taking a screenshot. It provides a module named pyautogui which can be used to take the screenshot. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case)
YouTubeGeeksforGeeks500K subscribersHow to Take Screenshot Using Python? | GeeksforGeeksWatch 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:000:00 / 13:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Wk2aaHz3Dv0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
pyautogui takes pictures as a PIL(python image library) which supports opening, manipulating, and saving many different image file formats. Then we need to convert the image to NumPy array, so that it can be converted from RGB to BGR because when the image file is read with the OpenCV using imread(), the order of colors should be BGR (blue, green, red).
Numpy: To install Numpy type the below command in the terminal.pip install numpy

pip install numpy

pyautogui: To install pyautogui type the below command in the terminal.pip install pyautogui

pip install pyautogui

OpenCV: To install OpenCV type the below command in the terminal.pip install opencv-python

pip install opencv-python

Below is the implementation.
# Python program to take# screenshots    import numpy as npimport cv2import pyautogui     # take screenshot using pyautoguiimage = pyautogui.screenshot()   # since the pyautogui takes as a # PIL(pillow) and in RGB we need to # convert it to numpy array and BGR # so we can write it to the diskimage = cv2.cvtColor(np.array(image),                     cv2.COLOR_RGB2BGR)   # writing it to the disk using opencvcv2.imwrite("image1.png", image)
Output:
python-modules
Python-OpenCV
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python program to check if the given number is Happy Number

When it is required to check if a given number is a happy number, the ‘%’ operator, the ‘//’ operator and the ‘+’ operator can be used.
A Happy number is the one that ends up as 1, when it is replaced by the sum of square of every digit in the number.
Below is a demonstration for the same −
 Live Demo
def check_happy_num(my_num):
   remaining = sum_val = 0
   while(my_num > 0):
      remaining = my_num%10
      sum_val = sum_val + (remaining*remaining)
      my_num = my_num//10
   return sum_val;
my_num = 86
my_result = my_num
while(my_result != 1 and my_result != 4):
   my_result = check_happy_num(my_result);
print("The number is being checked")
if(my_result == 1):
   print(str(my_num) + " is a happy number");
elif(my_result == 4):
   print(str(my_num) + " isn't a happy number");
The number is being checked
86 is a happy number
A method named ‘check_happy_num’ is defined, that takes a number as parameter.
It checks to see if the number is greater than 0.
A sum variable is assigned to 0.
It divides the number by 10 and gets the remainder, and assigns it to a value.
This remainder is multipled with itself and added to a ‘sum’ variable.
This occurs on all digits of the number.
This sum is returned as output.
The number is defined, and a copy of it is made.
It is checked to see if it is a happy number by calling the function previously defined.
Relevant message is displayed on the console.
Non capturing groups Java regular expressions:

Using capturing groups you can treat multiple characters as a single unit. You just need to place the characters to be grouped inside a set of parentheses. For example −
(.*)(\\d+)(.*)
If you are trying to match multiple groups the match results of each group is captured. You can get the results a group by passing its respective group number to the group() method. 1,2, 3 etc.. (from right to left) group 0 indicates the whole match.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroups {
   public static void main( String args[] ) {
      System.out.println("Enter input text");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "(.*)(\\d+)(.*)";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex);
      //Now create matcher object.
      Matcher matcher = pattern.matcher(input);
      if (matcher.find( )) {
         System.out.println("Found value: " + matcher.group(0) );
         System.out.println("Found value: " + matcher.group(1) );
         System.out.println("Found value: " + matcher.group(2) );
         System.out.println("Found value: " + matcher.group(3) );
      } else {
            System.out.println("NO MATCH");
      }
   }
}
Enter input text
sample data with 1234 (digits) in middle
Found value: sample data with 1234 (digits) in middle
Found value: sample data with 123
Found value: 4
Found value: (digits) in middle
The non-capturing group provides the same functionality of a capturing group but it does not captures the result
For example, if you need to match a URL or a phone number from a text using groups, since the starting part of the desired sub strings is same you need not capture the results of certain groups in such cases you can use non capturing groups. A non-capturing group starts with (?: and ends with ).
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroups {
   public static void main( String args[] ) {
      System.out.println("Enter input text");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "(.*)(?:\\d+)(.*)";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex);
      //Now create matcher object.
      Matcher matcher = pattern.matcher(input);
      if (matcher.find( )) {
         System.out.println("Found value: " + matcher.group(0) );
         System.out.println("Found value: " + matcher.group(1) );
         System.out.println("Found value: " + matcher.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}
Enter input text
sample data with 1234 (digits) in middle
Found value: sample data with 1234 (digits) in middle
Found value: sample data with 123
Found value: (digits) in middle
Note: The non-capturing group will not be included in the group count.
Print all n-digit strictly increasing numbers in C++

In this problem, we are given a number N and we have to print all n-digit numbers whose digits are strickly increasing from MSB to LSB i.e. the number at LSB (left) should be smaller than the number at right.
Let’s take an example to understand the problem −
Input − n = 2
Output −
01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 
29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89.
Explanation − as you can see all the numbers at the left are smaller than the numbers at the right of them.
To solve this problem, we will start from the MSB (left side) with numbers one by one and then generate numbers according to the condition. The next position will contain digits from i+1 to 9, i is the digit at the current position.
The code to implement code logic −
 Live Demo
#include <iostream>
using namespace std;
void printIncresingNumbers(int start, string out, int n) {
   if (n == 0){
      cout<<out<<" ";
      return;
   }
   for (int i = start; i <= 9; i++){
      string str = out + to_string(i);
      printIncresingNumbers(i + 1, str, n - 1);
   }
}
int main() {
   int n = 3;
   cout<<"All "<<n<<" digit strictly increasing numbers are :\n";
   printIncresingNumbers(0, "", n);
   return 0;
}
All 3 digit strictly increasing numbers are −
012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 
037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 
123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 
156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 
247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 
356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 
479 489 567 568 569 578 579 589 678 679 689 789
C Program on two-dimensional array initialized at run time

Calculate the sum and product of all elements in an array by using the run-time compilation.
A two-dimensional array is used in situations where a table of values have to be stored (or) in matrices applications
The syntax is as follows −
datatype array_ name [rowsize] [column size];
For example, int a[5] [5];
Number of elements in array = rowsize *columnsize = 5*5 = 25
Following is the C program to calculate the sum and product of all elements in an array by using the run-time compilation −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
   //Reading elements into the array's A and B using for loop//
   printf("Enter elements into the array A: \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] :",i,j);
         scanf("%d",&A[i][j]);
      }
      printf("\n");
   }
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("B[%d][%d] :",i,j);
         scanf("%d",&B[i][j]);
      }
      printf("\n");
   }
   //Calculating sum and printing output//
   printf("Sum array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         sum[i][j]=A[i][j]+B[i][j];
         printf("%d\t",sum[i][j]);
      }
      printf("\n");
   }
   //Calculating product and printing output//
   printf("Product array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         product[i][j]=A[i][j]*B[i][j];
         printf("%d\t",product[i][j]);
      }
      printf("\n");
   }
}
When the above program is executed, it produces the following result −
Enter elements into the array A:
A[0][0] :12
A[0][1] :23
A[0][2] :03

A[1][0] :25
A[1][1] :34
A[1][2] :01

B[0][0] :03
B[0][1] :46
B[0][2] :23

B[1][0] :01
B[1][1] :24
B[1][2] :32

Sum array is:
15    69    26
26    58    33
Product array is:
36    1058   69
25    816    32
Filter table with Bootstrap

To filter a table in Bootstrap, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Students Rank</h2>
         <input class = "form-control" id = "demo" type = "text" placeholder = "Seach here,..">
         <br>
         <table class = "table table-bordered table-striped">
            <thead>
               <tr>
               <th>Name</th>
               <th>Marks</th>
               <th>Rank</th>
               </tr>
            </thead>
            <tbody id = "test">
               <tr>
                  <td>Amit</td>
                  <td>94</td>
                  <td>1</td>
               </tr>
               <tr>
                  <td>Tom</td>
                  <td>90</td>
                  <td>2</td>
               </tr>
               <tr>
                  <td>Steve</td>
                  <td>88</td>
                  <td>3</td>
               </tr>
               <tr>
                  <td>Chris</td>
                  <td>80</td>
                  <td>4</td>
               </tr>
               <tr>
                  <td>Corey</td>
                  <td>79</td>
                  <td>5</td>
               </tr>
               <tr>
                  <td>Glenn</td>
                  <td>75</td>
                  <td>6</td>
               </tr>
            </tbody>
         </table>
      </div>
      <script>
         $(document).ready(function(){
            $("#demo").on("keyup", function() {
               var value = $(this).val().toLowerCase();
               $("#test tr").filter(function() {
                  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
               });
            });
         });
      </script>
   </body>
</html>
C++ program to find the sum of the series 1 + 1/2^2 + 1/3^3 + .....+ 1/n^n

In this tutorial, we will be discussing a program to find the sum of the given series 1 + 1/2^2 + 1/3^3 + .....+ 1/n^n.
For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series.
#include <iostream>
#include <math.h>
using namespace std;
//calculating the sum of the series
double calc_sum(int n) {
   int i;
   double sum = 0.0, ser;
   for (i = 1; i <= n; i++)
   ser = 1/ pow(i, i);
   sum += ser;
   return sum;
}
int main() {
   int n = 5;
   double res = calc_sum(n);
   cout << res << endl;
   return 0;
}
0.00032
C++ nested loops

A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
The syntax for a nested for loop statement in C++ is as follows −
for ( init; condition; increment ) {
   for ( init; condition; increment ) {
      statement(s);
   }
   statement(s); // you can put more statements.
}

The syntax for a nested while loop statement in C++ is as follows −
while(condition) {
   while(condition) {
      statement(s);
   }
   statement(s); // you can put more statements.
}

The syntax for a nested do...while loop statement in C++ is as follows −
do {
   statement(s); // you can put more statements.
   do {
      statement(s);
   } while( condition );

} while( condition );

The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <iostream>
using namespace std;
 
int main () {
   int i, j;
   
   for(i = 2; i<100; i++) {
      for(j = 2; j <= (i/j); j++)
         if(!(i%j)) break; // if factor found, not prime
         if(j > (i/j)) cout << i << " is prime\n";
   }
   
   return 0;
}
This would produce the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Multivalued Dependency (MVD) in DBMS - GeeksforGeeks

23 Feb, 2022
MVD or multivalued dependency means that for a single value of attribute ‘a’ multiple values of attribute ‘b’ exist. We write it as,
a --> --> b 
It is read as: a is multi-valued dependent on b.
Suppose a person named Geeks is working on 2 projects Microsoft and Oracle and has 2 hobbies namely Reading and Music. This can be expressed in a tabular format in the following way.
Project and Hobby are multivalued attributes as they have more than one value for a single person i.e., Geeks.
Multi Valued Dependency (MVD) :We can say that multivalued dependency exists if the following conditions are met.
Conditions for MVD :Any attribute say a multiple define another attribute b; if any legal relation r(R), for all pairs of tuples t1 and t2 in r, such that,
t1[a] = t2[a] 
Then there exists t3 and t4 in r such that.
t1[a] = t2[a] = t3[a] = t4[a]
t1[b] = t3[b]; t2[b] = t4[b] 
t1 = t4; t2 = t3 
Then multivalued (MVD) dependency exists.
To check the MVD in given table, we apply the conditions stated above and we check it with the values in the given table.
Condition-1 for MVD –
t1[a] = t2[a] = t3[a] = t4[a] 
Finding from table,
t1[a] = t2[a] = t3[a] = t4[a] = Geeks 
So, condition 1 is Satisfied.
Condition-2 for MVD –
t1[b] = t3[b] 
And 
t2[b] = t4[b] 
Finding from table,
t1[b] = t3[b] = MS 
And 
t2[b] = t4[b] = Oracle 
So, condition 2 is Satisfied.
Condition-3 for MVD –
∃c ∈ R-(a ∪ b) where R is the set of attributes in the relational table.
t1 = t4 
And  
t2=t3 
Finding from table,
t1 = t4 = Reading 
And
t2 = t3 = Music 
So, condition 3 is Satisfied.
All conditions are satisfied, therefore,
a --> --> b 
According to table we have got,
name --> --> project 
And for,
a --> --> C 
We get,
name --> --> hobby 
Hence, we know that MVD exists in the above table and it can be stated by,
name --> --> project
name --> --> hobby 
the_rdx
DBMS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
What is Temporary Table in SQL?
Deadlock in DBMS
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Lower bound in C++

In this tutorial, we will be discussing a program to understand the lower bound in C++.
lower_bound() method in C++ is used to return the very first number in the container object which is not less than the given value.
 Live Demo
#include <bits/stdc++.h>
int main(){
   std::vector<int> v{ 10, 20, 30, 40, 50 };
   std::cout << "Vector contains :";
   for (unsigned int i = 0; i < v.size(); i++)
      std::cout << " " << v[i];
   std::cout << "\n";
   std::vector <int>::iterator low1, low2;
   low1 = std::lower_bound(v.begin(), v.end(), 35);
   low2 = std::lower_bound(v.begin(), v.end(), 55);
   std::cout
      << "\nlower_bound for element 35 at position : "
      << (low1 - v.begin());
   std::cout
      << "\nlower_bound for element 55 at position : "
      << (low2 - v.begin());
   return 0;
}
Vector contains : 10 20 30 40 50
lower_bound for element 35 at position : 3
lower_bound for element 55 at position : 5
HTML | <table> width Attribute

29 May, 2019
The HTML <table> width Attribute is used to specify the width of a table. If width attribute is not set then it takes default width according to content.
Syntax:
<table width="pixels | %">
Attribute Values:
pixels: It sets the width of table in terms of pixels.
%: It sets the width of table in terms of percentage (%).
Note: The <table> width Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML table width Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML table width Attribute</h2>      <table border="1"            width="250">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <table> width Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Python Programs | Set 21 (Bool)

11 Jun, 2021
Prerequisite : Boolean Note: Output of all these programs is tested on Python31. What is the output of the code:  
Python3
print(bool('False'))print(bool())
False, TrueNone, NoneTrue, TrueTrue, False
False, True
None, None
True, True
True, False
Output:  
4. True, False
Explanation: If the argument passed to the bool function does not amount to zero then the Boolean function returns true else it always returns false. In the above code, in first line ‘False’ is passed to the function which is not amount to 0. Therefore output is true. In the second line, an empty list is passed to the function bool. Hence the output is false.2. What is the output of the code:  
Python3
print(not(4>3))print(not(5&5))
False, FalseNone, NoneTrue, TrueTrue, False
False, False
None, None
True, True
True, False
Output:  
1. False, False
Explanation: The not function returns true if the argument is false, and false if the argument is true. Hence the first line of above code returns false, and the second line will also returns false.3. What is the output of the code:  
Python3
print(['love', 'python'][bool('gfg')])
lovepythongfgNone
love
python
gfg
None
Output:  
2. python
Explanation: We can read the above code as print ‘love’ if the argument passed to the Boolean function is zero else print ‘python’. The argument passed to the Boolean function in the above code is ‘gfg’, which does not amount to zero and hence the output is: “python”.4. What is the output of the code:  
Python3
mylist =[0, 5, 2, 0, 'gfg', '', []]print(list(filter(bool, mylist)))
[0, 0, ][0, 5, 2, 0, ‘gfg’, ”, []]Error[5, 2, ‘gfg’]
[0, 0, ]
[0, 5, 2, 0, ‘gfg’, ”, []]
Error
[5, 2, ‘gfg’]
Output:  
4. [5, 2, 'gfg']
Explanation: The code above returns a new list containing only those elements of the list mylist which are not equal to zero. Hence the output is: [5, 2, ‘gfg’].5. What is the output of the code:  
Python3
if (7 < 0) and (0 < -7):    print("abhi")elif (7 > 0) or False:    print("love")else:    print("geeksforgeeks")
geeksforgeeksloveabhiError
geeksforgeeks
love
abhi
Error
Output:  
2. love
Explanation: The code shown above prints the appropriate option depending on the conditions given. The condition which matches is (7>0), and hence the output is: “love”. 
surinderdawra388
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.platform Property

12 Oct, 2021
The process.platform property is an inbuilt application programming interface of the process module which is used to get the Operating System platform information.
Syntax:  
process.platform
Return Value: This property returns a string that represents the operating system platform. The returned value can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunprocess’, and ‘win32’. This values is set at compile time.
Below examples illustrate the use of process.platform property in Node.js:
Example 1:  
Javascript
// Node.js program to demonstrate the// process.platform Property   // Include process moduleconst process = require('process');  // Printing process.platform property valueconsole.log(process.platform);
Output: 
win32
Example 2: 
Javascript
// Node.js program to demonstrate the// process.platform Property   // Include process moduleconst process = require('process');  // Printing process.platform property valuevar platform = process.platform;switch(platform) {    case 'aix':         console.log("IBM AIX platform");        break;    case 'darwin':         console.log("Darwin platform(MacOS, IOS etc)");        break;    case 'freebsd':         console.log("FreeBSD Platform");        break;    case 'linux':         console.log("Linux Platform");        break;    case 'openbsd':         console.log("OpenBSD platform");        break;    case 'sunos':         console.log("SunOS platform");        break;    case 'win32':        console.log("windows platform");        break;        default:         console.log("unknown platform");}
Output: 
windows platform
Note: The above program will compile and run by using the node filename.js command.Reference: https://nodejs.org/api/process.html#process_process_platform 
singghakshay
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
How to connect Node.js with React.js ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Simple Keyboard Racing with Python

21 Jul, 2021
Let’s make a simple keyboard racing game using Python. In the game, the participant clicks a pair of keys in quick succession and the program shows the total time taken by the racer to cover the distance.
Rules: As soon as you see ‘GO!’ on screen, start pressing the keys ‘z’ and ‘x’. A ‘*’ sign is shown for every meter covered. Pressing ‘z’ and ‘x’ once will be counted as 1 meter; targets is to cover 10 meters.
Modules Used: 
msvcrt : Used to get keystroke as input for race
time : Used to calculate time taken to complete the race
Note that MSVCRT module can only function on a terminal window, not on a GUI program/IDE.
Below is the code:  
Python3
import msvcrtimport time high_score = 17.78name = "GeeksforGeeks"while True:    distance = int(0)    print('\n--------------------------------------------------------------')    print('\n\nWelcome to the 100m sprint, tap z and x rapidly to move!')    print('* = 10m')    print('\nCurrent record:' + str(high_score) + ' by: ' + name)    print('\nPress enter to start')    input()    print('Ready...')    time.sleep(1)    print('GO!')     start_time = time.time()    while distance < 10:         k1 = msvcrt.getch().decode('ASCII')        if k1 == 'z':            k2 = msvcrt.getch().decode('ASCII')            if k2 == 'x':                distance += 1                if distance == 5:                    print("* You're halfway there!")                elif distance % 1 == 0:                    print('*')     fin_time = time.time() - start_time    fin_time = round(fin_time, 2)     print('Congratulations on successfully completing the race!')    print('You took', fin_time, 'seconds to reach the finish line')     if fin_time < high_score:        print("Well done you've got a new high score ")        name = input("Please enter your name : ")        high_score = fin_time
Output: 
Game Initiate
Game in Progress
Game Finished: New High Score
 
ruhelaa48
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | push() Function

25 Jun, 2019
push() function in Perl is used to push a list of values onto the end of the array. push() function is often used with pop to implement stacks. push() function doesn’t depend on the type of values passed as list. These values can be alpha-numeric.
Syntax: push(Array, List)
Parameter:Array: in which list of values is to be addedList: which is to be added using push function
Returns:the number of elements in new array.
Example 1:
#!/usr/bin/perl -w  # Original Array@array = ( 10, 20, 30 );  # Printing Array elementsprint "Original Array: @array \n";  # Calling push function to # add a list of elementspush(@array, (35, 40, 55));  # Printing Updated array elementsprint "Updated Array: @array \n";
Output:
Original Array: 10 20 30 
Updated Array: 10 20 30 35 40 55 

 Example 2:
#!/usr/bin/perl -w  # Original Array@array = ( 10, A, 30 );  # Printing Array elementsprint "Original Array: @array \n";  # Calling push function to # add a list of elementspush(@array, (F, G, H));  # Printing Updated array elementsprint "Updated Array: @array \n";
Output:
Original Array: 10 A 30 
Updated Array: 10 A 30 F G H 

Perl-Array-Functions
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Polymorphism in OOPs
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Hello World Program in Perl
Perl | ne operator
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Perl | eq operator
Python | Print the initials of a name with last name in full

21 Nov, 2018
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots.
Examples:
Input : geeks for geeks
Output : G.F.Geeks

Input : mohandas karamchand gandhi
Output : M.K.Gandhi 

A naive approach of this will be to iterate for spaces and print the next letter after every space except the last space. At last space we have to take all the characters after the last space in a simple approach.
Using Python in inbuilt functions we can split the words into a list, then traverse till the second last word and print the first character in capitals using upper() function in python and then add the last word using title() function in Python which automatically converts the first alphabet to capital.
# python program to print initials of a name def name(s):      # split the string into a list     l = s.split()    new = ""      # traverse in the list     for i in range(len(l)-1):        s = l[i]                  # adds the capital first character         new += (s[0].upper()+'.')              # l[-1] gives last item of list l. We    # use title to print first character in    # capital.    new += l[-1].title()          return new       # Driver code            s ="mohandas karamchand gandhi" print(name(s))        
Output:
M.K.Gandhi

Python list-programs
Python string-programs
python-list
python-string
Python
Strings
python-list
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
How do I generate random floats in C++?

In C or C++, we cannot create random float directly. We can create random floats using some trick. We will create two random integer values, then divide them to get random float value.
Sometimes it may generate an integer quotient, so to reduce the probability of that, we are multiplying the result with some floating point constant like 0.5.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
main() {
   srand((unsigned int)time(NULL));
   float a = 5.0;
   for (int i=0;i<20;i++)
      cout << (float(rand())/float((RAND_MAX)) * a) << endl;
}
2.07648
4.3115
1.31092
2.22465
2.17292
1.48381
1.91137
0.56505
2.24326
4.44517
3.1695
2.39067
1.89062
4.35881
4.17524
0.189673
1.87521
1.76916
2.3217
2.20481
Select from table where value does not exist with MySQL?

For this, you can use NOT IN() −
mysql> create table DemoTable1991
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
);
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1991(StudentName) values('Chris');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1991(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1991(StudentName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1991(StudentName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1991(StudentName) values('Mike');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1991;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | David       |
|         4 | Sam         |
|         5 | Mike        |
+-----------+-------------+
5 rows in set (0.03 sec)
Here is the query to select * from table where value does not exist:
mysql> select * from DemoTable1991
   where StudentName NOT IN('Bob','Sam','Mike');
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         3 | David       |
+-----------+-------------+
2 rows in set (0.04 sec)
Java String isEmpty() Method

❮ String Methods

Find out if a string is empty or not:
String myStr1 = "Hello";
String myStr2 = "";
System.out.println(myStr1.isEmpty());
System.out.println(myStr2.isEmpty());

Try it Yourself »

The isEmpty() method checks whether a string 
is empty or not.
This method returns true if the string is empty (length() is 0), and false if not.
public boolean isEmpty()

None.
true - The string is empty (length() is 0)
false - The string is not empty 
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to get an Entry box within a Messagebox in Tkinter?

There are various methods and built-in functions available with the messagebox library in tkinter. Let's assume you want to display a messagebox and take some input from the user in an Entry widget. In this case, you can use the askstring library from simpledialog. The askstring library creates a window that takes two arguments, the title of the window, and the input title before the Entry widget. Let's take an example to understand how it works.
# Import the required library
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter.messagebox import showinfo

# Create an instance of tkinter frame and window
win=Tk()
win.geometry("700x300")

name = askstring('Name', 'What is your name?')
showinfo('Hello!', 'Hi, {}'.format(name))

win.mainloop()
Running the above code will display a popup message box asking the user to enter the name in the given Entry widget.
Enter the name and click "OK". It will display the following message −
How to convert Byte Array to Image in java?

Java provides ImageIO class for reading and writing an image. To convert a byte array to an image.
Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor.
Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor.
Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).
Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).
Finally, Write the image to using the write() method of the ImageIo class.
Finally, Write the image to using the write() method of the ImageIo class.
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ByteArrayToImage {
   public static void main(String args[]) throws Exception {
      BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ImageIO.write(bImage, "jpg", bos );
      byte [] data = bos.toByteArray();
      ByteArrayInputStream bis = new ByteArrayInputStream(data);
      BufferedImage bImage2 = ImageIO.read(bis);
      ImageIO.write(bImage2, "jpg", new File("output.jpg") );
      System.out.println("image created");
   }
}
image created
Intersection of two subgroups of a group is again a subgroup - GeeksforGeeks

05 Mar, 2021
Group : It is a set equipped with a binary operation that combines any two elements to form a third element in such a way that three conditions called group axioms are satisfied, namely associativity, identity, and invertibility.
Subgroup : If a non-void subset H of a group G is itself a group under the operation of G, we say H is a subgroup of G.
To Prove :  Prove that the intersection of two subgroups of a group G is again a subgroup of G.
Proof : Let H1  and H2 be any two subgroups of G.Then,                 
H1 ∩  H2  ≠  ∅
Since at least the identity element ‘e’ is common to both H1 and H2 .In order to prove that H1  ∩ H2  is a subgroup, it is sufficient to prove that
   a ∈ H1 ∩ H2 ,  b ∈ H1 ∩ H2
⇢ a b-1 ∈ H1 ∩ H2
Now,
   a ∈ H1 ∩ H2  
⇢ a ∈ H1  and   a ∈ H2
   b ∈ H1 ∩ H2
⇢ b ∈ H1  and   b ∈ H2
Since H1 and H2 are subgroups.Therefore,
    a ∈ H1  ,  b ∈ H1
⇢  ab-1 ∈ H1 
and                     
   a ∈ H2 ,  b ∈ H2
⇢ ab-1 ∈ H2
Thus,       
   ab-1 ∈ H1    and     ab-1 ∈ H2
⇢ ab-1 ∈ H1 ∩ H2
Hence, H1 ∩  H2 is a subgroup of G and that is our theorem i.e. The intersection of two subgroups of a group is again a subgroup.
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Activation Functions
Difference between Propositional Logic and Predicate Logic
Proof that vertex cover is NP complete
Mathematics | Matrix Introduction
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Brackets in Latex
Secant Method of Numerical analysis
Betweenness Centrality (Centrality Measure)
Calculate age from date of birth in MySQL?

To calculate age from date of birth, you can use the below syntax −
select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentDOB datetime
);
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentDOB) values('1996-01-12');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentDOB) values('1990-12-31');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentDOB) values('1989-04-01');
Query OK, 1 row affected (0.45 sec)
mysql> insert into DemoTable(StudentDOB) values('2000-06-17');
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+---------------------+
| StudentId | StudentDOB          |
+-----------+---------------------+
| 1         | 1996-01-12 00:00:00 |
| 2         | 1990-12-31 00:00:00 |
| 3         | 1989-04-01 00:00:00 |
| 4         | 2000-06-17 00:00:00 |
+-----------+---------------------+
4 rows in set (0.00 sec)
Here is the query to calculate age from date of birth −
mysql> select timestampdiff(YEAR,StudentDOB,now()) AS AGE from DemoTable;
This will produce the following output −
+------+
| AGE  |
+------+
| 23   |
| 28   |
| 30   |
| 18   |
+------+
4 rows in set (0.03 sec)