code-rag-bench/online-tutorials huggingface dataset:
Bernstein's Conditions in Operating System - GeeksforGeeks

05 Jun, 2020
Bernstein’s Conditions are the conditions applied on two statements S1 and S2 that are to be executed in the processor. It states that three conditions that are explained below must be satisfied for two successive statements S1 and S2 to be executed concurrently and still produce the same result.
The intersection between read-write set, write-read set and write-write set of S1 and S2 must be null.
The above statement can be expressed in the form of expressions as following:
1. R(S1) ∩ W(S2) = { }
2. W(S1) ∩ R(S2) = { }
3. W(S1) ∩ W(S2) = { } 
The read and write set for the statement c = a – b;
R(c=a-b) = {a, b}
W(c=a-b) = {c} 
The read and write set for the statement w = c + 1;
R(w=c+1) = {c}
W(w=c+1) = {w} 
The read and write set for the statement x = x + 2;
R(x=x+2) = {x}
W(x=x+2) = {x} 
Example-1:Let,
S1 : a = x + y 
S2 : b = z + 1 
Check whether two statements S1 and S2 satisfies Bernstein’s conditions.Solution:
R(S1) = {x, y}
W(S1) = {a}
R(S2) = {z}
W(S2) = {b}

1. R(S1) ∩ W(S2) = {x, y} ∩ {b} = { }
2. W(S1) ∩ R(S2) = {a} ∩ {z} = { }
3. W(S1) ∩ W(S2) = {a} ∩ {b} = { } 
Therefore S1 ans S2 can be executed concurrently i.e., Bernstein’s conditions are satisfied.
Example-2:Let,
S1 : a = x + y 
S2 : b = z + 1 
S3 : c = a - b 
Check whether two statements S2 and S3 satisfies Bernstein’s conditions.
Solution:
R(S2) = {z}
W(S2) = {b}
R(S3) = {a, b}
W(S3) = {c}

1. R(S2) ∩ W(S3) = {z} ∩ {c} = { }
2. W(S2) ∩ R(S3) = {b} ∩ {a, b} = {b}
3. W(S2) ∩ W(S3) = {b} ∩ {c} = { } 
Therefore S2 ans S3 cannot be executed concurrently i.e., Bernstein’s conditions are not satisfied.
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Memory Management in Operating System
File Allocation Methods
Segmentation in Operating System
Difference between Internal and External fragmentation
Mutex lock for Linux Thread Synchronization
Program for Least Recently Used (LRU) Page Replacement algorithm
Introduction of Process Management
States of a Process in Operating Systems
Logical and Physical Address in Operating System
Structures of Directory in Operating System
How to create Instagram Like button in ReactJS? - GeeksforGeeks

20 Jan, 2021
We can create Instagram Like Button in ReactJS using the checkbox component, FormControlLabel component, and Icon component. Material UI for React has this component available for us and it is very easy to integrate. It can be used to turn an option on or off. We can create Instagram like button in ReactJS using the following approach:
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
@material-ui/icons
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Checkbox from '@material-ui/core/Checkbox';import Favorite from '@material-ui/icons/Favorite';import FavoriteBorder from '@material-ui/icons/FavoriteBorder';  const App = () => {    return (    <div style={{      margin: 'auto',      display: 'block',      width: 'fit-content'    }}>      <h3>How to use HeartCheckBox in ReactJS?</h3>      <FormControlLabel        control={<Checkbox icon={<FavoriteBorder />}                   checkedIcon={<Favorite />}          name="checkedH" />}        label="Instagram Like Button"      />    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks

17 Sep, 2021
Consider the intermediate code given below:
1. i = 1
2. j = 1
3. t1 = 5 * i
4. t2 = t1 + j
5. t3 = 4 * t2
6. t4 = t3
7. a[t4] = –1
8. j = j + 1
9. if j <= 5 goto(3)
10. i = i + 1
11. if i < 5 goto(2) 
The number of nodes and edges in the control-flow-graph constructed for the above code, respectively, are
(A) 5 and 7(B) 6 and 7(C) 5 and 5(D) 7 and 8Answer: (B)Explanation: Below is control flow graph of above code.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch 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:0035:26 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" 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.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
Selenium - Find all Links

Testers might be in a situation to find all the links on a website. We can easily do so by finding all elements with the Tag Name "a", as we know that for any link reference in HTML, we need to use "a" (anchor) tag.
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class getalllinks {

   public static void main(String[] args) {
   
      WebDriver driver = new FirefoxDriver();
      driver.navigate().to("http://www.calculator.net");
      java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
      System.out.println("Number of Links in the Page is " + links.size());
      
      for (int i = 1; i<=links.size(); i = i+1) {
         System.out.println("Name of Link# " + i + links.get(i).getText());
      }
   }
}
The output of the script would be thrown to the console as shown below. Though there are 65 links only partial output is shown below.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
How to get the closest input value from clicked element with jQuery?

To get the closest input value from clicked element with jQuery, follow the steps −
You need to use closest to find the closest ancestor matching the given.
Now, find the input with the given name using the attribute equals selector.
The last step is to use val() metjod to retrieve the value of the input.
Let’s first see how to add jQuery −
You can try to run the following code to get closest input value from clicked element with jQuery −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
             $(".add").on("click", function () {
                var v = $(this).closest("div.content").find("input[name=’rank’]").val();
                alert(v);
             });
         });
      </script>
   </head>
