code-rag-bench/online-tutorials huggingface dataset:
descendants generator – Python Beautifulsoup - GeeksforGeeks

25 Oct, 2020
descendants generator is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The .contents and .children attribute only consider a tag’s direct children. The descendants generator is used to iterate over all of the tag’s children, recursively. Each child is going to be the tag element for the elements and NavigableString for the strings.
Syntax: 
 tag.descendants 

Below given examples explain the concept of descendants generator in Beautiful Soup. Example 1: In this example, we are going to get the descendants of an element.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<body><b> Hello world </b><body>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the body tagtag = soup.body  # Print all the descendants of tagfor descendant in tag.descendants:    print(descendant)
Output: 
<b> Hello world </b>
 Hello world 
<body></body>

Example 2: In this example, we are going to see the type of descendants.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<body><b> Hello world </b><body>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the body tagtag = soup.body  # Print the type of the descendants of tagfor descendant in tag.descendants:    print(type(descendant))
Output: 
<class 'bs4.element.Tag'>
<class 'bs4.element.NavigableString'>
<class 'bs4.element.Tag'>

Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
How to return only value of a field in MongoDB?

In order to return only value of a field in MongoDB, you need to write a query and use forEach loop. Let us first create a collection with documents
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea537d628fa4220163b6e")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea53bd628fa4220163b6f")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea541d628fa4220163b70")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Ramit"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea549d628fa4220163b71")
}
Following is the query to display all documents from a collection with the help of find() method
> db.returnOnlyValueOfFieldDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9ea537d628fa4220163b6e"), "ClientName" : "Larry" }
{ "_id" : ObjectId("5c9ea53bd628fa4220163b6f"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5c9ea541d628fa4220163b70"), "ClientName" : "Robert" }
{ "_id" : ObjectId("5c9ea549d628fa4220163b71"), "ClientName" : "Ramit" }
Following is the query to return only value of a field in MongoDB
> var output = []
> db.returnOnlyValueOfFieldDemo.find().forEach(function(document) {output.push(document.ClientName) })
In order to get value of a field in MongoDB, you need to write variable name output at the Mongo shell (as we know the value is stored in output array). Following is the query
> output
This will produce the following output
[ "Larry", "Chris", "Robert", "Ramit" ]
\eqalign - Tex Command

\eqalign - Used for equation alignment; for aligning multi-line displays at a single place.
{ \eqalign{ <math> & <math> \cr <repeat as needed> } }
\eqalign command is used for equation alignment; for aligning multi-line displays at a single place. The ampersand is placed where alignment is desired; a double-backslash can be used in place of the  \cr ; the final   \\   or   \cr   is optional; supports only a single \tag, which is vertically centered.

\eqalign{
3x - 4y &= 5\cr
x  +  7 &= -2y
}


3x−4y=5x+7=−2y


\eqalign{
(a+b)^2 &= (a+b)(a+b) \\
        &= a^2 + ab + ba + b^2 \\
        &= a^2 + 2ab + b^2
}


(a+b)2=(a+b)(a+b)=a2+ab+ba+b2=a2+2ab+b2


\left\{
\eqalign{
a &= 1\\
b &= 2\\
c &= 3
}\right\}
\qquad
\eqalign{
ax + by &= c \\
 x + 2y &= 3
 }


{a=1b=2c=3}ax+by=cx+2y=3



\eqalign{
3x - 4y &= 5\cr
x  +  7 &= -2y
}


3x−4y=5x+7=−2y


\eqalign{
3x - 4y &= 5\cr
x  +  7 &= -2y
}

\eqalign{
(a+b)^2 &= (a+b)(a+b) \\
        &= a^2 + ab + ba + b^2 \\
        &= a^2 + 2ab + b^2
}


(a+b)2=(a+b)(a+b)=a2+ab+ba+b2=a2+2ab+b2


\eqalign{
(a+b)^2 &= (a+b)(a+b) \\
        &= a^2 + ab + ba + b^2 \\
        &= a^2 + 2ab + b^2
}

\left\{
\eqalign{
a &= 1\\
b &= 2\\
c &= 3
}\right\}
\qquad
\eqalign{
ax + by &= c \\
 x + 2y &= 3
 }


{a=1b=2c=3}ax+by=cx+2y=3


\left\{
\eqalign{
a &= 1\\
b &= 2\\
c &= 3
}\right\}
\qquad
\eqalign{
ax + by &= c \\
 x + 2y &= 3
 }


    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to Detect the key points of an image using OpenCV Java library?

The detect() method of the org.opencv.features2d.Feature2D (abstract) class detects the key points of the given image. To this method, you need to pass a Mat the object representing the source image and an empty MatOfKeyPoint object to hold the read key points.
You can draw the draw key points on the image using the drawKeypoints() method of the org.opencv.features2d.Features2d class.
Since Feature2D is an abstract class you need to instantiate one of its subclasses to invoke the detect() method. Here we have used the FastFeatureDetector class.
Since Feature2D is an abstract class you need to instantiate one of its subclasses to invoke the detect() method. Here we have used the FastFeatureDetector class.
Features2D and Features2d are two different classes of the package features2d don’t get confused...
Features2D and Features2d are two different classes of the package features2d don’t get confused...
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.Scalar;
import org.opencv.features2d.FastFeatureDetector;
import org.opencv.features2d.Features2d;
import org.opencv.highgui.HighGui;z
import org.opencv.imgcodecs.Imgcodecs;
public class DetectingKeyPoints{
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the contents of the image
      String file ="D:\\Images\\javafx_graphical.jpg";
      Mat src = Imgcodecs.imread(file);
      //Reading the key points of the image
      Mat dst = new Mat();
      MatOfKeyPoint matOfKeyPoints = new MatOfKeyPoint();
      FastFeatureDetector featureDetector = FastFeatureDetector.create();
      featureDetector.detect(src, matOfKeyPoints);
      //Drawing the detected key points
      Features2d.drawKeypoints(src, matOfKeyPoints, dst, new Scalar(0, 0, 255));
      HighGui.imshow("Feature Detection", dst);
      HighGui.waitKey();
   }
}
Extend data class in Kotlin

Data class is a class that holds the data for an application. It is just like a POJO class that we use in Java in order to hold the data.
In Java, for data class, we need to create getter and setter methods in order to access the properties of that class. In Kotlin, when a class is declared as a data class, the compiler automatically creates some supporting methods required to access the member variable of the class. The compiler will create getters and setters for the constructor parameters, hashCode(), equals(), toString(), copy().
For a class to be considered as a data class in Kotlin, the following conditions are to be fulfilled −
The primary constructor needs to have at least one parameter.
The primary constructor needs to have at least one parameter.
All primary constructor parameters need to be marked as val or var.
All primary constructor parameters need to be marked as val or var.
Data classes cannot be abstract, open, sealed, or inner.
Data classes cannot be abstract, open, sealed, or inner.
We cannot extend a data class but in order to implement the same feature, we can declare a super class and override the properties in a sub-class.
In the following example, we will create two data classes "Student" and "Book". We will also create an abstract class "Resource". Inside "Book", we will override the properties of the "Resource" class.
data class Student(val name: String, val age: Int)

fun main(args: Array) {
   val stu = Student("Student1", 29)
   val stu2 = Student("Student2", 30)
   println("Student1 Name is: ${stu.name}")
   println("Student1 Age is: ${stu.age}")
   println("Student2 Name is: ${stu2.name}")
   println("Student2 Age is: ${stu2.age}")
   val b=Book(1L,"India","123222") // implementing abstract class
   println(b.location)
}

// declaring super class
abstract class Resource {
   abstract var id: Long
   abstract var location: String
}

// override the properties of the Resource class
data class Book (
   override var id: Long = 0,
   override var location: String = "",
   var isbn: String
) : Resource()
It will generate the following output −
Student1 Name is: Student1
Student1 Age is: 29
Student2 Name is: Student2
Student2 Age is: 30
India
AtomicInteger getAndIncrement() method in Java with examples - GeeksforGeeks

29 Jan, 2019
The java.util.concurrent.atomic.AtomicInteger.getAndIncrement() is an inbuilt method in java that increases the given value by one and returns the value before updation which is of data-type int.
Syntax:
public final int getAndIncrement()

Parameters: The function does not accepts a single parameter.
Return value: The function returns the value before increment operation is performed to the previous value.
Program below demonstrates the function:
Program 1:
// Java program that demonstrates// the getAndIncrement() function  import java.util.concurrent.atomic.AtomicInteger;public class GFG {    public static void main(String args[])    {          // Initially value as 0        AtomicInteger val            = new AtomicInteger(0);          // Decreases and gets        // the previous value        int res            = val.getAndIncrement();          System.out.println("Previous value: "                           + res);          // Prints the updated value        System.out.println("Current value: "                           + val);    }}
Previous value: 0
Current value: 1

Program 2:
// Java program that demonstrates// the getAndIncrement() function  import java.util.concurrent.atomic.AtomicInteger;  public class GFG {    public static void main(String args[])    {          // Initially value as 18        AtomicInteger val            = new AtomicInteger(18);          // Increases 1 and gets        // the previous value        int res = val.getAndIncrement();          System.out.println("Previous value: "                           + res);        // Prints the updated value        System.out.println("Current value: "                           + val);    }}
Previous value: 18
Current value: 19

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement–
Java - util package
Java-AtomicInteger
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
C# | Number of elements in HashSet - GeeksforGeeks

01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. You can use HashSet.Count Property to count the number of elements in a HashSet.
Syntax:
mySet.Count;

Here mySet is the HashSet
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get the number of// elements that are contained in HashSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet = new HashSet<int>();          // Inserting elements in HashSet        for (int i = 0; i < 5; i++) {            mySet.Add(i * 2);        }          // To get the number of        // elements that are contained in HashSet        Console.WriteLine(mySet.Count);    }}
5

Example 2:
// C# code to get the number of// elements that are contained in HashSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet = new HashSet<int>();          // To get the number of        // elements that are contained in HashSet.        // Note that, here the HashSet is empty        Console.WriteLine(mySet.Count);    }}
0

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.count?view=netframework-4.7.2#System_Collections_Generic_HashSet_1_Count
CSharp-Generic-HashSet
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
HashSet in C# with Examples
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
Python | Grayscaling of Images using OpenCV - GeeksforGeeks

26 Jul, 2021
Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white.
Dimension reduction: For example, In RGB images there are three color channels and has three dimensions while grayscale images are single-dimensional.
Reduces model complexity: Consider training neural article on RGB images of 10x10x3 pixel. The input layer will have 300 input nodes. On the other hand, the same neural network will need only 100 input nodes for grayscale images.
For other algorithms to work: Many algorithms are customized to work only on grayscale images e.g. Canny edge detection function pre-implemented in OpenCV library works on Grayscale images only.
Let’s learn the different image processing methods to convert a colored image into a grayscale image.
Python3
# import opencvimport cv2 # Load the input imageimage = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg')cv2.imshow('Original', image)cv2.waitKey(0) # Use the cvtColor() function to grayscale the imagegray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow('Grayscale', gray_image)cv2.waitKey(0)  # Window shown waits for any key pressing eventcv2.destroyAllWindows()
Input image: 
Output Image: 
Python3
# Import opencvimport cv2 # Use the second argument or (flag value) zero# that specifies the image is to be read in grayscale modeimg = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg', 0) cv2.imshow('Grayscale Image', img)cv2.waitKey(0) # Window shown waits for any key pressing eventcv2.destroyAllWindows()
Output Image:
Python3
# Import opencvimport cv2 # Load the input imageimg = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg') # Obtain the dimensions of the image array# using the shape method(row, col) = img.shape[0:2] # Take the average of pixel values of the BGR Channels# to convert the colored image to grayscale imagefor i in range(row):    for j in range(col):        # Find the average of the BGR pixel values        img[i, j] = sum(img[i, j]) * 0.33 cv2.imshow('Grayscale Image', img)cv2.waitKey(0) # Window shown waits for any key pressing eventcv2.destroyAllWindows()
Output Image:
Hope you have understood the above discussed image processing techniques to convert a colored image into a grayscale image in Python!
sanju6890
saurabh1990aror
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Get the last record from a table in MySQL database with Java?

To get data from MySQL database, you need to use executeQuery() method from java. First create a table in the MySQL database. Here, we will create the following table in the ‘sample’ database
mysql> create table javaGetDataDemo
- > (
- > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > FirstName varchar(10),
- > LastName varchar(10)
- > );
Query OK, 0 rows affected (0.80 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into javaGetDataDemo(FirstName,LastName) values('John','Smith');
Query OK, 1 row affected (0.19 sec)
mysql> insert into javaGetDataDemo(FirstName,LastName) values('Carol','Taylor');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from javaGetDataDemo;
The following is the output
+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
|  1 | John      | Smith    |
|  2 | Carol     | Taylor   |
+----+-----------+----------+
2 rows in set (0.00 sec)
Now here is the Java code to get the last record from the table with the help of ORDER BY DESC clause
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetDataFromMySQLToJava {
   public static void main(String[] args) {
      String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
      String Username = "root";
      String password = "123456";
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
         System.out.println("Connecting to database..............." + JdbcURL);
         con = DriverManager.getConnection(JdbcURL, Username, password);
         Statement st = con.createStatement();
         String query = ("SELECT * FROM javaGetDataDemo ORDER BY Id DESC LIMIT 1;");
         rs = st.executeQuery(query);
         if (rs.next()) {
            String fname = rs.getString("FirstName");
            String lname = rs.getString("LastName");
            System.out.println("FirstName:" + fname);
            System.out.println("LastName:" + lname);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
The screenshot of Java code is as follows
The following is the screenshot of the output displaying the last record from the table
Tryit Editor v3.7 - Show Java

static void Main(string[] args)
    {
      string txt = "We are the so-called \"Vikings\" from the north.";
Minimum number of moves to make all elements equal using C++.

Given an array of N elements and an integer K., It is allowed to perform the following operation any number of times on the given array −
Insert the Kth element at the end of the array and delete the first element of the array.
Insert the Kth element at the end of the array and delete the first element of the array.
The task is to find the minimum number of moves needed to make all elements of the array equal. Print -1 if it is not possible
If arr[] = {1, 2, 3, 4, 5, 6} and k = 6 then minimum 5 moves are
required:
Move-1: {2, 3, 4, 5, 6, 6}
Move-2: {3, 4, 5, 6, 6, 6}
Move-3: {4, 5, 6, 6, 6, 6}
Move-4: {5, 6, 6, 6, 6, 6}
Move-5: {6, 6, 6, 6, 6, 6}
1. First we copy a[k] to the end, then a[k+1] and so on
2. To make sure that we only copy equal elements, all elements in the range K to N should be equal. We need to remove all elements in range 1 to K that are not equal to a[k]
3. Keep applying operations until we reach the rightmost term in range 1 to K that is not equal to a[k].
#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int getMinMoves(int *arr, int n, int k){
   int i;
   for (i = k - 1; i < n; ++i) {
      if (arr[i] != arr[k - 1]) {
         return -1;
      }
   }
   for (i = k - 1; i >= 0; --i) {
      if (arr[i] != arr[k - 1]) {
         return i + 1;
      }
   }
   return 0;
}
int main(){
   int arr[] = {1, 2, 3, 4, 5, 6};
   int k = 6;
   cout << "Minimum moves required = " << getMinMoves(arr, SIZE(arr), k) << endl;
   return 0;
}
When you compile and execute the above program. It generates the following output −
Minimum moves required = 5
Fabric.js Image cropX Property - GeeksforGeeks

31 Aug, 2020
Fabric.js is a javascript library that is used to work with canvas. The canvas image is one of the class of fabric.js that is used to create image instances. The canvas image means the Image is movable and can be stretched according to requirement. The cropX property of the image is used to crop a certain amount of the canvas image. The size is given in pixels.
Approach: First import the fabric.js library. After importing the library, create a canvas block in the body tag which will contain the image. After this, initialize an instance of Canvas and image class provided by Fabric.JS and give the width to be cropped of the canvas image in pixels using the cropX property of the image object.
Syntax:
fabric.Image(image, {
    cropX:Number
});
Parameters: The above function takes two parameters as mentioned above and described below:
image: This parameter takes the image.
cropX: This parameter is the amount of image crop in pixels from the original size of the image.
Example: This example uses FabricJS to crop the section of the canvas image along the x-axis as shown in the below given example.
   <!DOCTYPE html> <html>   <head>     <!-- Adding the FabricJS library -->     <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script> </head>   <body>     <h1 style="color: green;">GeeksforGeeks</h1>     <b>Fabric.js | Image cropX Property </b>       <canvas id="canvas" width="400" height="300"        style="border:2px solid #000000">     </canvas>       <img src ="https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png"         width="100" height="100" id="my-image"        style="display: none;"><br>      <button onclick="cropX()">Click me</button>      <script>               // Create the instance of canvas object        var canvas = new fabric.Canvas("canvas");           // Getting the image        var img= document.getElementById('my-image');          // Creating the image instance         var imgInstance = new fabric.Image(img, {        });        function cropX() {            imgInstance = new fabric.Image(img, {                cropX:80            });            canvas.clear();            canvas.add(imgInstance);        }          // Rendering the image to canvas        canvas.add(imgInstance);    </script> </body>   </html>
Output:
Before clicking the button:
After clicking the button:
Fabric.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Program to Insert new item in array on any position in PHP - GeeksforGeeks

01 Oct, 2018
New item in an array can be inserted with the help of array_splice() function of PHP. This function removes a portion of an array and replaces it with something else. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset.
Syntax:
array array_splice ($input, $offset [, $length [, $replacement]])
Parameters: This function takes four parameters out of which 2 are mandatory and 2 are optional:
$input: This parameter takes the value of an array on which operations are needed to perform.
$offset: If this parameter is positive then the start of removed portion is at that position from the beginning of the input array and if this parameter is negative then it starts that far from the end of the input array.
$length: (optional) If this parameter is omitted then it removes everything from offset to the end of the array.If length is specified and is positive, then that many elements will be removed.If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array.If length is specified and is zero, no elements will be removed.
If length is specified and is positive, then that many elements will be removed.
If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array.
If length is specified and is zero, no elements will be removed.
$replacement: (optional) This parameter is an optional parameter which takes value as an array and if this replacement array is specified, then the removed elements are replaced with elements from this replacement array.
Return Value: It returns the last value of the array, shortening the array by one element.
Note that keys in replacement array are not preserved.
Program
<?php//Original Array on which operations is to be perform  $original_array = array( '1', '2', '3', '4', '5' );  echo 'Original array : ';foreach ($original_array as $x) {echo "$x ";}  echo "\n";  //value of new item$inserted_value = '11';  //value of position at which insertion is to be done  $position = 2;  //array_splice() function   array_splice( $original_array, $position, 0, $inserted_value );   echo "After inserting 11 in the array is : ";foreach ($original_array as $x) {echo "$x ";}?>
Original array : 1 2 3 4 5 
After inserting 11 in the array is : 1 2 11 3 4 5

References : http://php.net/manual/en/function.array-splice.php
PHP-array
Picked
PHP
PHP Programs
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
\lbrack - Tex Command

\lbrack - Used to draw left bracket symbol.
{ \lbrack }
\lbrack command is used to draw left brace symbol.

\lbrack \frac ab, c \rbrack

[ab,c]


\left\lbrack \frac ab, c \right\rbrack

[ab,c]



\lbrack \frac ab, c \rbrack

[ab,c]


\lbrack \frac ab, c \rbrack
\left\lbrack \frac ab, c \right\rbrack

[ab,c]


\left\lbrack \frac ab, c \right\rbrack

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
MySQL edit and update records including employee salary

The UPDATE command is used in MySQL to update records. With it, the SET command is used to set new values. Let us first create a table −
mysql> create table DemoTable
(
   EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeName varchar(50),
   EmployeeSalary int
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(EmployeeName,EmployeeSalary) values('Chris',56780);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeSalary) values('Robert',45670);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeSalary) values('Mike',87654);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeSalary) values('David',34569);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
|          1 | Chris        |          56780 |
|          2 | Robert       |          45670 |
|          3 | Mike         |          87654 |
|          4 | David        |          34569 |
+------------+--------------+----------------+
4 rows in set (0.00 sec)
Following is the query to update records and set new values −
mysql> update DemoTable
   set EmployeeSalary=EmployeeSalary+12346;
Query OK, 4 rows affected (0.14 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
|          1 | Chris        | 69126          |
|          2 | Robert       | 58016          |
|          3 | Mike         | 100000         |
|          4 | David        | 46915          |
+------------+--------------+----------------+
4 rows in set (0.00 sec)
When to use static methods in Java?

You should use static methods whenever,
The code in the method is not dependent on instance creation and is not using any instance variable.
A particular piece of code is to be shared by all the instance methods.
The definition of the method should not be changed or overridden.
you are writing utility classes which should not be changed.
 Live Demo
public class InstanceCounter {
   private static int numInstances = 0;
   protected static int getCount() {
      return numInstances;
   }
   private static void addInstance() {
      numInstances++;
   }
   InstanceCounter() {
      InstanceCounter.addInstance();
   }
   public static void main(String[] arguments) {
      System.out.println("Starting with "+InstanceCounter.getCount()+" instances");
      
      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}
Started with 0 instances
Created 500 instances
Calculate the sum of the diagonal elements of a NumPy array - GeeksforGeeks

05 Sep, 2020
Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy.trace() and numpy.diagonal() method.
Method 1: Finding the sum of diagonal elements using numpy.trace()
Syntax : numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)  
Example 1: For 3X3 Numpy matrix
Python3
# importing Numpy packageimport numpy as np  # creating a 3X3 Numpy matrixn_array = np.array([[55, 25, 15],                    [30, 44, 2],                    [11, 45, 77]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # calculating the Trace of a matrixtrace = np.trace(n_array)    print("\nTrace of given 3X3 matrix:")print(trace)
Output:
Example 2: For 4X4 Numpy matrix
Python3
# importing Numpy packageimport numpy as np  # creating a 4X4 Numpy matrixn_array = np.array([[55, 25, 15, 41],                    [30, 44, 2, 54],                    [11, 45, 77, 11],                    [11, 212, 4, 20]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # calculating the Trace of a matrixtrace = np.trace(n_array)    print("\nTrace of given 4X4 matrix:")print(trace)
Output:
Method 2: Finding the sum of diagonal elements using numpy.diagonal()
Syntax :
numpy.diagonal(a, offset=0, axis1=0, axis2=1

Example 1: For 3X3 Numpy Matrix
Python3
# importing Numpy packageimport numpy as np  # creating a 3X3 Numpy matrixn_array = np.array([[55, 25, 15],                    [30, 44, 2],                    [11, 45, 77]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # Finding the diagonal elements of a matrixdiag = np.diagonal(n_array)  print("\nDiagonal elements are:")print(diag)  print("\nSum of Diagonal elements is:")print(sum(diag))
Output:
Example 2: For 5X5 Numpy Matrix
Python3
# importing Numpy packageimport numpy as np  # creating a 5X5 Numpy matrixn_array = np.array([[5, 2, 1, 4, 6],                    [9, 4, 2, 5, 2],                    [11, 5, 7, 3, 9],                    [5, 6, 6, 7, 2],                    [7, 5, 9, 3, 3]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # Finding the diagonal elements of a matrixdiag = np.diagonal(n_array)  print("\nDiagonal elements are:")print(diag)  print("\nSum of Diagonal elements is:")print(sum(diag))
Output:
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Achieve Glow Effect with CSS Filters

The glow effect is used to create a glow around the object. If it is a transparent image, then glow is created around the opaque pixels of it.
The following parameters can be used in this filter −
You can try to run the following code to create a glow around the object −
Live Demo
<html>
   <head>
   </head>

   <body>
      <img src="/css/images/logo.png"
         alt="CSS Logo"
         style="Filter: Chroma(Color = #000000) Glow(Color=#00FF00, Strength=20)">

      <p>Text Example:</p>

      <div style="width: 357;
         height: 50;
         font-size: 30pt;
         font-family: Arial Black;
         color: red;
         Filter: Glow(Color=#00FF00, Strength=20)">CSS Tutorials</div>
   </body>
</html>
Comments in Octave GNU - GeeksforGeeks

01 Aug, 2020
Octave is open-source, free available for many of the platforms. It is a high-level language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB.
Comments are generic English sentences, mostly written in a program to explain what it does or what a piece of code is supposed to do. More specifically, information that programmer should be concerned with and it has nothing to do with the logic of the code. They are completely ignored by the compiler and are thus never reflected on to the input.
In Octave comments are of two types:
Single-line Comments
Block Comments
Single-line comments are comments that require only one line. They are usually drafted to explain what a single line of code does or what it is supposed to produce so that it can help someone referring to the source code. In octave to make a line comment just put a ‘#’ or ‘%’ in front of that line.
Syntax :
# comment statement 
% comment statement 

Example :
char1 = '#';printf("Below is the comment using %c\n", char1);# this is a comment  char2 = '%';printf("Below is the comment using %c\n", char2);% this is also a comment
Output :
Below is the comment using #
Below is the comment using %

In octave to make a block comment just put a ‘#{‘ or ‘%{‘ in the starting of the block and ‘#}’ or ‘%}’ at the end of the block.
Syntax :
#{ 
this is
 a block
 comment
#}

%{ 
this is  
 a block 
 comment
%} 

Example :
char1 = '#';printf("Below is the block comment using %c\n", char1);#{this is a comment using # #}  char2 = '%';printf("Below is the block comment using %c\n", char2);%{this is a comment using % %}
Output :
Below is the block comment using #
Below is the block comment using %

Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Difference between Shallow and Deep copy of a class
Advantages and Disadvantages of OOP
Prolog | An Introduction
Program to calculate Electricity Bill
Top 10 Fastest Programming Languages
Java Swing | JComboBox with examples
JLabel | Java Swing
10 Best IDEs for C or C++ Developers in 2021
Control Structures in Programming Languages
p5.js | setVolume() Function - GeeksforGeeks

21 Nov, 2021
The setVolume() function is an inbuilt function in p5.js library. This function is used to control the volume of the played audio on the web. This function has a range of between (0.0) which means total silence to (1.0) which means full volume. This volume also can be controllable by a slider var by dividing that in different ranges. 
Syntax:  
setVolume( volume, rampTime, timeFromNow )
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameter: This function accept three parameters as mentioned above and described below.  
volume: This parameter holds a float number that defines the volume of the playback.
rampTime: This parameter holds an integer value of time in the second format after that the sound will be fade. It is optional.
timeFromNow: This parameter holds an integer value of time in the second format after that define event will happen.
Below examples illustrate the p5.setVolume() function in JavaScript: Example 1: In this example, we set the fixed volume in the code which is 0.5.  
javascript
var sound; function preload() {     // Initialize sound    sound = loadSound("pfivesound.mp3");} function setup() {     // Playing the preloaded sound    sound.play();    //stopping the played sound after 5 seconds    sound.setVolume(0.5);}
Example 2: In this example, we will create a slide that will help the user to increase the volume by 0.2, and the starting volume is set to 0.2. 
javascript
var sound;var slider; function preload() {      // Initialize sound    sound = loadSound("pfivesound.mp3");}  function setup() {      // Playing the preloaded sound    sound.play();    //creating sound rocker    slider = createSlider(0, 1, 0.2, 0.2);  }  function draw() {    sound.setVolume(slider.value());}
Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Supported Browsers: The browsers are supported by p5.js setVolume() function are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera 
sumitgumber28
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
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?
LISP - Cond Construct

The cond construct in LISP is most commonly used to permit branching.
Syntax for cond is −
(cond   (test1    action1)
   (test2    action2)
   ...
   (testn   actionn))

Each clause within the cond statement consists of a conditional test and an action to be performed.
If the first test following cond, test1, is evaluated to be true, then the related action part, action1, is executed, its value is returned and the rest of the clauses are skipped over.
If test1 evaluates to be nil, then control moves to the second clause without executing action1, and the same process is followed.
If none of the test conditions are evaluated to be true, then the cond statement returns nil.
Create a new source code file named main.lisp and type the following code in it −
(setq a 10)
(cond ((> a 20)
   (format t "~% a is greater than 20"))
   (t (format t "~% value of a is ~d " a)))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
value of a is 10

Please note that the t in the second clause ensures that the last action is performed if none other would.

    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
DateTimeOffset.ToUnixTimeSeconds() Method in C# - GeeksforGeeks

19 Mar, 2019
DateTimeOffset.ToUnixTimeSeconds Method is used to return the number of seconds that have elapsed since 1970-01-01T00:00:00Z. Before returning the Unix time, this method will convert the current instance to the UTC. And also, it will return a negative value for the date and time values before 1970-01-01T00:00:00Z.
Syntax: public long ToUnixTimeSeconds ();
Return Value: This method return the number of seconds that have elapsed since 1970-01-01T00:00:00Z.
Below programs illustrate the use of DateTimeOffset.ToUnixTimeSeconds() Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // creating object of  DateTimeOffset        DateTimeOffset offset = new DateTimeOffset(2017,                6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));          // Returns the number of seconds        // that have elapsed since 1970-01-01T00:00:00Z.        // instance using ToUnixTimeSeconds() method        long value = offset.ToUnixTimeSeconds();          // Display the time        Console.WriteLine("Returns the number of"+                         " seconds : {0}", value);    }}
Returns the number of seconds : 1496321700

Example 2:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeSeconds()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // creating object of  DateTimeOffset        DateTimeOffset offset = new DateTimeOffset(2017,                6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));          // Returns the number of seconds        // that have elapsed since 1970-01-01T00:00:00Z.        // instance using ToUnixTimeSeconds() method        long value = offset.ToUnixTimeSeconds();          // Display the time        Console.WriteLine("Returns the number of"+                         " seconds : {0}", value);    }}
Returns the number of seconds : 1496321700

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
How to convert number to words in an R data frame column?

To convert number to words in an R data frame column, we can use english function from english package. For example, if we have a data frame called df that contains a number column x then we can convert the numbers into words by using the command as.character(english(df$x)).
Consider the below data frame −
 Live Demo
x<-rpois(20,5)
df1<-data.frame(x)
df1
    x
1   3
2   5
3   4
4   7
5   7
6   3
7   6
8   1
9  11
10  6
11  6
12  6
13  5
14  7
15  4
16  1
17  3
18  1
19  1
20  1
Loading english package and converting numbers in column x to words −
library(english)
df1$x<-as.character(english(df1$x))
df1
     x
1   three
2   five
3   four
4   seven
5   seven
6   three
7   six
8   one
9   eleven
10  six
11  six
12  six
13  five
14  seven
15  four
16  one
17  three
18  one
19  one
20  one
 Live Demo
y<-rpois(20,10)
df2<-data.frame(y)
df2
    y
1   6
2  12
3  10
4  11
5  13
6   5
7   7
8   8
9   2
10 11
11 11
12 11
13 12
14 13
15 15
16  6
17 11
18  6
19 11
20 10
Converting numbers in column y to words −
df2$y<-as.character(english(df2$y))
df2
     y
1   six
2   twelve
3   ten
4   eleven
5   thirteen
6   five
7   seven
8   eight
9   two
10  eleven
11  eleven
12  eleven
13  twelve
14  thirteen
15  fifteen
16  six
17  eleven
18  six
19  eleven
20  ten
How to use subList() in android CopyOnWriteArrayList?

Before getting into the example, we should know what CopyOnWriteArrayList is. It is a thread-safe variant of ArrayList and operations add, set, and so on by making a fresh copy of the underlying array.
This example demonstrates about How to use subList() in android CopyOnWriteArrayList
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/actionEvent"
      android:textSize = "40sp"
      android:layout_marginTop = "30dp"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken a text view to show CopyOnWriteArrayList elements.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
public class MainActivity extends AppCompatActivity {
   CopyOnWriteArrayList copyOnWriteArrayList;
   String head;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      copyOnWriteArrayList = new CopyOnWriteArrayList<String>();
      final TextView actionEvent = findViewById(R.id.actionEvent);
      copyOnWriteArrayList.add("sai");
      copyOnWriteArrayList.add("ram");
      copyOnWriteArrayList.add("krishna");
      copyOnWriteArrayList.add("prasad");
      copyOnWriteArrayList.add("ram");
      actionEvent.setText("" + copyOnWriteArrayList);
      actionEvent.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            actionEvent.setText("" + copyOnWriteArrayList.subList(0,2));
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click on textview, It will give the result as shown below –
Click here to download the project code