code-rag-bench/online-tutorials huggingface dataset:
How to set space between the flexbox ?

31 Oct, 2019
Flexible Box Module or Flexbox is a type of layout model. The main aim of this layout is to distribute space between items in a container. This layout is a one-dimensional layout model. The flexbox layout even works when the size of the items is unknown or dynamic.
To set space between the flexbox you can use the flexbox property justify-content you can also visit all the property in that link.
We can use the justify-content property of a flex container to set space between the flexbox.Syntax:
The value space-between is used for displaying flex items with space between the lines.justify-content: space-between;
justify-content: space-between;
The value space-around is used for displaying flex items with space between, before and after the lines.justify-content: space-around;
justify-content: space-around;
The below example will illustrate the property used for setting space between the flexbox.
Example:
<!DOCTYPE html> <html>     <head>         <title>Space between flexbox</title>         <style>             .flex2 {                 display: flex;                 justify-content: space-around;                 background-color: green;             }             .flex3 {                 display: flex;                 justify-content: space-between;                 background-color: green;             }             .flex-items {                 background-color: #f4f4f4;                 width: 100px;                 height:50px;                 margin: 10px;                 text-align: center;                 font-size: 40px;             }             h3 {                 text-align:center;             }             .geeks {                 font-size:40px;                 text-align:center;                 color:#009900;                 font-weight:bold;             }                             </style>     </head>       <body>         <div class = "geeks">GeeksforGeeks</div>         <h3>Space between flexbox</h3>            <br>         <b>justify-content: space-around </b>         <div class="flex2">             <div class="flex-items">1</div>             <div class="flex-items">2</div>             <div class="flex-items">3</div>         </div>         <br>         <b>justify-content: space-between </b>         <div class="flex3">             <div class="flex-items">1</div>             <div class="flex-items">2</div>             <div class="flex-items">3</div>         </div>         <br>           </body> </html>                                 
Output:
CSS-Misc
CSS-Properties
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js line.curve() method

19 Aug, 2020
The d3.line.curve() method is used to give a curve to our line. D3.js provides several curve factories that can be used to give different curves.
Syntax:
d3.line.curve(curve_factory);
Parameters:
curve_factory: type of curve to be given to the line.
Return Value: This method has no return value.
Example 1: In this example, we will use the curveBasis curve factory.
<!DOCTYPE html><html><meta charset="utf-8"><head>  <title>d3.line.curve()</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>  <body>    <h1 style="text-align: center;         color: green;">GeeksforGeeks</h1>  <center>    <svg id="gfg" width="200" height="200"></svg></center>  <script>var points = [  {xpoint: 25,  ypoint: 150},  {xpoint: 75,  ypoint: 85},  {xpoint: 100, ypoint: 115},  {xpoint: 175, ypoint: 25}];  var Gen = d3.line()  .x((p) => p.xpoint)  .y((p) => p.ypoint)  .curve(d3.curveBasis);    d3.select("#gfg")  .append("path")  .attr("d", Gen(points))  .attr("fill", "none")  .attr("stroke", "green");  </script></body></html>
Output:
Example 2: In this example, we will use the curveCardinal curve factory.
<!DOCTYPE html><html><meta charset="utf-8"><head>  <title>d3.line.curve()</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>  <body>    <h1 style="text-align: center;                color: green;">         GeeksforGeeks    </h1>  <center>    <svg id="gfg" width="200"          height="200">    </svg></center>  <script>var points = [  {xpoint: 25,  ypoint: 150},  {xpoint: 75,  ypoint: 85},  {xpoint: 100, ypoint: 115},  {xpoint: 175, ypoint: 25}];  var Gen = d3.line()  .x((p) => p.xpoint)  .y((p) => p.ypoint)  .curve(d3.curveCardinal);  d3.select("#gfg")  .append("path")  .attr("d", Gen(points))  .attr("fill", "none")  .attr("stroke", "green");  </script></body></html>
Output:
D3.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 - QDialog Class

A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed).
PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.
In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key.
A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar.
The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   btn = QPushButton(w)
   btn.setText("Hello World!")
   btn.move(100,50)
   btn.clicked.connect(showdialog)
   w.setWindowTitle("PyQt Dialog demo")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   dlg = QDialog()
   b1 = QPushButton("ok",dlg)
   b1.move(50,50)
   dlg.setWindowTitle("Dialog") 9. PyQt5 — QDialog Class
   dlg.setWindowModality(Qt.ApplicationModal)
   dlg.exec_()

if __name__ == '__main__':
   window()
The above code produces the following output. Click on button in main window and dialog box pops up −
Python | Pandas Dataframe/Series.dot()