<body>
  <div class="content">
     <div class="ranking">
        <label>Rank:</label>
        <input type="text" name="rank" value="1"/>
     </div>
     <div class="buttons">
        <a href="#" class="add">Click</a>
     </div>
  </div>  
</body>
</html>
PyTorch - Feature Extraction in Convents

Convolutional neural networks include a primary feature, extraction. Following steps are used to implement the feature extraction of convolutional neural network.
Import the respective models to create the feature extraction model with “PyTorch”.
import torch
import torch.nn as nn
from torchvision import models

Create a class of feature extractor which can be called as and when needed.
class Feature_extractor(nn.module):
   def forward(self, input):
      self.feature = input.clone()
      return input
new_net = nn.Sequential().cuda() # the new network
target_layers = [conv_1, conv_2, conv_4] # layers you want to extract`
i = 1
for layer in list(cnn):
   if isinstance(layer,nn.Conv2d):
      name = "conv_"+str(i)
      art_net.add_module(name,layer)
      if name in target_layers:
         new_net.add_module("extractor_"+str(i),Feature_extractor())
      i+=1
   if isinstance(layer,nn.ReLU):
      name = "relu_"+str(i)
      new_net.add_module(name,layer)
   if isinstance(layer,nn.MaxPool2d):
      name = "pool_"+str(i)
      new_net.add_module(name,layer)
new_net.forward(your_image)
print (new_net.extractor_3.feature)
 Print
 Add Notes
 Bookmark this page
C# Program to convert a Double to an Integer Value

To convert a Double value to an integer value, use the Convert.ToInt32() method.
Int32 represents a 32-bit signed integer.
Let’s say the following is our double value.
double val = 21.34;
Now to convert it to Int32.
int res = Convert.ToInt32(val);
Let us see the complete example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      double val = 21.34;
      int res = Convert.ToInt32(val);
      Console.WriteLine("Converted double {0} to integer {1} ", val, res);
   }
}
Converted double 21.34 to integer 21
Tryit Editor v3.7

Tryit: Using the animation-fill-mode property
Scala short /(x: Int): Int - GeeksforGeeks

05 Dec, 2019
Short, a 16-bit signed integer (equivalent to Java’s short primitive type) is a subtype of scala.AnyVal. The /(x: Int) method is utilized to return a result of the quotient operation on the specified Int value by the x.
Method Definition: def /(x: Int): Int
Return Type: It returns quotient with value and x.
Example #1:
// Scala program of Short /(x: Int) // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Applying Short /(x: Int) function         val result = (998.toShort)./(20:Int)                  // Displays output         println(result)           } } 
Output:
49

Example #2:
// Scala program of Short /(x: Int) // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Applying Short /(x: Int) function         val result = (-111.toShort)./(47:Int)                  // Displays output         println(result)           } } 
Output:
-2

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hello World in Scala
Scala Map get() method with example
Scala ListBuffer
Scala List map() method with example
How to install Scala on Windows?
Inheritance in Scala
Scala | Case Class and Case Object
Scala | Traits
Scala List length() method with example
GATE | GATE-CS-2005 | Question 59 - GeeksforGeeks

15 Sep, 2021
Consider the grammar
E → E + n | E × n | n 
For a sentence n + n × n, the handles in the right-sentential form of the reduction are(A) n, E + n and E + n × n(B) n, E + n and E + E × n(C) n, n + n and n + n × n(D) n, E + n and E × nAnswer: (D)Explanation:
E → E * n       {Applying E → E * n } 
  → E + n * n   {Applying E → E + n } 
  → n + n * n   {Applying E → n } 
