code-rag-bench/online-tutorials huggingface dataset:
Changing Column in MySQL from int to double?

To change the column in MySQL from int to double you need to use ALTER TABLE command.
The syntax is as follows:
ALTER TABLE yourTableName modify column yourColumnName DOUBLE NOT NULL;
If you want NULL value then remove NOT NULL from the above syntax. The syntax is as follows:
ALTER TABLE yourTableName modify column yourColumnName DOUBLE;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table IntToDoubleDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> CylinderVolume int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.63 sec)
Check the description of the table using DESC command. The syntax is as follows:
DESC yourTableName;
Apply the above query for your table to get the description of the table:
mysql> desc IntToDoubleDemo;
The following is the output:
+----------------+-------------+------+-----+---------+----------------+
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| Id             | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name           | varchar(10) | YES  |     | NULL    |                |
| CylinderVolume | int(11)     | YES  |     | NULL    |                |
+----------------+-------------+------+-----+---------+----------------+
3 rows in set (0.18 sec)
Look at the above sample output, the field ‘CylinderVolume’ is a type of int. Now you can convert from int to double.
Change the column in MySQL from int to double. The query is as follows:
mysql> alter table IntToDoubleDemo MODIFY COLUMN CylinderVolume double NOT NULL;
Query OK, 0 rows affected (2.79 sec)
Records: 0 Duplicates: 0 Warnings: 0
Once again check the description of the table. The query is as follows:
mysql> desc IntToDoubleDemo\G
The following is the output:
*************************** 1. row ***************************
Field: Id
Type: int(11)
Null: NO
Key: PRI
Default: NULL
Extra: auto_increment
*************************** 2. row ***************************
Field: Name
Type: varchar(10)
Null: YES
Key:
Default: NULL
Extra:
*************************** 3. row ***************************
Field: CylinderVolume
Type: double
Null: NO
Key:
Default: NULL
Extra:
3 rows in set (0.00 sec)
How to remove gaps between bars in Matplotlib bar chart?

To remove gaps between bars, we can change the align value to center in the argument of bar() method.
Create a dictionary called data with two keys, milk and water.
Create a dictionary called data with two keys, milk and water.
Get the list of keys and values in the dictionay.
Get the list of keys and values in the dictionay.
Using subplots() method, create a figure and add a set of two subplots.
Using subplots() method, create a figure and add a set of two subplots.
On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method.
On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method.
Use tight_layout() to adjust the padding between and around the subplots.
Use tight_layout() to adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = {'milk': 12, 'water': 10}
names = list(data.keys())
values = list(data.values())
fif, (ax1, ax2) = plt.subplots(2)
ax1.bar(range(len(data)), values, align='center', width=.05, color='yellow')
ax1.set_title("with gap")
ax2.bar(range(len(data)), values, align='edge', width=1.0, color='yellow')
ax2.set_title("without gap")
plt.tight_layout()
plt.show()
How to remove an element from an array in Java

Following example shows how to remove an element from array. 
import java.util.ArrayList; public class Main {
   public static void main(String[] args) {
      ArrayList objArray = new ArrayList();
      objArray.clear();
      objArray.add(0,"0th element");
      objArray.add(1,"1st element");
      objArray.add(2,"2nd element");
      System.out.println("Array before removing an element"+objArray);
      objArray.remove(1);
      objArray.remove("0th element");
      System.out.println("Array after removing an element"+objArray);
   }
}
The above code sample will produce the following result. 
Array before removing an element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]
ASIN(), ACOS() and ATAN() Function in MariaDB - GeeksforGeeks