19 Apr, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Dataframe.dot() works similarly like mul() method, but instead of returning multiplied separate values, Dot product is returned (Sum of multiplication of values at each index).
Syntax: Series.dot(other)Parameters:other: Other Series to be used to calculate DOT product
Return type: Series with updated values
Example #1:In this example, two series are created from Python lists using Pandas Series() method. Method is then called on series1 and series2 is passed as parameter. The result is then stored in a variable and displayed.
# importing pandas module  import pandas as pd      # importing numpy module import numpy as np     # creating series 1 series1 = pd.Series([7, 5, 6, 4, 9])     # creating series 2 series2 = pd.Series([1, 2, 3, 10, 2])   # storing in new variable# calling .dot() methodans = series1.dot(series2)  # displayprint('Dot product = {}'.format(ans))
Output:
Dot product = 93
Explanation –The elements in caller series are multiplied with the element at same index in passed series. All the multiplied values are then added to get the dot product.As in above example, the series are:
[7, 5, 6, 4, 9]
[1, 2, 3, 10, 2]

Dot product = 7*1 + 5*2 + 6*3 + 4*10 + 9*2 = 7 + 10 + 18 + 40 + 18 = 93
Note: If there is any Null value in any of the series, the net result is NaN. NaN values should be removed/replaced using dropna() or fillna() methods respectively.
Example #2 :
# import DataFrameimport pandas as pd  # using DataFrame.dot() methodgfg1 = pd.DataFrame([[1, 4], [9, 5]])gfg2 = pd.DataFrame([[4, 3, 2, 1], [21, -3, -4, 1]])  print(gfg1.dot(gfg2))
Output :
0 1 2 30 88 -9 -14 51 141 12 -2 14
Jitender_1998
Python pandas-dataFrame
Python pandas-series
Python-pandas
Python
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()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
<mat-slider> in Angular Material

01 Feb, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-slider> tag is used whenever there is a need for a slider in our projects.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatSliderModule’ from ‘@angular/material/slider’ in the app.module.ts file.
Then use the mat-slider tag to display the slider.
They are many properties in <mat-slider> which helps us in using it in different scenarios.
Some important properties are explained in below table.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
By default, the accent theme is set.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms';       import { AppComponent } from './app.component'; import { MatSliderModule } from '@angular/material/slider';   @NgModule({   imports:   [ BrowserModule,     FormsModule,     MatSliderModule],   declarations: [ AppComponent ],   bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.html:
HTML
<p>Default Accent Theme Slider</p><mat-slider></mat-slider><hr>  <p>Primary Theme Slider</p><mat-slider color="primary"></mat-slider><hr>  <p>Warn Theme Slider</p><mat-slider color="warn"></mat-slider><hr>  <p>Inverted Slider</p><mat-slider invert="true"></mat-slider><hr>  <p>Vertical Slider</p><mat-slider vertical="true"></mat-slider><hr>  <p>Disabled Slider</p><mat-slider disabled="true"></mat-slider><hr>
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unpacking a Tuple in Python

24 Jun, 2021
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program.
Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.
Example 1 
Python3
# Program to understand about# packing and unpacking in Python # this lines PACKS values# into variable aa = ("MNNIT Allahabad", 5000, "Engineering")  # this lines UNPACKS values# of variable a(college, student, type_ofcollege) = a  # print college nameprint(college) # print no of studentprint(student) # print type of collegeprint(type_ofcollege)
MNNIT Allahabad
5000
Engineering
 
NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of values in given tuple a.Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .For better understanding consider the following code. 
Example 2 
Python3
# Python3 code to study about# unpacking python tuple using * # first and last will be assigned to x and z# remaining will be assigned to yx, *y, z = (10, "Geeks ", " for ", "Geeks ", 50) # print detailsprint(x)print(y)print(z) # first and second will be assigned to x and y# remaining will be assigned to zx, y, *z = (10, "Geeks ", " for ", "Geeks ", 50)print(x)print(y)print(z)
10
['Geeks ', ' for ', 'Geeks ']
50
10
Geeks 
[' for ', 'Geeks ', 50]
 
In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable. Consider the following code for better understanding. 
Example 3 : 
Python3
# Python3 code to study about# unpacking python tuple using function # function takes normal arguments# and multiply themdef result(x, y):    return x * y# function with normal variablesprint (result(10, 100)) # A tuple is createdz = (10, 100) # Tuple is passed# function unpacked them print (result(*z))
1000
1000
 
ashutosh_kar
sumitgumber28
python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Turing Machine for addition