Hence, the handles in right sentential form is n, E + n and E × n.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | 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:0054:19 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" 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
madarsh986
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
Perl | return() Function - GeeksforGeeks

07 May, 2019
return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.
Syntax: return Value
Returns:a List in Scalar Context
Note: If no value is passed to the return function then it returns an empty list in the list context, undef in the scalar context and nothing in void context.
Example 1:
#!/usr/bin/perl -w  # Subroutine for Multiplicationsub Mul($$) {    my($a, $b ) = @_;      my $c = $a * $b;          # Return Value        return($a, $b, $c);}  # Calling in Scalar context$retval = Mul(25, 10);print ("Return value is $retval\n" );  # Calling in list context@retval = Mul(25, 10);print ("Return value is @retval\n" );
Return value is 250
Return value is 25 10 250

Example 2:
#!/usr/bin/perl -w  # Subroutine for Subtractionsub Sub($$) {    my($a, $b ) = @_;           my $c = $a - $b;          # Return Value        return($a, $b, $c);}  # Calling in Scalar context$retval = Sub(25, 10);print ("Return value is $retval\n" );  # Calling in list context@retval = Sub(25, 10);print ("Return value is @retval\n" );
Return value is 15
Return value is 25 10 15

perl-basics
Perl-function
Perl-Inbuilt-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl | Polymorphism in OOPs
Perl | File Handling Introduction
Perl | Arrays
Perl | length() Function
Perl Tutorial - Learn Perl With Examples
Perl | Multidimensional Hashes
Perl | Reading Excel Files
Perl | my keyword
Perl | shift() Function
Fragment in React.js

Most of the times we need to return multiple elements from a component. React Fragment helps in returning multiple elements. The other alternative is to use a html element like div to wrap them. But using extra html node can cause some semantic issues.
render() {
   return (
      <React.Fragment>
      <ElementA />
      <ElementB />
      <ElementC />
      </React.Fragment>
   );
}
The short syntax is <>:
render() {
   return (
      <>
         <ElementA />
         <ElementB />
         <ElementC />
      </>
   );
}
Understanding the problem if React Fragment is not used −
Suppose we create a table −
class ExampleTable extends React.Component {
   render() {
      return (
         <table>
            <tr>
               <ExampleColumns />
            <tr>
         </table>
      );
   }
}
class ExampleColumns extends React.Component {
   render() {
      return (
         <div>
            <td>col 1</td>
            <td>col 2</td>
         </div>
      );
   }
}
The actual syntax will include the div which we have added in the return statement of columns.
<table>
   <tr>
      <div>
         <td>col 1 </td>
         <td>col 2</td>
      </div>
   </tr>
</table>
Now, table tag is containing a div tag which is breaking the semantic of the html. So to avoid this we can simply replace the div with React.Fragment or in short <>
class ExampleColumns extends React.Component {
   render() {
      return (
         <>
            <td>col 1</td>
            <td>col 2</td>
         </>
      );
   }
}
We can use the fragment in iterating of list as well.
props.myMessages.map(message => (
   // Without the `key`, React will fire a key warning
   <React.Fragment key={message.id}>
      <dt>{message.title}</dt>
      <dd>{message.text}</dd>
   </React.Fragment>
))
char vs string keywords in C#

Use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.
For example.
string name;
name = "Tom Hanks";

Another example.
string [] array={ "Hello", "From", "Tutorials", "Point" };

The char keyword is used to set array of characters.
For example.
char[] ch = new char[2];
ch[0] = 'A';        // Character literal
ch[1] = 'B';        // Character literal

Another example.
char []letters= { 'H', 'e', 'l', 'l','o' };
Jenkins â Tomcat Setup

The following prerequisites must be met for Jenkins Tomcat setup.
To verify Java installation, open the console and execute the following java command.
If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on.
Java version "1.7.0_60"
Java (TM) SE Run Time Environment (build 1.7.0_60-b19)
Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode)
java version "1.7.0_25"
Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)
Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)
We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial.
In case you do not have Java JDK, you can download it from the link Oracle
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,
Append the full path of the Java compiler location to the System Path.
Verify the command java-version from command prompt as explained above.
The official website for tomcat is Tomcat. If you click the given link, you can get the home page of the tomcat official website as shown below.
Browse to the link https://tomcat.apache.org/download-70.cgi to get the download for tomcat.
Go to the ‘Binary Distributions’ section. Download the 32-bit Windows zip file.
Then unzip the contents of the downloaded zip file.
Copy the Jenkis.war file which was downloaded from the previous section and copy it to the webapps folder in the tomcat folder.
Now open the command prompt. From the command prompt, browse to the directory where the tomcat7 folder is location. Browse to the bin directory in this folder and run the start.bat file
E:\Apps\tomcat7\bin>startup.bat