01 Oct, 2020
1. ASIN Function :In MariaDB, the ASIN function is used for finding arc sine of a number. In this function, a number will be passed as a parameter and this function will return the arcsine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output.
Syntax :
ASIN(number)
Parameter : Required. A numeric value.number : A number used to calculate the arcsine. The range of number must in the range -1 to 1.
Example-1 :
SELECT ASIN(1);
Output :
1.5707963267948966
Example-2 :
SELECT ASIN(2.3);
Output :
NULL
Example-3 :
SELECT ASIN(0.41);
Output :
0.42245406218675574
2. ACOS Function :In MariaDB, the ACOS function is used for finding arc cosine of a number. In this function, a number will be passed as a parameter and this function will return the arc cosine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output.
Syntax :
ACOS(number)
Parameter : Required. A numeric value.number : A number used to calculate the arc cosine. The range of number must in the range -1 to 1.
Example-1 :
SELECT ACOS(-0.6);
Output :
2.214297435588181
Example-2 :
SELECT ACOS(1);
Output :
0
Example-3 :
SELECT ACOS(1.9);
Output :
NULL
3. ATAN Function :In MariaDB, the ATAN function is used for finding arc tangent of a number or arc tangent of n and m. In this function, a number will be passed as a parameter or n and m will be passed for the second type of syntax. this function will return the arc tangent of that number. When the second type of syntax is used then the sign of m, n is used for deciding the quadrant for the result.
Syntax-1 :
ATAN(number)
Parameter : Required. A numeric value.number : A number used to calculate the arc tangent.
Syntax-2 :
ATAN(n, m)
Parameters : Required. Two numeric values.n, m : Two values used to calculate the arc tangent.
Example-1 :
SELECT ATAN(-1.4);
Output :
-0.9505468408120751
Example-2 :
SELECT ATAN(1, 3);
Output :
0.3217505543966422
Example-3 :
SELECT ATAN(0.6);
Output :
0.5404195002705842
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
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
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?
MySQL | Group_CONCAT() Function
Using styled API in ReactJS - GeeksforGeeks

28 Dec, 2020
Styled components in ReactJS is a CSS-in-JS library that can be used for a better UI design. This API allows us to create a styled component and apply all styling properties. For using Styled API in React we need to install styled components.
Prerequisites:
Basics of ReactJS
Already created ReactJS app
Step 1: Before moving further, firstly we have to install the styled component, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.
npm install --save styled-components
Step 2: After installing the modules, now open your App.js file which is present inside your project’s directory, under src folder.
Step 3: Now import React and styled modules.
Step 4: In your App.js file, add this code snippet to import React and styled modules.
import React from 'react';
import styled from 'styled-components';
Below is a sample program to illustrate the use of styled-components:
Example 1: Changing the background color of the button to green.
App.js:
Javascript
import React from 'react';  // Importing styled from styled-componentsimport styled from 'styled-components';  // Importing the background-color of your // choice to the button using css// Button component that will render an <a> // tag with some styles using styled.const Button = styled.a`  background-color:green;  color: white;  padding: 1rem 2rem;  margin-top:100px;  width: 150px;  display: block;`const App = () => {  return (    <center><Button>GeeksforGeeks</Button></center>  )}  export default App;
Output:
Example 2: Adding a border to the button.
App.js:
Javascript
import React from 'react';  // Importing styled from styled componentsimport styled from 'styled-components';  // Importing the background-color of your // choice to the button using css// Button component that will render an <a>// tag with some styles using styled.const Button = styled.a`  background-color:green;  color: white;  padding: 1rem 2rem;  margin-top:100px;  width: 150px;  display: block;  border:8px solid black;`const App = () => {  return (    <center><Button>GeeksforGeeks</Button></center>  )}  export default App;
Output:
Hence, using the above-mentioned steps, we can use the Styled-components to import and change the style of components in React. 
react-js
Technical Scripter 2020
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
Style Rules in CSS

CSS comprises of style rules interpreted by the browser and then applied to the corresponding elements in your document. A style rule is made of three parts −
Selector -  A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc.
Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc.
Value - Values assigned to properties. For example, the color property can have value either red or #F1F1F1 etc
You can put CSS Style Rule Syntax as follows:
selector { property: value }
Convert a string to uppercase in Julia - uppercase() and uppercasefirst() Methods - GeeksforGeeks