01 Jun, 2022
Prerequisite – Turing Machine A number is represented in binary format in different finite automata. For example, 5 is represented as 101. However, in the case of addition using a Turing machine, unary format is followed. In unary format, a number is represented by either all ones or all zeroes. For example, 5 will be represented by a sequence of five zeroes or five ones: 5 = 1 1 1 1 1 or 5 = 0 0 0 0 0. Lets use zeroes for representation. 
For adding 2 numbers using a Turing machine, both these numbers are given as input to the Turing machine separated by a “c”. 
Examples – (2 + 3) will be given as 0 0 c 0 0 0:  
Input  :  0 0 c 0 0 0    // 2 + 3
Output :  0 0 0 0 0      // 5

Input  :  0 0 0 0 c 0 0 0  // 4 + 3
Output :  0 0 0 0 0 0 0    // 7
Approach used – Convert a 0 in the first number in to X and then traverse entire input and convert the first blank encountered into 0. Then move towards left ignoring all 0’s and “c”. Come the position just next to X, and repeat the same procedure until the time we get a “c” instead of X on returning. Convert the c into blank and addition is completed. 
Steps – 
Step-1: Convert 0 into X and go to step 2. If symbol is “c” then convert it into blank(B), move right and go to step 6. 
Step-2: Keep ignoring 0’s and move towards right. Ignore “c”, move right and go to step 3. 
Step-3: Keep ignoring 0’s and move towards right. Convert a blank (B) into 0, move left and go to step 4. 
Step-4: Keep ignoring 0’s and move towards left. Ignore “c”, move left and go to step 3. 
Step-5: Keep ignoring 0’s and move towards left. Ignore an X, move right and go to step 1. 
Step-6: End. 
 
 
Akanksha_Rai
singhutkarsh2799
miamactavish
surinderdawra388
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Normal Forms in DBMS
Difference between DFA and NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Design 101 sequence detector (Mealy machine)
Post Correspondence Problem
How to retrieve source code from Python objects?

29 Aug, 2020
It is sometimes important to know what some functions source codes look like. In such cases, we have inspect module a built-in standard library in Python programming. It provides several useful functions to track information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. getsource() method is used to get the source code of Python objects.
Syntax: inspect.getsource(object)
Return type: text of the source code for an object
An IOError is raised if the source code cannot be retrieved.
Example:
# import inspect libraryimport inspect  def test(x):    return x * 2  print(inspect.getsource(test))
Output:
def test(x):

   return (x+2)*(x-2)

Example:
# import inspect libraryimport inspect    def far(n):    factorial = 1    if int(n) >= 1:        for i in range (1, int(n)+1):            factorial = factorial * i    return factorial  source = inspect.getsource(far)print(source)
Output:
def far(n):
    factorial = 1
    if int(n) >= 1:
        for i in range (1, int(n)+1):
            factorial = factorial * i
    return factorial