Once the processing is complete without major errors, the following line will come in the output of the command prompt.
INFO: Server startup in 1302 ms

Open the browser and go to the link − http://localhost:8080/jenkins. Jenkins will be up and running on tomcat.
C | Structure & Union | Question 8

28 Jun, 2021
union test{    int x;    char arr[4];    int y;};  int main(){    union test t;    t.x = 0;    t.arr[1] = 'G';    printf("%s", t.arr);    return 0;}
Predict the output of above program. Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also assume that there is no alignment needed.(A) Nothing is printed(B) G(C) Garbage character followed by ‘G’(D) Garbage character followed by ‘G’, followed by more garbage characters(E) Compiler ErrorAnswer: (A)Explanation: Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. O is ASCII value of ‘\0’. When we do “t.arr[1] = ‘G'”, arr[] becomes “\0G\0\0”. When we print a string using “%s”, the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.Quiz of this Question
C-Structure & Union
Structure & Union
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
Unordered Sets in C++ Standard Template Library
Enumeration (or enum) in C
C Language Introduction
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | Storage Classes and Type Qualifiers | Question 1
C | Dynamic Memory Allocation | Question 7
Output of C programs | Set 64 (Pointers)
Numpy string operations | replace() function

29 Aug, 2020
In the numpy.core.defchararray.replace() function, each element in arr, return a copy of the string with all occurrences of substring old replaced by new.
Syntax : numpy.core.defchararray.replace(arr, old, new, count = None)
Parameters :
 arr : [array-like of str]  Given array-like of string.
 old : [str or unicode] Old substring you want to replace.
 new : [str or unicode] New substring which would replace the old substring.
 count : [int, optional] If the optional argument count is given, only the first count occurrences are replaced.
Return : [ndarray] Return the output array of str .
Code #1 :  
Python3
# Python program explaining # numpy.char.replace() function   # importing numpy as geek  import numpy as geek   gfg = geek.char.replace('GFG | a computer science portal for geeks', 'GFG', 'GeeksforGeeks')    print (gfg)
Output :  
GeeksforGeeks | a computer science portal for geeks
 Code #2 :  
Python3
# Python program explaining # numpy.char.replace() function   # importing numpy as geek  import numpy as geek   gfg = geek.char.replace('This is a python article', 'python', 'Numpy-Python', count = 1)    print (gfg)
Output : 
This is a Numpy-Python article
Python numpy-String Operation
Python-numpy
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python Program to check Armstrong Number
Appending a dictionary to a list in Python
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python | Remove spaces from a string
Python Program for Merge Sort
Python Program for simple interest
Python | Get the first key in dictionary
SQL | SYNONYM

24 Aug, 2020
A SYNONYM provides another name for database object, referred to as original object, that may exist on a local or another server. A synonym belongs to schema, name of synonym should be unique. A synonym cannot be original object for an additional synonym and synonym cannot refer to user-defined function.
The query below results in an entry for each synonym in database. This query provides details about synonym metadata such as the name of synonym and name of the base object.
select * 
from sys.synonyms ;
Note : Synonyms are database dependent and cannot be accessed by other databases.
Syntax –
CREATE SYNONYM synonymname 
FOR servername.databasename.schemaname.objectname;
GO
Example –Let us assume Geektabtable of GFGdatabase, Geeekshschema on server named Server1. To reference this table from another server, Server2, an application would have to use four-part named Server1.GFG.Geeeksh.Geektab. Also, if the location of table were to change, for example, to another server, application would have to be modified to reflect that change.
To address both these issues, one can create synonym, Geektable, on Server2for Geektabtable on Server1. Now, the application only has to use single-part name, Geektable, to point Geektab table. Also, if location of the Geektab table changes, you will have to modify synonym, Geektable, to point to new location of Geektab table.
Now, let us create synonym for Geektab table of GFG database, Geeeksh schema on server named Server1.
CREATE SYNONYM Geektable  
FOR Server1.GFG.Geeeksh.Geektab;  
GO
Find the output in Server2 by using synonym.
SELECT ID, Name    
FROM Geektable;
Output –
(4 row(s) affected)
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
OLAP Guidelines (Codd's Rule)
What is Temporary Table in SQL?
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
PHP | getdate() Function - GeeksforGeeks

03 Jul, 2018
The getdate() function is an inbuilt function in PHP which is used to get date/time information of the current local date/time.
Syntax:
getdate($timestamp)
Parameters: The getdate() function accepts one parameter and it is described below:
$timestamp: It is an optional parameter which specifies an integer unix timestamp. Default is the current local time (time()).
Return Value:The function returns an array with information of the timestamp.
[seconds] – seconds
[minutes] – minutes
[hours] – hours
[mday] – day of the month
[wday] – day of the week
[mon] – month
[year] – year
[yday] – day of the year
[weekday] – name of the weekday
[month] – name of the month
[0] – seconds since Unix Epoch
Below programs illustrate the getdate() function in PHP:Program 1:
<?php// PHP program to illustrate // getdate() function  print_r(getdate());?>
Array
(
    [seconds] => 40
    [minutes] => 25
    [hours] => 6
    [mday] => 3
    [wday] => 2
    [mon] => 7
    [year] => 2018
    [yday] => 183
    [weekday] => Tuesday
    [month] => July
    [0] => 1530599140
)

Program 2:
<?php  // Unix timestamp for date // 27-june-2018 10:10:10 // is 1530094210  $y = 1530094210;$today = getdate($y);  print_r($today);?>
Array
(
    [seconds] => 10
    [minutes] => 10
    [hours] => 10
    [mday] => 27
    [wday] => 3
    [mon] => 6
    [year] => 2018
    [yday] => 177
    [weekday] => Wednesday
    [month] => June
    [0] => 1530094210
)

Reference: http://php.net/manual/en/function.getdate.php
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
C++ Program to Split the array and add the first part to the end - GeeksforGeeks

05 Dec, 2018
There is a given an array and split it from a specified position, and move the first part of array add to the end.
Examples:
Input : arr[] = {12, 10, 5, 6, 52, 36}
            k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}