01 Apr, 2020
The uppercase() is an inbuilt function in julia which is used to return a string with all characters converted to uppercase.
Syntax: uppercase(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with all characters converted to uppercase.
Example:
# Julia program to illustrate # the use of uppercase() method   # Getting a string with all # characters converted to uppercaseprintln(uppercase("gfg"))println(uppercase("geeks"))println(uppercase("geeksforgeeks"))
Output:
GFG
GEEKS
GEEKSFORGEEKS

The uppercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to uppercase.
Syntax: uppercasefirst(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with first character converted to uppercase.
Example:
# Julia program to illustrate # the use of uppercasefirst() method   # Getting a string with first# character converted to uppercaseprintln(uppercasefirst("gfg"))println(uppercasefirst("geeks"))println(uppercasefirst("geeksforgeeks"))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Getting the maximum value from a list in Julia - max() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Date and Time in Julia
Working with Excel Files in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Exception handling in Julia
Functions in Julia
Replacing elements of a collection in Julia - replace() and replace!() Methods
Convert XML to POJO using the Jackson library in Java?

The JSON Jackson is a library for Java. It has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can also convert an XML format to the POJO object using the readValue() method of the XmlMapper class.
public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException
import com.fasterxml.jackson.dataformat.xml.*;
public class XMLToPOJOTest {
   public static void main(String args[]) throws Exception {
      try {
         XmlMapper xmlMapper = new XmlMapper();
         Person pojo = xmlMapper.readValue(getXmlString(), Person.class);
         System.out.println(pojo);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
   private static String getXmlString() {
      return "<person> <firstName>Adithya</firstName>"
                    + "<lastName>Jai</lastName>"
                    + "<address>Bangalore</address>" + "</person>";
   }
}
// Person class (POJO)
class Person {
   private String firstName;
   private String lastName;
   private String address;
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Person[ " +
             "firstName = " + firstName +
             ", lastName = " + lastName +
             ", address = " + address +
             " ]";
   }
}
Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]
What is the class "class" in Java?

The Java.lang.Class class instance represent classes and interfaces in a running Java application. It has no public constructor.
Following is the example demonstrates the usage of the class Class.
The java.lang.Class.getCanonicalName() method returns the canonical name of the underlying class as defined by the Java Language Specification. It returns null if the class does not have a canonical name.
 Live Demo
import java.lang.*;

public class ClassDemo {
   public static void main(String[] args) {
      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();
      
      //Returns the canonical name of the underlying class if it exists
      System.out.println("Class = " + cls.getCanonicalName());
   }
}
Class = com.tutorialspoint.ClassDemo
How to open a file in binary mode with Python?

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it.
f = open('my_file.mp3', 'rb')
file_content = f.read()
f.close()
 Above code opens my_file.mp3 in binary read mode and stores the file content in file_content variable.
strcpy() in C/C++

The function strcpy() is a standard library function. It is used to copy one string to another. In C language,it is declared in “string.h” header file while in C++ language, it is declared in cstring header file. It returns the pointer to the destination.
Here is the syntax of strcpy() in C language,
char* strcpy(char* dest, const char* src);
Some key points of strcpy().
It copies the whole string to the destination string. It replaces the whole string instead of appending it.
It copies the whole string to the destination string. It replaces the whole string instead of appending it.
It won’t change the source string.
It won’t change the source string.
Here is an example of strcpy() in C language,
 Live Demo
#include <stdio.h>
#include<string.h>
int main() {
   char s1[] = "Hello world!";
   char s2[] = "Welcome";
   printf("String s1 before: %s\n", s1);
   strcpy(s1, s2);
   printf("String s1 after: %s\n", s1);
   printf("String s2 : %s", s2);
   return 0;
}
String s1 before: Hello world!
String s1 after: Welcome
String s2 : Welcome
strrchr() function in C/C++ - GeeksforGeeks

27 Aug, 2018
The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file.Syntax :
const char* strrchr( const char* str, int ch )
            or
char* strrchr( char* str, int ch )

Parameter :The function takes two mandatory parameters which are described below:
str : specifies the pointer to the null terminated string to be searched for.
ch: specifies the character to be search for.
Return Value: The function returns a pointer to the last location of ch in string, if the ch is found. If not found, it returns a null pointer.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate// the strrchr() function#include <bits/stdc++.h>using namespace std;  int main(){    // Storing it in string array    char string[] = "Geeks for Geeks";      // The character we've to search for    char character = 'k';      // Storing in a pointer ptr    char* ptr = strrchr(string, character);      // ptr-string gives the index location    if (ptr)        cout << "Last position of " << character             << " in " << string << " is " << ptr - string;      // If the character we're searching is not present in the array    else        cout << character << " is not present "             << string << endl;    return 0;}
Last position of k in Geeks for Geeks is 13

Program 2:
// C++ program to illustrate // the strrchr() function#include <bits/stdc++.h>using namespace std;  int main(){    // Storing it in string array    char string[] = "Geeks for Geeks";    char* ptr;      // The character we've to search for    char character = 'z';      // Storing in a pointer ptr    ptr = strrchr(string, character);      // ptr-string gives the index location    if (ptr)        cout << "Last position of " << character             << " in " << string << " is " << ptr - string;      // If the character we're searching    // is not present in the array    else        cout << character << " is not present in "             << string << endl;    return 0;}
z is not present in Geeks for Geeks

C-Library
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
Creating alias in a MongoDB query?

You can use aggregate framework to create an alias. Let us first create a collection with documents −
> db.creatingAliasDemo.insertOne({_id:101,"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.creatingAliasDemo.insertOne({_id:102,"Name":"David Miller"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.creatingAliasDemo.insertOne({_id:103,"Name":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from the collection with the help of find() method −
> db.creatingAliasDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "Name" : "John Doe" }
{ "_id" : 102, "Name" : "David Miller" }
{ "_id" : 103, "Name" : "Sam Williams" }
Following is the query to create alias in a query −
> db.creatingAliasDemo.aggregate(
...    [
...       {
...          $project: {
...             _id:1,
...             "FullName":"$Name"
...          }
...       }
...    ]
... );
This will produce the following output −
{ "_id" : 101, "FullName" : "John Doe" }
{ "_id" : 102, "FullName" : "David Miller" }
{ "_id" : 103, "FullName" : "Sam Williams" }
Flask â Application

In order to test Flask installation, type the following code in the editor as Hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World’

if __name__ == '__main__':
   app.run()
Importing flask module in the project is mandatory. An object of Flask class is our WSGI application.
Flask constructor takes the name of current module (__name__) as argument.
The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.
app.route(rule, options)

The rule parameter represents URL binding with the function.
The rule parameter represents URL binding with the function.
The options is a list of parameters to be forwarded to the underlying Rule object.
The options is a list of parameters to be forwarded to the underlying Rule object.
In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered.
Finally the run() method of Flask class runs the application on the local development server.
app.run(host, port, debug, options)

All parameters are optional
host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally
port
Defaults to 5000
debug
Defaults to false. If set to true, provides a debug information
options
To be forwarded to underlying Werkzeug server.
The above given Python script is executed from Python shell.
Python Hello.py

A message in Python shell informs you that
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it.
A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.
The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.
app.debug = True
app.run()
app.run(debug = True)

    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Removing property from a JSON object in JavaScript

Let’s say, we create an object as follows −
const myObject = {
   "ircEvent": "PRIVMSG",
   "method": "newURI",
   "regex": "^http://.*"
};
We are required to illustrate the best way to remove the property regex to end up with new
myObject as follows −
const myObject = {
   "ircEvent": "PRIVMSG",
   "method": "newURI"
};
The delete operator is used to remove properties from objects −
const myObject = {
   "ircEvent": "PRIVMSG",
   "method": "newURI",
   "regex": "^http://.*"
};
delete myObject['regex'];
console.log(myObject.hasOwnProperty("regex")); // false
The delete operator in JavaScript has a different function to that of the keyword in C and C++ −
It does not directly free memory. Instead, its sole purpose is to remove properties from objects.
Following is the console output −
False
Rotate xtick labels in Seaborn boxplot using Matplotlib

To rotate xtick labels in Seaborn boxplot, we can take the following steps −
Create data points for xticks.
Create data points for xticks.
Draw a boxplot using boxplot() method that returns the axis.
Draw a boxplot using boxplot() method that returns the axis.
Now, set the xticks using set_xticks() method, pass xticks.
Now, set the xticks using set_xticks() method, pass xticks.
Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method.
Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method.
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xticks = [1, 4, 5, 2, 3]
ax = sns.boxplot(xticks)
ax.set_xticks(xticks)
ax.set_xticklabels(["one", "two", "three", "four", "five"], rotation=45)
plt.show()
Program to extract frames using OpenCV in Python?

OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.
With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & reorganization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.
In this exercise we are going to implement frame by frame video processing. The input video can be live camera video or video stored in your local machine. We are going to create frames from the video stored in our local machine & then store the frames in our local drive.
As opencv is not a standard python library, so we need to install it. We can install it using pip very easily:
pip install opencv-python
Collecting opencv-python
Downloading https://files.pythonhosted.org/packages/49/4b/ad55a2e2c309fb698e1283e687129e0892c7864de9a4424c4ff01ba0a3bb/opencv_python-4.0.0.21-cp36-cp36m-win32.whl (22.1MB)
100% |████████████████████████████████| 22.1MB 141kB/s
Requirement already satisfied: numpy>=1.11.3 in c:\python\python361\lib\site-packages (from opencv-python) (1.13.0)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.0.0.21
My video file is stored in the f: drive, which I want to convert into frames (thumbnails) and then store the frames in my chosen location.
Code: Program to read a video file and extract frames from it.
#Import libraries
import cv2
import os
#Function to extract frames
def extractFrames(pathIn, pathOut):
   #directory path, where my video images will be stored
   os.mkdir(r'c:/users/rajesh/Desktop/data')
   #Capture vidoe from video file
   cap = cv2.VideoCapture(pathIn)
#Counter Variable
count = 0

while (cap.isOpened()):
   # Capture frame-by-frame
   ret, frame = cap.read()
   if ret == True:
      print('Read %d frame: ' % count, ret)
      # save frame as JPEG file
      cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)
      count += 1
   else:
      break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def main():
   extractFrames(r'f:/I Miss You.mp4' , 'data')
if __name__=="__main__":
   main()
We can see, a data folder is created in my desktop(destination path) and the frames from the video are stored inside the folder.
Express.js – app.post() Method

The app.post() method routes all the HTTP POST requests to the specified path with the specified callback functions.
app.path(path, callback, [callback])
path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.
callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).
Create a file with the name "appPost.js" and copy the following code snippet. After creating the file, use the command "node appPost.js" to run this code.
// app.post() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Creating a POST request
app.post('/api', (req, res) => {
   console.log("POST Request Called for /api endpoint")
   res.send("POST Request Called")
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint with a POST request
http://localhost:3000/api

C:\home\node>> node appPost.js
Server listening on PORT 3000
POST Request Called for /api endpoint
Let’s take a look at one more example.
// app.post() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Creating a POST request
app.post('/api', (req, res) => {
   console.log("Method called is -- ", req.method)
   res.end()
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Now, hit the following Endpoint with a POST request
http://localhost:3000/api

C:\home\node>> node appPost.js
Server listening on PORT 3000
Method called is -- POST
Lodash _.prototype.toJSON() Method - GeeksforGeeks

18 Sep, 2020
The _.prototype.toJSON() method of Sequence in lodash is used to execute the chain sequence in order to solve the unwrapped value.
Syntax:
_.prototype.toJSON()

Parameters: This method doesn’t accept any parameter.
Return Value: This method returns the resolved unwrapped value.
Below examples illustrate the Lodash _.prototype.toJSON() method in JavaScript:
Example 1:
Javascript
// Requiring lodash libraryconst _ = require('lodash');  // Calling _.prototype.toJSON() method let unwrap_val = _([6, 7, 8]).toJSON();  // Displays outputconsole.log(unwrap_val);
Output:
[ 6, 7, 8 ]

Example 2:
Javascript
// Requiring lodash libraryconst _ = require('lodash');  // Defining valueslet values = {"gfg":3, "geek":15};  // Calling _.prototype.toJSON() method let res = _(values).toJSON();  // Displays outputconsole.log(res);
Output:
{ gfg: 3, geek: 15 }

JavaScript-Lodash
JavaScript
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Hide or show elements in HTML using display property
JavaScript | console.log() with Examples
Difference Between PUT and PATCH Request
reflect.Pointer() Function in Golang with Examples

05 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Pointer() Function in Golang is used to get the v’s value as a uintptr. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) Pointer() uintptr

Parameters: This function does not accept any parameter.
Return Value: This function returns the v’s value as a uintptr.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Pointer() Function    package main   import (    "reflect"    "unsafe"    "fmt")   func main() {    var s = struct{ foo int }{100}    var i int       rs := reflect.ValueOf(&s).Elem()     rf := rs.Field(0)                  ri := reflect.ValueOf(&i).Elem()           // use of Pointer() method    rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()    ri.Set(rf)    rf.Set(ri)           fmt.Println(rf)}
Output:
100

Example 2:
// Golang program to illustrate// reflect.Pointer() Function    package main   import (    "fmt"    "play.ground/foo"    "reflect"    "unsafe")   func GetUnexportedField(field reflect.Value) interface{} {    return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()}   func SetUnexportedField(field reflect.Value, value interface{}) {    reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).        Elem().        Set(reflect.ValueOf(value))}   func main() {    f := &foo.Foo{        Exported: "Old Value ",    }       fmt.Println(f.Exported)            field := reflect.ValueOf(f).Elem().FieldByName("unexported")    SetUnexportedField(field, "New Value")    fmt.Println(GetUnexportedField(field))}   -- go.mod --module play.ground   -- foo/foo.go --package foo   type Foo struct {    Exported   string    unexported string}
Output:
Old Value 
New Value

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REPLACE() Function in MySQL

31 Aug, 2020
REPLACE() function could be used to replaces all presence of a substring within a string, with a new substring. REPLACE() function is a case-sensitive.
Syntax :
SELECT REPLACE(string, from_string, new_string)

Parameter string is used to replace the original string from_string to be new_string.
Example-1:In this example, you will see how you can replace any string value with a new string value by using the replace function.Let’s consider an example where “MySQL” replace with “HTML” value. Below given is the replace function values.
Replace "MySQL" with "HTML"

Now, you will see how you can read the replace values.
SELECT REPLACE("MySQL in Geeksforgeeks", "SQL", "HTML");

Output :
Example-2:
Replace "X" with "A"

Now, If you want to read the replaced value then use the following function given below.
SELECT REPLACE("It is Good to study XXX from GFG", "X", "A");

Output :
Example-3:
Replace "x" with "a"

Now, If you want to read the replaced value then use the following function given below.
SELECT REPLACE("It is Good to study xxx from GFG", "x", "a");

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

It exchanges the content of the container by the content of str, which is another string object. Lengths may differ.
Following is the declaration for std::string::swap.
void swap (string& str);
void swap (string& str);
void swap (string& str);
str − It is a string object.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::swap.
#include <iostream>
#include <string>

main () {
   std::string buyer ("money");
   std::string seller ("goods");

   std::cout << "Before the swap, buyer has " << buyer;
   std::cout << " and seller has " << seller << '\n';

   seller.swap (buyer);

   std::cout << " After the swap, buyer has " << buyer;
   std::cout << " and seller has " << seller << '\n';

   return 0;
}
The sample output should be like this −
Before the swap, buyer has money and seller has goods
 After the swap, buyer has goods and seller has money
Pandas Groupby and Sum

25 Nov, 2020
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. 
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. It is helpful in the sense that we can :
Compute summary statistics for every group
Perform group-specific transformations
Do the filtration of data
The groupby() involves a combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups such as sum().
Example 1:
Python3
# import required moduleimport pandas as pd  # create dataframedf = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'],                   'Max Speed': [380., 370., 24., 26.]})  # use groupby() to compute sumdf.groupby(['Animal']).sum()
Output
Example 2:
Python3
# import required moduleimport pandas as pd  # assign listl = [[100, 200, 300], [10, None, 40],     [20, 10, 30], [100, 200, 200]]  # create dataframedf = pd.DataFrame(l, columns=["a", "b", "c"])  # use groupby() to generate sumdf.groupby(by=["b"]).sum()
Output:
Example 3:
Python3
# import required moduleimport pandas as pd  # assign dataipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils',                     'Kings',  'kings', 'Kings', 'Kings',                     'Riders', 'Royals', 'Royals', 'Riders'],            'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2],              'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016,                      2017, 2016, 2014, 2015, 2017],              'Points': [876, 789, 863, 673, 741, 812, 756, 788,                        694, 701, 804, 690]}  # create dataframedf = pd.DataFrame(ipl_data)  # use groupby() to generate sumdf.groupby(['Team']).sum()
Output:
Python pandas-groupby
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Software Engineering - GeeksforGeeks

22 Jan, 2014
GROUP I                                         GROUP II
(P) Service oriented computing                 (1) Interoperability
(Q) Heterogeneous communicating systems        (2) BPMN
(R) Information representation                 (3) Publish-find-bind
(S) Process description                        (4) XML 
Coupling between M1 and M2 = (Number of external links) / 
                             (Number of modules) 
                           = 2/2
                           = 1

Cohesion of a module = (Number of internal links) / 
                       (Number of methods)
                   

Cohesion of M1 = 8/4 = 2
Cohesion of M2 = 6/3 = 2


After moving method m to M2, we get following


Coupling = 2/2 = 1
Cohesion of M1 = 6/3 = 2
Cohesion of M2 = 8/4 = 2 
Effort Applied (E) = ab(KLOC)bb [ person-months ]
                   = 2.8 x(40)1.20 
                   = 2.8 x 83.65 
                   = 234.25 
 
        /* This function computes the roots of a quadratic equation
           a.x^2 + b.x + c = . The function stores two real roots
           in *root1 and *root2 and returns the status of validity
           of roots. It handles four different kinds of cases.
           (i) When coefficient a is zero irrespective of discriminant
           (ii) When discreminant is positive
           (iii) When discriminant is zero
           (iv) When discriminant is negative.
           Only in case (ii) and (iii) the stored roots are valid.
           Otherwise 0 is stored in roots. The function returns
           0 when the roots are valid and -1 otherwise.
           The function also ensures root1 >= root2
              int get_QuadRoots( float a, float b, float c,
                 float *root1, float *root2);
        */
Cyclomatic Complexity of module = Number of decision points + 1

Number of decision points in A = 10 - 1 = 9
Number of decision points in B = 10 - 1 = 9
Cyclomatic Complexity of the integration = Number of decision points + 1
                                         = (9 + 9) + 1
                                         = 19

P. Requirements Capture	 1.Module Development and Integration
Q. Design	         2.Domain Analysis
R. Implementation	 3.Structural and Behavioral Modeling
S. Maintenance	         4.Performance Tuning
begin
  if (a== b) {S1; exit;}
  else if (c== d) {S2;]
       else {S3; exit;}
  S4;
end 
T1 checks S1 

T2 checks S3

T4 checks S2 and S4
   I.   Content coupling
   II.  Common coupling
   III. Control coupling 
   IV.  Stamp coupling
   V.   Data coupling 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Order and Ranking Questions & Answers
Spring Boot - Thymeleaf with Example
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Explain Promise.all with async-await in JavaScript
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
Installation and Configuration Symfony Framework

10 May, 2020
Symfony is an open-source PHP web application framework with MVC architecture. It is a set of reusable PHP components/libraries. It is basically designed for developers who need an elegant and simple toolkit to create web applications and is the most popular application frameworks among the open-source developer’s community. It is used to build high-performance complex web applications.
Prerequisites:
PHP installation on windows.
Environment setup to run the project.
Composer software to create symfony project: https://getcomposer.org/download
Symfony software download: https://symfony.com/download
Installation:
Step 1: Go to xampp root folder and open htdocs folder there. Type “cmd” (without inverted commas) in the address bar(shown below) and hit enter.
Step 2: Enter the following command in the command prompt.composer create-project symfony/skeleton project_1In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully.
composer create-project symfony/skeleton project_1
In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully.
Step 3: Start your xampp server and goto localhost/project_1/public.If you see something like this then your project is created successfully.
First Project: Here we will create a Hello World page in three steps.
Step 1: Create a new file named “HelloController.php” in src/Controller/ folder and write the following code in that file.<?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class HelloController{    public function hello()    {        return new Response(            'Hello World'        );    }}
<?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class HelloController{    public function hello()    {        return new Response(            'Hello World'        );    }}
Step 2: Open config/routes.yaml file and write the following code in that file.app_hello:    path: /    controller: App\Controller\HelloController::hello
app_hello:    path: /    controller: App\Controller\HelloController::hello
Step 3: Goto localhost/project_1/public.If you see something like this then you have successfully created hello world page.
PHP
PHP Programs
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 ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
HTML | <img> hspace Attribute

08 Aug, 2019
The HTML <img> hspace attribute is used to specify the number of whitespaces on the left and the right side of the image. The hspace attribute is not supported by HTML 5 you can use CSS there.
Syntax:
<img hspace="pixels"> 
Attribute Values:
pixels: It specifies the number of whitespaces in terms of pixels.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML <img> hspace Attribute    </title>        <style>                h1,        h3 {            text-align: center;        }                  h4 {            font-weight: bold;        }    </style></head>  <body>      <h1 style="color:green;">             GeeksforGeeks         </h1>      <h3>HTML Image hspace Attribute</h3>    <h4>Image without hspace</h4>    <p><img id="myImage" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png"             alt="Submit"            width="42"             height="42"             align="middle" />      It is a computer science portal for geeks.GeeksforGeeks    </p>    <h4>Image with hspace</h4>    <p><img id="myImage" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png"             alt="Submit"             hspace="40"             width="42"             height="42"            align="middle" />      It is a computer science portal for geeks.GeeksforGeeks    </p>  </body>  </html>
Output :
Supported Browsers: The browser supported by HTML <img> hspace Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.