Example: We can use inspect on built in library functions and objects also.
# import inspect libraryimport inspectimport pandas    source_DF = inspect.getsource(pandas.DataFrame)print(source_DF[:100])
Output:
class DataFrame(NDFrame):
    """
    Two-dimensional size-mutable, potentially heterogeneous tabula

python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
3D Sine Wave Using Matplotlib - Python - GeeksforGeeks

03 Jan, 2021
Prerequisites: Mathplotlib, NumPy
In the Cartesian coordinate system, the trigonometric sine function sin(x) sin (x) generates a regular undulating curve, which passes through the origin. Its values range between −1 − 1 and 1 1 for all real values of x x.In this article, we will plot a sin wave graph using scatter in 3-Dimension. A simple way to plot sine wave in python using matplotlib.
Approach: 
Import required libraries.
Create an array of points.
Plotting 3D-graph.
Create a sin wave.
Show Graph.
Example 1: In this example, we are plotting a 3-d graph of the sine wave signal using the scatter method.
Python3
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D  # Creating array points using numpyx = np.arange(0, 20, 0.1)y = np.sin(x)z = y*np.sin(x)c = x + y  #Change the Size of Graph using Figsizefig = plt.figure(figsize = (10, 10))  #Generating a 3D sine waveax = plt.axes(projection = '3d')  # To create a scatter graphax.scatter(x, y, z, c = c)  # show the graph plt.show()
Output:
Example 2: In this example, we are plotting a simple 3-D line graph of the sine wave signal. 
Python3
from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt  fig = plt.figure(figsize=(8, 8))ax = plt.axes(projection = '3d')  # Creating array points using numpyz = np.linspace(0, 15, 1000)x = np.sin(zline)y = np.cos(zline)ax.plot3D(x, y, z, 'gray')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Groovy - subList()

Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive
List subList(int fromIndex, int toIndex)

fromIndex – Starting index of the range
toIndex – End Index of the range
The list of range values from specified starting to ending index.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def rint = 1..10; 
		
      println(rint.subList(1,4)); 
      println(rint.subList(4,8)); 
   } 
}
When we run the above program, we will get the following result −
[2, 3, 4] 
[5, 6, 7, 8] 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
C Program for Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks

22 Aug, 2019
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example:
Example 1 : Consider the following 3 activities sorted by finish time.
     start[]  =  {10, 12, 20};
     finish[] =  {20, 25, 30};
A person can perform at most two activities. The 
maximum set of activities that can be executed 
is {0, 2} [ These are indexes in start[] and 
finish[] ]

Example 2 : Consider the following 6 activities 
sorted by by finish time.
     start[]  =  {1, 3, 0, 5, 8, 5};
     finish[] =  {2, 4, 6, 7, 9, 9};
A person can perform at most four activities. The 
maximum set of activities that can be executed 
is {0, 1, 3, 4} [ These are indexes in start[] and 
finish[] ]

C++
// C++ program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include <stdio.h>  // Prints a maximum set of activities that can be done by a single// person, one at a time.// n   -->  Total number of activities// s[] -->  An array that contains start time of all activities// f[] -->  An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){    int i, j;      printf("Following activities are selected n");      // The first activity always gets selected    i = 0;    printf("%d ", i);      // Consider rest of the activities    for (j = 1; j < n; j++) {        // If this activity has start time greater than or        // equal to the finish time of previously selected        // activity, then select it        if (s[j] >= f[i]) {            printf("%d ", j);            i = j;        }    }}  // driver program to test above functionint main(){    int s[] = { 1, 3, 0, 5, 8, 5 };    int f[] = { 2, 4, 6, 7, 9, 9 };    int n = sizeof(s) / sizeof(s[0]);    printMaxActivities(s, f, n);    return 0;}
Following activities are selected n0 1 3 4

Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!
nidhi_biet
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Producer Consumer Problem in C
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Lex program to implement a simple Calculator
How to return a Pointer from a Function in C
Implementing upper_bound() and lower_bound() in C
Lamport's logical clock
C Hello World Program
How to add items to an array in java dynamically?

Since the size of an array is fixed you cannot add elements to it dynamically. But, if you still want to do it then,
Convert the array to ArrayList object.
Add the required element to the array list.
Convert the Array list to array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class AddingItemsDynamically {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array :: ");
      int size = sc.nextInt();
      String myArray[] = new String[size];
      System.out.println("Enter elements of the array (Strings) :: ");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.next();
      }
      System.out.println(Arrays.toString(myArray));
      ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
      System.out.println("Enter the element that is to be added:");
      String element = sc.next();
      myList.add(element);
      myArray = myList.toArray(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
Enter the size of the array ::
3
Enter elements of the array (Strings) ::
Ram
Rahim
Robert
[Ram, Rahim, Robert]
Enter the element that is to be added:
Mahavir
[Ram, Rahim, Robert, Mahavir]
How to standardize data.table object column by group in R?

To standardize data.table object column by group, we can use scale function and provide
the grouping column with by function.
For Example, if we have a data.table object called DT that contains two columns say G
and Num where G is a grouping column and Num is a numerical column then we can
standardize Num by column G by using the below given command −
DT[,"Num":=as.vector(scale(Num)),by=G]
Consider the below data.table object −
library(data.table)
Grp<-sample(c("Male","Female"),20,replace=TRUE)
Response<-round(rnorm(20,5,1.25),2)
DT1<-data.table(Grp,Response)
DT1
The following dataframe is created
       Grp Response
 1: Female 5.31
 2: Male   5.20
 3: Female 6.38
 4: Male   4.53
 5: Female 4.90
 6: Female 4.78
 7: Male   3.73
 8: Female 6.19
 9: Male   4.33
10: Male   7.84
11: Male   6.70
12: Female 5.11
13: Male   6.80
14: Male   3.76
15: Male   3.56
16: Male   5.51
17: Female 6.58
18: Female 7.59
19: Male   4.62
20: Female 6.75
To standardize Response column by Grp column in DT1 on the above created data
frame, add the following code to the above snippet −
library(data.table)
Grp<-sample(c("Male","Female"),20,replace=TRUE)
Response<-round(rnorm(20,5,1.25),2)
DT1<-data.table(Grp,Response)
DT1[,"Response":=as.vector(scale(Response)),by=Grp]
DT1
If you execute all the above given snippets as a single program, it generates the following Output −
     Grp    Response
 1: Female -0.66313371
 2: Male    0.03955265
 3: Female  0.43789692
 4: Male   -0.43061348
 5: Female -1.08502396
 6: Female -1.20850403
 7: Male   -0.99200587
 8: Female  0.24238681
 9: Male   -0.57096158
10: Male    1.89214752
11: Male    1.09216337
12: Female -0.86893383
13: Male    1.16233742
14: Male   -0.97095365
15: Male   -1.11130175
16: Male    0.25709220
17: Female  0.64369704
18: Female  1.68298763
19: Male   -0.36745684
20: Female  0.81862714
Following snippet creates a sample data frame −
Class<-sample(c("I","II","III"),20,replace=TRUE)
Rate<-round(rnorm(20,10,1.02),0)
DT2<-data.table(Class,Rate)
DT2

The following dataframe is created
  Class Rate
 1: II  10
 2: III  9
 3: II  10
 4: II  10
 5: III 10
 6: III  9
 7: III  8
 8: II  10
 9: II  11
10: III  9
11: I    9
12: II  11
13: III 13
14: II  10
15: III 12
16: I    8
17: II   9
18: I   10
19: III  9
20: II  10
To standardize Rate column by Class column in DT2 on the above created data frame,
add the following code to the above snippet −
Class<-sample(c("I","II","III"),20,replace=TRUE)
Rate<-round(rnorm(20,10,1.02),0)
DT2<-data.table(Class,Rate)
DT2[,"Rate":=as.vector(scale(Rate)),by=Class]
DT2
If you execute all the above given snippets as a single program, it generates the
following Output −
   Class     Rate
 1: II  -0.18490007
 2: III -0.50669175
 3: II  -0.18490007
 4: II  -0.18490007
 5: III  0.07238454
 6: III -0.50669175
 7: III -1.08576803
 8: II  -0.18490007
 9: II   1.47920052
10: III -0.50669175
11: I    0.00000000
12: II   1.47920052
13: III  1.80961338
14: II  -0.18490007
15: III  1.23053710
16: I   -1.00000000
17: II  -1.84900065
18: I    1.00000000
19: III -0.50669175
20: II  -0.18490007
Appending a key value pair to an array of dictionary based on a condition in JavaScript?

For this, use Object.assign(). Following is the code −
const details =
{john:{'studentName':'John'},david:{'studentName':'David'},mike:{'studen
tName':'Mike'},bob:{'studentName':'Bob'},carol:{'studentName':'Carol'}},
join_values = ['David', 'Carol'],
   output = Object.assign(
      {},
      ...Object
      .keys(details)
      .map(key =>
      ({[key]: {
         ...details[key],
         lastName: join_values.includes(details[key].studentName) ?
         'Miller' : 'Smith'
   }})))
console.log(output)
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo157.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo157.js
{
   john: { studentName: 'John', lastName: 'Smith' },
   david: { studentName: 'David', lastName: 'Miller' },
   mike: { studentName: 'Mike', lastName: 'Smith' },
   bob: { studentName: 'Bob', lastName: 'Smith' },
   carol: { studentName: 'Carol', lastName: 'Miller' }
}
How to create a simple "star rating" look with CSS?

To create a simple star rating look with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<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;
      margin: 30px;
   }
   .fa {
      font-size: 30px;
      color: grey;
   }
   .rated {
      color: rgb(255, 0, 0);
      border: 2px solid yellow;
   }
</style>
</head>
<body>
<h1>Star Rating Example</h1>
<span class="fa fa-star rated"></span>
<span class="fa fa-star rated"></span>
<span class="fa fa-star rated"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</body>
</html>
The above code will produce the following output −
How to subtract Python timedelta from date in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date. 
from datetime import datetime
from datetime import timedelta
today = datetime.today()
yesterday = today - timedelta(days=1)
print(today)
print()
print(yesterday)
This will give the output −
2017-12-29 12:28:06.531791
2017-12-28 12:28:06.531791
You can also subtract years, months, hours, etc. in the same way from a date using the timedelta object.
C library function - remove()

The C library function int remove(const char *filename) deletes the given filename so that it is no longer accessible.
Following is the declaration for remove() function.
int remove(const char *filename)
filename − This is the C string containing the name of the file to be deleted.
filename − This is the C string containing the name of the file to be deleted.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
The following example shows the usage of remove() function.
#include <stdio.h>
#include <string.h>

int main () {
   int ret;
   FILE *fp;
   char filename[] = "file.txt";

   fp = fopen(filename, "w");

   fprintf(fp, "%s", "This is tutorialspoint.com");
   fclose(fp);
   
   ret = remove(filename);

   if(ret == 0) {
      printf("File deleted successfully");
   } else {
      printf("Error: unable to delete the file");
   }
   
   return(0);
}
Let us assume we have a text file file.txt having some content. So we are going to delete this file, using the above program. Let us compile and run the above program to produce the following message and the file will be deleted permanently.
File deleted successfully


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Fibonacci Recursive Program in C

#include <stdio.h>

int factorial(int n) {
   //base case
   if(n == 0) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}

int fibbonacci(int n) {
   if(n == 0){
      return 0;
   } else if(n == 1) {
      return 1;
   } else {
      return (fibbonacci(n-1) + fibbonacci(n-2));
   }
}

int main() {
   int n = 5;
   int i;
	
   printf("Factorial of %d: %d\n" , n , factorial(n));
   printf("Fibbonacci of %d: " , n);
	
   for(i = 0;i<n;i++) {
      printf("%d ",fibbonacci(i));            
   }
}
If we compile and run the above program, it will produce the following result −
Factorial of 5: 120
Fibbonacci of 5: 0 1 1 2 3


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to count the number of duplicate rows in an R data frame?

To count the number of duplicate rows in an R data frame, we would first need to convert the data frame into a data.table object by using setDT and then count the duplicates with Count function. For example, if we have a data frame called df then the duplicate rows will be counted by using the command − setDT(df)[,list(Count=.N),names(df)].
 Live Demo
Consider the below data frame −
x1<−rpois(20,2)
x2<−rpois(20,2)
df1<−data.frame(x1,x2)
df1
x1 x2
1 4 3
2 3 3
3 3 0
4 3 0
5 2 0
6 2 0
7 0 4
8 1 1
9 4 3
10 0 1
11 3 2
12 5 3
13 1 1
14 3 2
15 1 3
16 2 2
17 3 1
18 1 1
19 5 1
20 3 1
Loading data.table object −
library(data.table)
Finding the duplicate rows −
setDT(df1)[,list(Count=.N),names(df1)]
  x1 x2 Count
1:  4  3 2
2:  3  3 1
3:  3  0 2
4:  2  0 2
5:  0  4 1
6:  1  1 3
7:  0  1 1
8:  3  2 2
9:  5  3 1
10: 1  3 1
11: 2  2 1
12: 3  1 2
13: 5  1 1
 Live Demo
y1<−sample(0:2,20,replace=TRUE)
y2<−sample(0:2,20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 2 1
2 2 2
3 0 0
4 2 2
5 0 2
6 2 2
7 1 0
8 0 2
9 1 0
10 2 1
11 1 2
12 0 2
13 1 0
14 0 0
15 2 1
16 1 1
17 0 0
18 0 1
19 2 1
20 2 0
Finding the duplicate rows −
setDT(df2)[,list(Count=.N),names(df2)]
y1 y2 Count
1: 2 1 4
2: 2 2 3
3: 0 0 3
4: 0 2 3
5: 1 0 3
6: 1 2 1
7: 1 1 1
8: 0 1 1
9: 2 0 1
Bootstrap success Contextual class

The Bootstrap success contextual class indicates a successful or positive action.
You can try to run the following code to implement the .success class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</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>
      <table class = "table">
         <thead>
            <tr>
               <th>Subject</th>
               <th>Marks</th>
               <th>Student</th>
            </tr>
          </thead>
          <tbody>
             <tr class = "success">
                <td>Maths</td>
                <td>90</td>
                <td>Amit</td>
             </tr>
             <tr class = "active">
                <td>Science</td>
                <td>80</td>
                <td>Aman</td>
             </tr>
             <tr>
                <td>English</td>
                <td>85</td>
                <td>Rahul</td>
             </tr>
          </tbody>
      </table>
   </body>
</html>
How to plot int to datetime on X-axis using Seaborn?

To plot int to datetime on X-axis using Seaborn in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data, with three columns.
Create a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data, with three columns.
Create a countplot with int, i.e., dob on the X-axis.
Create a countplot with int, i.e., dob on the X-axis.
Set int to datetime label on the X-axis.
Set int to datetime label on the X-axis.
To display the figure, use Show() method.
To display the figure, use Show() method.
import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Data frame with 3 columns
df = pd.DataFrame([
    [23, 'James', 1259969793926],
    [39, 'Jimmy', 1259969793927],
    [56, 'Jack', 1259969793929],
    [60, 'Tom', 1259969793928],
    [80, 'Tim', 1259969793939]
], columns=['marks', 'names', 'dob'])

# Create a Countplot with df
ax = sns.countplot(x="dob", data=df)

ax.set_xticklabels(
    [
        pd.to_datetime(tm, unit='ms').strftime('%Y-%m-%d %H:%M:%S')
        for tm in ax.get_xticks()
    ], rotation=45)

# Display the plot
plt.show()
It will produce the following output −
Find depth of a dictionary in Python

A python dictionary can be nested i.e., there are dictionaries within a dictionary. In this article we will see how to calculated the level of nesting in a dictionary when there is a nested dictionary.
In this approach we convert the entire dictionary into a string. Then we count the number of left { that indicate to which level the dictionaries are nested.
 Live Demo
dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
dictStr = str(dictA)
cnt = 0
for i in dictStr :
   if i == "{":
      cnt += 1
print("The depth of dictionary: ",cnt)
Running the above code gives us the following result −
The depth of dictionary: 3
We can design a function that will recursively call itself to check the values of the dictionary. As long as the inner element is evaluated to be a dictionary, the function will call itself and we will get the result for the depth of the dictionary.
 Live Demo
def finddepth(dictA):
   if isinstance(dictA, dict):
      return 1 + (max(map(finddepth, dictA.values()))
         if dictA else 0)

   return 0

dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
print("The depth of dictionary: ",finddepth(dictA))
Running the above code gives us the following result −
The depth of dictionary: 3
GATE | GATE-CS-2003 | Question 56 - GeeksforGeeks

12 Sep, 2019
Consider the grammar shown below
S → i E t S S' | a
S' → e S | ε
E → b 
In the predictive parse table. M, of this grammar, the entries M[S’, e] and M[S’, $] respectively are(A) {S’ → e S} and {S’ → e}(B) {S’ → e S} and {}(C) {S’ → ε} and {S’ → ε}(D) {S’ → e S, S’→ ε} and {S’ → ε}Answer: (D)Explanation: Here representing the parsing table as M[ X , Y ], where X represents rows( Non terminals) and Y represents columns(terminals).
Here are the rules to fill the parsing table.
For each distinct production rule A->α, of the grammar, we need to apply the given rules:
Rule 1: if A –> α is a production, for each terminal ‘a’ in FIRST(α), add A–>α to M[ A , a ]
Rule 2 : if ‘ ε ‘ is in FIRST(α), add A –> α to M [ A , b ] for each ‘b’ in FOLLOW(A).
As Entries have been asked corresponding to Non-Terminal S’, hence we only need to consider its productions to get the answer.
For S’ → eS, according to rule 1, this production rule should be placed at the entry M[ S’, FIRST(eS) ], and from the given grammar, FIRST(eS) ={e}, hence S’->eS is placed in the parsing table at entry M[S’ , e].
Similarly,
For S’->ε, as FIRST(ε) = {ε}, hence rule 2 should be applied, therefore, this production rule should be placed in the parsing table at entry M[S’,FOLLOW(S’)], and FOLLOW(S’) = FOLLOW(S) = { e, $ }, hence R->ε is placed at entry M[ S’, e ] and M[ S’ , $ ].
Therefore Answer is option D.
Visit the Following links to Learn how to find First and Follow sets.
http://geeksquiz.com/compiler-design-first-in-syntax-analysis/http://geeksquiz.com/compiler-design-follow-set-in-syntax-analysis/Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
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 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
New 21 Game in C++

Suppose Rima plays the following game, that is loosely based on the card game "21". So Rima starts with 0 points, and draws numbers while she has less than K points. Now, during each draw, she gains an integer number of points randomly from the range [1, W], where W is given, and that is an integer. Now each draw is independent and the outcomes have equal probabilities. Rima stops drawing numbers when she gets K or more points. We have to find the probability that she has N or less points?
So if N = 6, K is 1 and W is 10, then the answer will be 0.6, as Rima gets a single card, then stops, In 6 out of 10 probabilities, She is at or below N = 6 points.
To solve this, we will follow these steps −
If k is 0, or N >= K + W, then return 1
make an array dp of size N + 1, set dp[0] := 1
set wsum := 1.0, ret := 0.0
for i in range 1 to Ndp[i] := wsum / Wif i < K, then wsum := wsum + dp[i], otherwise ret := ret + dp[i]if i – W >= 0, then wsum := wsum – dp[i - W]
dp[i] := wsum / W
if i < K, then wsum := wsum + dp[i], otherwise ret := ret + dp[i]
if i – W >= 0, then wsum := wsum – dp[i - W]
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   double new21Game(int N, int K, int W) {
      if(K == 0 || N >= K + W) return 1.0;
      vector <double> dp (N + 1);
      dp[0] = 1;
      double Wsum = 1.0;
      double ret = 0.0;
      for(int i = 1; i <= N; i++){
         dp[i] = Wsum / W;
         if(i < K){
            Wsum += dp[i];
         }else ret += dp[i];
         if(i - W >= 0) Wsum -= dp[i - W];
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.new21Game(6, 1, 10));
}
6
1
10
0.6
HTML <label> for Attribute

The for attribute of the <label> element is used to set an element with a label.
Following is the syntax −
<label for="id">
Above, id is the associated element id.
Let us now see an example to implement the for attribute of <label> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Last Semester Results</h2>
<form>
<fieldset>
<legend>Result</legend>
<label for="stinfo">Student:</label>
<input type="text" id ="stinfo" value="Jack"><br>
<label for="sub">Subject:</label>
<input type="text" value="Maths"><br>
<label for="rank">Rank:</label>
<input type="number" value="8"><br>
</fieldset>
</form>
</body>
</html>
This will produce the following output −
In the above example, we have a form with some fields −
<form>
<fieldset>
<legend>Result</legend>
<label for="stinfo">Student:</label>
<input type="text" id ="stinfo" value="Jack"><br>
<label for="sub">Subject:</label>
<input type="text" value="Maths"><br>
<label for="rank">Rank:</label>
<input type="number" value="8"><br>
</fieldset>
</form>
We have set the label for the field using for attribute of the <label> element, for example −
<label for="stinfo">Student:</label>
<input type="text" id ="stinfo" value="Jack"><br>
Now the input type text with is stinfo will have the label “Student” since we have set it with label for −
<label for="stinfo">Student:</label>
How to decode an encoded string in JavaScript?

In JavaScript, to decode a string unescape() method is used. This method takes a string, which is encoded by escape() method, and decodes it. The hexadecimal characters in a string will be replaced by the actual characters they represent using unescape() method.
unescape(string)
In the following the two exclamation marks have converted to hexadecimal characters using escape() method. Later on those marks were decoded in to their natural characters using unescape() method. 
Live Demo
<html>
<body>
<script type="text/javascript">
   // Special character encoded with escape function
   var str = escape("Tutorialspoint!!");
   document.write("</br>");
   document.write("Encoded : " + str);
   // unescape() function
   document.write("Decoded : " + unescape(str))
</script>
</body>
</html>
Encoded : Tutorialspoint%21%21
Decoded : Tutorialspoint!!
There is an exception that the characters .(dot) and @ wont convert in to hexadecimal characters. For instance, in the following code when escape() method is used all the characters have converted to hexadecimal except .(dot) and @.
Live Demo
<html>
<body>
<script type="text/javascript">
   str = escape("My gmail address is robbinhood@rocketmail.com")
   document.write("Encoded : " + str);
   document.write("</br>");
   // unescape() function
   document.write("Decoded : " + unescape(str))
</script>
</body>
</html>
Encoded : My%20gmail%20address%20is%20robbinhood@rocketmail.com
Decoded : My gmail address is robbinhood@rocketmail.com
Find the sublist with maximum value in given nested list in Python

A list can contain other list as its elements. In this article we are equal to find the sublist with maximum value which are present in a given list.
The max and the Lambda function can together be used to give that sublist which has the maximum value.
 Live Demo
listA = [['Mon', 90], ['Tue', 32], ['Wed', 120]]
# Using lambda
res = max(listA, key=lambda x: x[1])
# printing output
print("Given List:\n", listA)
print("List with maximum value:\n ", res)
Running the above code gives us the following result −
Given List:
[['Mon', 90], ['Tue', 32], ['Wed', 120]]
List with maximum value:
['Wed', 120]
We use itemgetter from index position 1 and apply a max function to get the sublist with maximum value.
 Live Demo
import operator
listA = [['Mon', 90], ['Tue', 32], ['Wed', 120]]
# Using itemgetter
res = max(listA, key = operator.itemgetter(1))
# printing output
print("Given List:\n", listA)
print("List with maximum value:\n ", res)
Running the above code gives us the following result −
Given List:
[['Mon', 90], ['Tue', 32], ['Wed', 120]]
List with maximum value:
['Wed', 120]
C Program to Add two Integers

A program to add two numbers takes to numbers and does their mathematical sum and
gives it to another variable that stores its sum.
 Live Demo
#include <stdio.h>
int main(void) {
   int a = 545;
   int b = 123;
   printf("The first number is %d and the second number is %d \n", a , b);
   int sum = a + b;
   printf("The sum of two numbers is %d" , sum);
   return 0;
}
The first number is 545 and the second number is 123
The sum of two numbers is 668
How to create a vertical toolbar in Java?

Let us first create a toolbar −
JToolBar toolbar = new JToolBar();
Now, set the orientation to create vertical toolbar −
toolbar.setOrientation(SwingConstants.VERTICAL);
The following is an example to create a vertical toolbar in Java −
package my;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JToolBar toolbar = new JToolBar();
      toolbar.setOrientation(SwingConstants.VERTICAL);
      toolbar.add(new JTextArea());
      toolbar.add(new JButton("Submit"));
      frame.add(toolbar,BorderLayout.WEST);
      frame.setTitle("Vertical ToolBar");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //frame.setLocationByPlatform(true);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}