Explanation : Split from index 2 and first 
part {12, 10} add to the end .

Input : arr[] = {3, 1, 2}
           k = 1
Output : arr[] = {1, 2, 3}
Explanation : Split from index 1 and first
part add to the end.

// CPP program to split array and move first// part to end.#include <bits/stdc++.h>using namespace std;  void splitArr(int arr[], int n, int k){    for (int i = 0; i < k; i++) {          // Rotate array by 1.        int x = arr[0];        for (int j = 0; j < n - 1; ++j)            arr[j] = arr[j + 1];        arr[n - 1] = x;    }}  // Driver codeint main(){    int arr[] = { 12, 10, 5, 6, 52, 36 };    int n = sizeof(arr) / sizeof(arr[0]);    int position = 2;      splitArr(arr, 6, position);      for (int i = 0; i < n; ++i)        printf("%d ", arr[i]);      return 0;}
5 6 52 36 12 10

Please refer complete article on Split the array and add the first part to the end for more details!
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Iterative Letter Combinations of a Phone Number
Setting up Sublime Text for C++ Competitive Programming Environment
Return by reference in C++ with Examples
Why it is important to write "using namespace std" in C++ program?
How to sort an Array in descending order using STL in C++?
Node.js Buffer.readFloatBE() Method - GeeksforGeeks

13 Oct, 2021
The Buffer.readFloatBE() Method is an inbuilt application programming interface of class Buffer within the Buffer module which is used to read big endian 32 bits floating-point value to an allocated buffer at the specified offset.
Syntax:
Buffer.readFloatBE( offset )
Parameters: This method accepts single parameter offset which specifies the number of bytes to skip before read. The value of offset lies 0 <= offset <= Buffer.length – 4. It’s default value is 0.
Return Value: It returns an integer value in big endian format.
Below examples illustrate the use of buf.readFloatBE() Method in Node.js:
Example 1:
// Node program to demonstrate the  // Buffer.readFloatBE(INTEGER) method // Creating a buffer of given size const buf = Buffer.from([10, 20, 30, 40, 50, 60, 70, 80]);  // Display the result console.log("Functions of Buffer.readFloatBE(int)");console.log(buf.readFloatBE(0))console.log(buf); 
Output:
Functions of Buffer.readFloatBE(int)
7.13161255447549e-33
<Buffer 0a 14 1e 28 32 3c 46 50>
Example 2:
// Node program to demonstrate the  // Buffer.readFloatBE(INTEGER) method // Creating a buffer of given size const buf = Buffer.from([100, 200, 300, 400, 500, 600, 700, 800]);  // Display the result console.log("Functions of Buffer.readFloatBE(int)"); console.log(buf.readFloatBE(5))console.log(buf); 
Output:
Functions of Buffer.readFloatBE(int)
internal/buffer.js:72
  throw new ERR_OUT_OF_RANGE(type || 'offset',
  ^

RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.
It must be >= 0 and <= 4. Received 5
   . . .
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/docs/latest-v11.x/api/buffer.html#buffer_buf_readfloatbe_offset
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Python | sympy.expand_log() method - GeeksforGeeks

25 Jun, 2019
With the help of sympy.expand_log(), we can simplify the log terms in the mathematical expression by using the following properties that are listed below.
Properties :1) log(x*y)=log(x)+log(y)2) log(x**n)=nlog(x)
Syntax : sympy.expand_log()Return : Return the simplified mathematical expression.
Example #1 :In this example we can see that by using sympy.expand_log(), we are able to simplify the log terms in mathematical expression.
# import sympyfrom sympy import *   x, y, z = symbols('x y z', positive = True)gfg_exp = log(x * y)    # Using sympy.expand_log() methodgfg_exp = expand_log(gfg_exp)    print(gfg_exp)
Output :
log(x) + log(y)
Example #2 :
# import sympyfrom sympy import *   x, y, z = symbols('x y z', positive = True)gfg_exp = log(x**3)    # Using sympy.expand_log() methodgfg_exp = expand_log(gfg_exp)    print(gfg_exp)
Output :
3*log(x)
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
How to add a legend to a scatter plot in Matplotlib ? - GeeksforGeeks

10 Nov, 2021
In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph. 
Syntax: matplotlib.pyplot.legend( [“title_1”, “Title_2”],  ncol = 1 , loc = “upper left” ,bbox_to_anchor =(1, 1) )
Parameters :
ncol: [takes int, optional parameter] the default value is 1. It represents the number of columns in legend.
loc: [takes string, optional parameter] the default value is “best” i.e “upper left”. It represents the location of the legend. Other options can be: “best”, “upper right”, “upper left”, “lower left”, “lower right” , “right”, “center left”, “center right”, “lower center”, “upper center”, “center”.
bbox_to_anchor: [takes a list or tuple of 2 int/float, optional parameter ]. It represents the co-ordinates of legend on the graph. Both x and y co-ordinates are mandatory to give.
Example 1: 
Python3
# import required modulesimport matplotlib.pyplot as plt # adjust coordinatesx =  [1,2,3,4,5]y1 = [2,4,6,8,10]y2 = [3,6,9,12,15] # depict illustrationplt.scatter(x, y1)plt.scatter(x,y2) # apply legend()plt.legend(["x*2" , "x*3"])plt.show()
Output:
Example 2:
Python3
# impoert required modulesimport matplotlib.pyplot as plt # adjust coordinatesx =  [1,2,3,4,5]y1 = [2,4,6,8,10]y2 = [3,6,9,12,15] # depict illustrationplt.scatter(x, y1)plt.scatter(x,y2) # apply legend()plt.legend(["x*2" , "x*3"], ncol = 2 , loc = "lower right")plt.show()
Output:
Example 3:
Python3
# import required modulesimport matplotlib.pyplot as plt # adjust coordinatesx =  [1,2,3,4,5]y1 = [2,4,6,8,10]y2 = [3,6,9,12,15] # depict illustrationplt.scatter(x, y1)plt.scatter(x,y2) # apply legend()plt.legend(["x*2" , "x*3"], bbox_to_anchor = (1 , 1))plt.show()
Output:
Note : We may label the elements of the plot in matplotlib.pyplot.scatter() using “label” parameter. However, to show it matplotlib.pyplot.legend() must be written. 
Example 4:
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy as np # assign coordinatesx = np.arange(1, 6)y1 = x**2y2 = x**4 # depict illustrationplt.scatter(x, y1, label="x**2")plt.scatter(x, y2, label="x**4") # apply legend()plt.legend()plt.show()
Output:
Note: If matplotlib.pyplot.legend() is not written in code, then labels will not be shown.
sumitgumber28
surindertarika1234
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
How to create a form with icons using CSS?

Following is the code to create a form with icons −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
* {
   box-sizing: border-box;
}
h1 {
   text-align: center;
}
form {
   max-width: 500px;
   margin: auto;
}
.fieldContainer {
   display: flex;
   width: 100%;
   margin-bottom: 15px;
}
.icon {
   font-size: 30px;
   padding: 10px;
   background: rgb(11, 9, 116);
   color: white;
   min-width: 50px;
   text-align: center;
}
.field {
   font-size: 20px;
   width: 100%;
   padding: 10px;
   outline: none;
}
.field:focus {
   border: 2px solid dodgerblue;
}
.btn {
   font-size: 24px;
   background-color: rgb(20, 60, 170);
   color: white;
   padding: 15px 20px;
   border: none;
   cursor: pointer;
   width: 100%;
   opacity: 0.9;
   border-radius: 8px;
}
.btn:hover {
   opacity: 1;
}
</style>
</head>
<body>
<h1>Register Form Example</h1>
<form action="/action_page.php">
<div class="fieldContainer">
<i class="fa fa-user icon"></i>
<input class="field" type="text" placeholder="Username" name="usrnm" />
</div>
<div class="fieldContainer">
<i class="fa fa-envelope icon"></i>
<input class="field" type="text" placeholder="Email" name="email" />
</div>
<div class="fieldContainer">
<i class="fa fa-key icon"></i>
<input class="field" type="password" placeholder="Password" name="pass"/>
</div>
<div class="fieldContainer">
<i class="fa fa-birthday-cake icon" aria-hidden="true"></i>
<input class="field" type="text" placeholder="Date of Birth" name="dob"/>
</div>
<button type="submit" class="btn">Register</button>
</form>
</body>
</html>
This will produce the following output −
Interfacing DAC with 8051 Microcontroller

In this section we will see how DAC (Digital to Analog Converter) using Intel 8051 Microcontroller. We will also see the sinewave generation using DAC.
The Digital to Analog converter (DAC) is a device, that is widely used for converting digital pulses to analog signals. There are two methods of converting digital signals to analog signals. These two methods are binary weighted method and R/2R ladder method. In this article we will use the MC1408 (DAC0808) Digital to Analog Converter. This chip uses R/2R ladder method. This method can achieve a much higher degree of precision. DACs are judged by its resolution. The resolution is a function of the number of binary inputs. The most common input counts are 8, 10, 12 etc. Number of data inputs decides the resolution of DAC. So if there are n digital input pin, there are 2n analog levels. So 8 input DAC has 256 discrete voltage levels.
In this chip the digital inputs are converted to current. The output current is known as Iout by connecting a resistor to the output to convert into voltage. The total current provided by the Iout pin is basically a function of the binary numbers at the input pins D0 - D7 (D0 is the LSB and  D7 is the MSB) of DAC0808 and the reference current Iref. The following formula is showing the function of Iout
IOut=Iref⟮D72+D64+D58+D416+D332+D264+D1128+D0256⟯
The Iref is the input current. This must be provided into the pin 14. Generally 2.0mA is used as Iref
We connect the Iout pin to the resistor to convert the current to voltage. But in real life it may cause inaccuracy since the input resistance of the load will also affect the output voltage. So practically Iref current input is isolated by connecting it to an Op-Amp with Rf = 5KΩ as feedback resistor. The feedback resistor value can be changed as per requirement.
For generating sinewave, at first we need a look-up table to represent the magnitude of the sine value of angles between 0° to 360°. The sine function varies from -1 to +1. In the table only integer values are applicable for DAC input. In this example we will consider 30° increments and calculate the values from degree to DAC input. We are assuming full-scale voltage of 10V for DAC output. We can follow this formula to get the voltage ranges.
Vout = 5V + (5 ×sinθ)
Let us see the lookup table according to the angle and other parameters for DAC.
Circuit Diagram −
#include<reg51.h>
sfr DAC = 0x80; //Port P0 address
void main(){
   int sin_value[12] = {128,192,238,255,238,192,128,64,17,0,17,64};
   int i;
   while(1){
      //infinite loop for LED blinking
      for(i = 0; i<12; i++){
         DAC = sin_value[i];
      }
   }
}
The output will look like this −
How can we limit the number of characters inside a JTextField in Java?

A JTextFeld is one of the most important components that allow the user to an input text value in a single line format. We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.
In the below example, we can implement the logic by using a PlainDocument class, hence we can allow a user to enter a maximum of 10 characters, it doesn't allow if we enter more than 10 characters.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
class JTextFieldLimit extends PlainDocument {
   private int limit;
   JTextFieldLimit(int limit) {
      super();
      this.limit = limit;
   }
   JTextFieldLimit(int limit, boolean upper) {
      super();
      this.limit = limit;
   }
   public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
      if (str == null)
         return;
      if ((getLength() + str.length()) <= limit) {
         super.insertString(offset, str, attr);
      }
   }
}
public class JTextFieldLimitTest extends JFrame {
   JTextField textfield;
   JLabel label;
   public static void main(String[]args){
      new JTextFieldLimitTest().GUI();
   }
   public void GUI() {
      setLayout(new FlowLayout());
      label = new JLabel("max 10 chars");
      textfield = new JTextField(15);
      add(label);
      add(textfield);
      textfield.setDocument(new JTextFieldLimit(10));
      setSize(350,300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
}
C/C++ Program for Largest Sum Contiguous Subarray?

An array of integers is given. We have to find sum of all elements which are contiguous. Whose sum is largest, that will be sent as output.
Using dynamic programming we will store the maximum sum up to current term. It will help to find sum for contiguous elements in the array.
Input: An array of integers. {-2, -3, 4, -1, -2, 1, 5, -3}
Output: Maximum Sum of the Subarray is : 7
Input − The main array, the size of the array.
Output − maximum sum.
Begin
   tempMax := array[0]
   currentMax = tempMax
   for i := 1 to n-1, do
      currentMax = maximum of (array[i] and currentMax+array[i])
      tempMax = maximum of (currentMax and tempMax)
   done
   return tempMax
End
 Live Demo
#include<iostream>
using namespace std;
int maxSum( int arr[], int n) {
   int tempMax = arr[0];
   int currentMax = tempMax;
   for (int i = 1; i < n; i++ ) { //find the max value
      currentMax = max(arr[i], currentMax+arr[i]);
      tempMax = max(tempMax, currentMax);
   }
   return tempMax;
}
int main() {
   int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
   int n = 8;
   cout << "Maximum Sum of the Sub-array is: "<< maxSum( arr, n );
}
Maximum Sum of the Sub-array is: 7
Get filename from string path in JavaScript?

We need to write a function that takes in a string file path and returns the filename. Filename
usually lives right at the very end of any path, although we can solve this problem using regex
but there exists a simpler one-line solution to it using the string split() method of JavaScript and
we will use the same here.
Let’s say our file path is −
"/app/base/controllers/filename.js
Following is the code to get file name from string path −
const filePath = "/app/base/controllers/filename.js";
const extractFilename = (path) => {
   const pathArray = path.split("/");
   const lastIndex = pathArray.length - 1;
   return pathArray[lastIndex];
};
console.log(extractFilename(filePath));
The console output for this code will be −
filename.js
Print newline in PHP in single quotes


Since \n can’t be used with single quotes, we need to resort to other options.
When using command line interface, the constant PHP_EOL can be used.
When using with browsers, the ‘<br>’ can be used.
Both the options have been demonstrated below.
<?php
if (PHP_SAPI === 'cli') {
   return PHP_EOL;
}
else
{
   return "<BR/>";
}
?>
Suppose our option was not cli, the ‘else’ part will be executed and a newline will be printed −
 Live Demo
<?php
   $var_1 = 'hi';
   $var_2 = "\n";
   $var_3 = 'hello';
   echo $var_1 . $var_2 . $var_3;
   echo PHP_EOL;
   $var_2 = str_replace("\n", '\n', $var_2);
   echo $var_1 . $var_2 . $var_3;
   echo PHP_EOL;
?>
This will produce the following output −
hi hello hi\nhello
Python Program for Find sum of odd factors of a number

In this article, we will learn about the solution to the problem statement given below −
Given a number input n, the task is to Find the sum of odd factors of a number.
Here we first need to eliminate all the even factors.
To remove all even factors, we repeatedly divide n till it is divisible by 2. After this step, we only get the odd factors of the number.
Below is the implementation −
 Live Demo
import math
def sumofoddFactors( n ):
   #prime factors
   res = 1
   # ignore even factors
   while n % 2 == 0:
      n = n // 2
   for i in range(3, int(math.sqrt(n) + 1)):
      count = 0
      curr_sum = 1
      curr_term = 1
      while n % i == 0:
         count+=1
         n = n // i
         curr_term *= i
         curr_sum += curr_term
      res *= curr_sum
   # n is a prime number.
   if n >= 2:
      res *= (1 + n)
      return res
# main
n = 27
print(sumofoddFactors(n))
41
All the variables are declared in the global frame as shown in the figure given below −
In this article, we learnt about the approach to Find sum of odd factors of a number
Go - functions as values

Go programming language provides the flexibility to create functions on the fly and use them as values. In the following example, we've initialized a variable with a function definition. Purpose of this function variable is just to use inbuilt math.sqrt() function. For example −
package main

import ("fmt" "math")

func main(){
   /* declare a function variable */
   getSquareRoot := func(x float64) float64 {
      return math.Sqrt(x)
   }

   /* use the function */
   fmt.Println(getSquareRoot(9))
}
When the above code is compiled and executed, it produces the following result −
3


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page