code-rag-bench/online-tutorials huggingface dataset:
How to select all on focus in input using JQuery? - GeeksforGeeks

31 Oct, 2019
The select() event is applied to an element using jQuery when the user makes a text selection inside an element or on focus the element. This event is limited to some fields.Syntax:
$("selected element").select();

//Select all Input field on focus
$("input").select();
//Select Input field on focus whose type="text"
$("input[type='text']").select();
//Select input field using its id="input-field"
$("#input-field").select();

Example:In below example, select all made on input element of the form using focus, focus and click event.
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script>    <style>        input {            margin: 12px;        }                  ::-moz-selection {            /* Code for Firefox */            color: white;            background: red;        }                  ::selection {            color: white;            background: red;        }    </style></head>  <body align="center">    <form action="/action_page.php"           autocomplete="off">        First name:        <input type="text"                name="fname"                value="Geeks"               required>        <br> Last name:        <input type="text"               name="lname"               value="forGeeks"               required>        <br> E-mail:        <input type="email"                name="eid"                value="carear@geeksforgeeks.org" />        <br> Password:        <input type="password"                name="upwd"                value="********"               required maxlength="8">        <br> User Age:        <input type="number"                name="Test"               min="10"                value="24"                max="80"                required/>        <br> Your web Profile:        <input type="url"                name="Test"                value="http://geeksforgeeks.org"               required />        <br>        <input type="submit" value="Submit">    </form>    <script>        $("input[type='text']").on("click", function() {            $(this).select();        });        $("input").focus(function() {            $(this).select();        });        $("input").focusin(function() {            $(this).select();        });    </script></body>  </html>
Output:
jQuery-Selectors
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
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?
How to Get Uint32 Type Random Number in Golang? - GeeksforGeeks

26 Mar, 2020
Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random numbers for security-sensitive work, then use the crypto/rand package.
You are allowed to generate a pseudo-random number of a 32-bit integer as an uint32 type from the default source with the help of the Uint32() function provided by the math/rand package. So, you need to add a math/rand package in your program with the help of the import keyword to access the Uint32() function.
Syntax:
func Uint32() uint32
Let us discuss this concept with the help of the given examples:
Example 1:
// Golang program to illustrate// how to get a random numberpackage main  import (    "fmt"    "math/rand")  // Main functionfunc main() {      // Finding random numbers    // Using Uint32() function    res_1 := rand.Uint32()    res_2 := rand.Uint32()    res_3 := rand.Uint32()      // Displaying the result    fmt.Println("Random Number 1: ", res_1)    fmt.Println("Random Number 2: ", res_2)    fmt.Println("Random Number 3: ", res_3)}
Output:
Random Number 1:  2596996162
Random Number 2:  4039455774
Random Number 3:  2854263694

Example 2:
// Golang program to illustrate the// use of the random numberspackage main  import (    "fmt"    "math/rand")  // Functionfunc uint32random(value_1, value_2 uint32) uint32 {    return value_1 + value_2 + rand.Uint32()  }  // Main functionfunc main() {      // Getting result from uint32random() function    res1 := uint32random(10, 3)    res2 := uint32random(44, 59)    res3 := uint32random(130, 50)      // Displaying results    fmt.Println("Result 1: ", res1)    fmt.Println("Result 2: ", res2)    fmt.Println("Result 3: ", res3)}
Output:
Result 1:  2596996175
Result 2:  4039455877
Result 3:  2854263874

Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang
How to install Anaconda on Linux? - GeeksforGeeks

21 Jan, 2020
Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming language. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda.
To begin working with Anaconda, one must get it installed first. Follow the below instructions to Download and install Anaconda on your system:
Head over to anaconda.com and install the latest version of Anaconda. Make sure to download the “Python 3.7 Version” for the appropriate architecture.
Begin with the installation process:
Getting Started:
Getting through the License Agreement:
Choose Installation Location:
Extracting Files and packages:
Initializing Anaconda Installation:
Finishing up the Installation:
Once the installation process is done, Anaconda can be used to perform multiple operations. To begin using Anaconda, use the following command to start Anaconda Navigator:
anaconda-navigator
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python | sympy.S.GoldenRatio - GeeksforGeeks

26 Jul, 2019
With the help of sympy.S.GoldenRatio value, We can directly use the value of Golden Ratio constant which is 1.618033989 or we can say that in sympy Golden Ratio constant is a singleton value.
Value of Golden Ratio constant –
Example #1 :In this example we can see that by using singleton value of Golden Ratio constant, we are able to get the value of Golden Ratio constant.
# import sympyfrom sympy import *  # Using sympy.S.GoldenRatio valuegfg = S.GoldenRatio.n(10) + S(20)  print(gfg)
Output :
21.61803399
Example #2 :
# import sympyfrom sympy import *  # Using sympy.S.GoldenRatio valuegfg = S.GoldenRatio.n(20)  print(gfg)
Output :
1.6180339887498948482
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Remove trailing/leading special characters from strings list - GeeksforGeeks

03 Oct, 2019
Sometimes, while working with String lists, we can have a problem in which we need to perform the deletion of extra characters that can be termed as unwanted and occur at end of each string. Let’s discuss a way in which this task can be performed.
Method : Using map() + str.strip()Combination of the above two functionalities can help us achieve this particular task. In this, we employ strip(), which has the ability to remove the trailing and leading special unwanted characters from string list. The map(), is used to extend the logic to each element in list.
# Python3 code to demonstrate working of# Remove trailing / leading special characters from strings list# Using map() + str.strip()  # initializing listtest_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']  # printing listprint("The original list : " + str(test_list))  # Remove trailing / leading special characters from strings list# Using map() + str.strip()res = list(map(str.strip, test_list))  # Printing resultprint("List after removal of special characters : " + str(res))
 
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Initialize dictionary with common value - GeeksforGeeks

26 Aug, 2019
While working with Python, sometimes, we might have a problem in which we require the initialize the static list into a dictionary with a constant value. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using dict() + list comprehension
The combination of above functions can be used to perform this particular task. In this, we just convert the elements extracted from list as keys and assign the common value using list comprehension and conversion done by dict().
# Python3 code to demonstrate working of# Initialize dictionary with common value# Using list comprehension + dict()  # Initialize listtest_list = ['gfg', 'is', 'best']  # printing original listprint("The original list is : " + str(test_list))  # Initialize dictionary with common value# Using list comprehension + dict()res = dict((sub, 4) for sub in test_list)  # printing resultprint("The constructed dictionary with common value : " + str(res))
The original list is : ['gfg', 'is', 'best']
The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}

 
Method #2 : Using fromkeys()
The inbuilt function of fromkeys() can also be used to perform this particular task which is made to perform this particular task itself and is more Pythonic way to perform this task.
# Python3 code to demonstrate working of# Initialize dictionary with common value# Using fromkeys()  # Initialize listtest_list = ['gfg', 'is', 'best']  # printing original listprint("The original list is : " + str(test_list))  # Initialize dictionary with common value# Using fromkeys()res = dict.fromkeys(test_list, 4)  # printing resultprint("The constructed dictionary with common value : " + str(res))
The original list is : ['gfg', 'is', 'best']
The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to wrap tables with div element using jQuery?

To wrap tables with div element, use the wrap() method. You can try to run the following code to wrap tables with div element using jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 
     $("#button1").click(function(){
        $('table').wrap('<div></div>');
    });
   
});
</script>
<style>
 div {
  background-color: gray;
 }
</style>
</head>
<body>

 <table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Will</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

<button id="button1">Wrap</button>

</body>
</html>
Fetch date record that equals today in MySQL

For this, compare the date records with the current date using the CURDATE() method. Let us first create a table −
mysql> create table DemoTable
(
   RegistrationLastDate datetime
);
Query OK, 0 rows affected (0.61 sec)
Let’s say the current date is −
2019-09-03
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-08-01');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-09-03 9:50:56');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2019-09-03');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-09-02');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2019-09-02 9:50:00');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------------+
| RegistrationLastDate |
+----------------------+
| 2019-08-01 00:00:00  |
| 2019-09-03 09:50:56  |
| 2019-09-03 00:00:00  |
| 2019-09-02 00:00:00  |
| 2019-09-02 09:50:00  |
+----------------------+
5 rows in set (0.00 sec)
Following is the query to fetch data record that equals today. Here, we are comparing all the records with the current date using the CURDATE() method −
mysql> select *from DemoTable where DATE(RegistrationLastDate)=curdate();
This will produce the following output −
+----------------------+
| RegistrationLastDate |
+----------------------+
| 2019-09-03 09:50:56  |
| 2019-09-03 00:00:00  |
+----------------------+
2 rows in set (0.01 sec)
PHP | DOMXPath query() Function - GeeksforGeeks

13 Mar, 2020
The DOMXPath::query() function is an inbuilt function in PHP which is used to evaluate the given XPath expression.
Syntax:
DOMNodeList DOMXPath::query( string $expression, 
       DOMNode $contextnode, bool $registerNodeNS )
Parameters: This function accept three parameters as mentioned above and described below:
$expression: It specifies the XPath expression to execute.
$contextnode (Optional): It specifies the optional contextnode for doing relative XPath queries. By default, the queries are relative to the root element.
$registerNodeNS (Optional): It specifies the optional registerNodeNS to disable automatic registration of the context node.
Return Value: This function returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.
Below given programs illustrate the DOMXPath::query() function in PHP:
Program 1: In this program we will fetch all the element values of elements with name content.
<?php  // Create a new DOMDocument instance$document = new DOMDocument();  // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><root>    <content>        First    </content>    <content>        Second    </content>    <content>        Third    </content></root>XML;  // Load the XML$document->loadXML($xml);  // Create a new DOMXPath instance$xpath = new DOMXPath($document);  // Get the root element$tbody = $document->getElementsByTagName('root')->item(0);  // Get all the element with name content$query = '//content';  // Execute the query$entries = $xpath->query($query);  foreach ($entries as $entry) {    echo $entry->nodeValue . "<br>";}?>
Output:
First
Second
Third
Program 2: In this program we will count all the elements with name h1.
<?php// Create a new DOMDocument instance$document = new DOMDocument();  // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><root>    <h1>        Hello    </h1>    <h1>        World    </h1>    <h1>        Foo    </h1>    <h1>        Bar    </h1></root>XML;  // Load the XML$document->loadXML($xml);  // Create a new DOMXPath instance$xpath = new DOMXPath($document);  // Get the root element$tbody = $document->getElementsByTagName('root')->item(0);  // Get all the element with name h1$query = '//h1';  // Execute the query$entries = $xpath->query($query);  // Count the number of headingsecho count($entries);?>
Output:
4
Reference: https://www.php.net/manual/en/domxpath.query.php
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to track the position of the face in OpenCV using C++?

When we want to track the position of the face, it is better to enclose the face with ellipse because an ellipse has a center. This center is also the center point of the detected face. As result, tracking the position of detected face becomes more accurate.
The following program tracks the center of detected face and show the position in console window −
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
//This header includes definition of 'rectangle()' function//
#include<opencv2/objdetect/objdetect.hpp>
//This header includes the definition of Cascade Classifier//
#include<string>
using namespace std;
using namespace cv;
int main(int argc, char** argv){
   Mat image_with_humanface;//Declaring a matrix to load image with human faces//
   image_with_humanface = imread("person.jpg");//loading an image that contains human face in it//
   namedWindow("Face Detection");//Declaring an window to show the result//
   string trained_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";//Defining the location our XML Trained Classifier in a string//
   CascadeClassifier faceDetector;//Declaring an object named 'face detector' of CascadeClassifier class//
   faceDetector.load(trained_classifier_location);//loading the XML trained classifier in the object//
   vector<Rect>faces;//Declaring a rectangular vector named faces//
   faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE,Size(20,20));//Detecting the faces in 'image_with_humanfaces' matrix//
   for (int i = 0; i < faces.size(); i++){ //Initiating for loop to detect the largest face//
      Point center(faces[i].x + faces[i].width * 0.5, faces[i].y + faces[i].height * 0.5);//getting the center of the face//
      ellipse(image_with_humanface, center, Size(faces[i].width * 0.5, faces[i].height * 0.5), 0, 0, 360, Scalar(255, 0, 255), 4, 8, 0);//draw an ellipse on the face//
      int horizontal = (faces[i].x + faces[i].width * 0.5);//Getting the horizontal value of coordinate//
      int vertical = (faces[i].y + faces[i].width * 0.5);//Getting the vertical value of coordinate//
   }
   cout << "Position of the face is at(x,y)=" << " ("<<CAP_PROP_XI_DECIMATION_HORIZONTAL<<","<<CAP_PROP_XI_DECIMATION_VERTICAL<<")"<< endl;//
   imshow("Face Detection", image_with_humanface);//Showing the largest face face//
   waitKey(0);//To wait for keystroke to terminate the program
   return 0;
}
Change Data Type for one or more columns in Pandas Dataframe

In this tutorial, we are going to learn about the conversion of one or more columns data type into another data type. We are going to use the method DataFrame.astype() method.
We have to pass any data type from Python, Pandas, or Numpy to change the column elements data types. We can also give a dictionary of selected columns to change particular column elements data types. Let's see the examples with code.
# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# we will change the data type of all columns to str
data_frame = data_frame.astype(str)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)
All the column data types changed to str objects. If you run the above program, you will get the following results.
No     object
Name   object
Age    object
dtype: object
Now, let's try to change the data type of Age column from int to str. We have to create a dictionary specifying column name and desired data type.
# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# creating a dictionary with column name and data type
data_types_dict = {'Age': str}
# we will change the data type of Age column to str by giving the dict to the astype method
data_frame = data_frame.astype(data_types_dict)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)
If you see the output, only the Age column data type is changed from int to str. See the result below.
No      int64
Name   object
Age    object
dtype: object
If you face any difficulties in following the tutorial, mention them in the comment section.
Instruction type DCX rp in 8085 Microprocessor

In 8085 Instruction set, DCX is a mnemonic that stands for “DeCrementeXtended register” and rp stands for register pair. And it can be any one of the following register pairs −
rp = BC, DE, or HL

This instruction will be used to subtract 1 from the present content of the rp. And thus the result of the decremented content will remain stored in rp itself. Though, it is an arithmetic instruction, note that flags are not at all affected by the execution of this instruction. A register pair is generally used to store 16-bit memory address. If flag bits got affected during decrement of a memory address, then it may cause problems in many cases. So as per design of 8085, flag bits are not getting affected by the execution of this instruction DCXrp.
As rp can have any one of the three values, there are three opcodes for this type of instruction. It occupies only 1-Byte in memory.
Let us consider DCX B as a sample instruction falling in this category. As it is a 1-Byte instruction, so it will occupy single 1-Byte location in the memory. Let us consider that the initial content of register pair BC is 4055H. So after execution of the instruction DCX B, the new content of BC register pair would be 4054H. The result of execution of this instruction is shown below with the help of a tracing table −
(BC)
We may think that DCX B is similar to DCR C in this example. But that is not true. As if the initial content of BC register pair be 2000H then after DCR C instruction execution it would be 20FFH not 1FFFH.So, basically, DCX instruction decrements a 16-bit quantity, whereas DCR decrements an 8-bit quantity.
Here is the timing diagram of the instruction execution DCX B as below −
Summary − So this instruction DCX B requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 6 T-States for execution as shown in the timing diagram.
Finding IP address of a URL in Java - GeeksforGeeks

09 Nov, 2021
Prerequisite: InetAddressgetByName() : Returns the InetAddress of the given host. If the host is a literal IP address, then only its validity is checked. Fetches public IP Address of the host specified. It takes the host as an argument and returns the corresponding IP address.
Examples: 
Input : www.google.com
Output : 216.58.199.164

Input : localhost
Output : 127.0.0.1
Below programs illustrate how to fetch public IP addresses:
Note: These programs won’t run on online compilers. Use offline compilers like Netbeans, Eclipse, etc, instead.
Program 1: Fetch IP address of any URL 
Java
// Java program to demonstrate// how to fetch public IP Addressimport java.net.*;import java.*; class GFG {    public static void main(String args[])        throws UnknownHostException    {        // The URL for which IP address needs to be fetched        String s = "https:// www.google.com/";         try {            // Fetch IP address by getByName()            InetAddress ip = InetAddress.getByName(new URL(s)                                                       .getHost());             // Print the IP address            System.out.println("Public IP Address of: " + ip);        }        catch (MalformedURLException e) {            // It means the URL is invalid            System.out.println("Invalid URL");        }    }}
Output: 
Public IP Address of: www.google.com/216.58.196.164
Program 2: Fetch the public IP address of one’s systemTo find public IP, use http://bot.whatismyipaddress.com. It is an online utility, to find the system’s public IP. Open the URL, read a line and print the line. 
Java
// Java program to demonstrate// how to fetch public IP Addressimport java.net.*;import java.*; class GFG {    public static void main(String args[])        throws UnknownHostException    {        String systemipaddress = "";        try {            URL url_name = new URL("http://bot.whatismyipaddress.com");             BufferedReader sc = new BufferedReader(                new InputStreamReader(url_name.openStream()));             // reads system IPAddress            systemipaddress = sc.readLine().trim();        }        catch (Exception e) {            systemipaddress = "Cannot Execute Properly";        }        // Print IP address        System.out.println("Public IP Address: "                           + systemipaddress + "\n");    }}
Output: 
Public IP Address: 103.62.239.242
 
vaibhavsinghtanwar
Java-Networking
Computer Networks
Java
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
PyQt5 - QList Widget

QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable.
Following are the frequently used methods of QListWidget class −
addItem()
Adds QListWidgetItem object or string in the list
addItems()
Adds each item in the list
insertItem()
Inserts item at the specified index
clear()
Removes contents of the list
setCurrentItem()
Sets currently selected item programmatically
sortItems()
Rearranges items in ascending order
Following are the signals emitted by QListWidget −
currentItemChanged()
Whenever current item changes
itemClicked()
Whenever an item in the list is clicked
The following example shows the click event being captured to pop up a message box.
from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys

class myListWidget(QListWidget):
   def Clicked(self,item):
      QMessageBox.information(self, "ListWidget", "You clicked: "+item.text())
		
def main():
   app = QApplication(sys.argv)
   listWidget = myListWidget()
	
   #Resize width and height
   listWidget.resize(300,120)
	
   listWidget.addItem("Item 1"); 
   listWidget.addItem("Item 2");
   listWidget.addItem("Item 3");
   listWidget.addItem("Item 4");
	
   listWidget.setWindowTitle('PyQT QListwidget Demo')
   listWidget.itemClicked.connect(listWidget.Clicked)
   
   listWidget.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output. Status bar shows caption of selected menu button −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Number Divisibility - GeeksforGeeks

13 May, 2016
All 3 digit numbers divisible by 3 are :
102, 105, 108, 111, ..., 999.

This is an A.P. with first element 'a' as 
102 and difference  'd' as 3.

Let it contains n terms. Then,
102 + (n - 1) x 3 = 999 
102 + 3n-3 = 999
3n = 900 or n = 300
Sum of AP = n/2 [2*a  + (n-1)*d]
Required sum = 300/2[2*102 + 299*3] = 165150. 
In case of 546702 last 2 digits are 02 (x)
In case of 556824 last 2 digits are 24 (/)
In case of 367312 last 2 digits are 12 (/)
In case of 467536 last 2 digits are 36 (/) 
9 + 8 + 5 + * + 8 + 6 + 5 = 9x
41 + * = 9x
Nearest value of 9x must be 45
41 + * = 45
* = 4
LCM of 15, 20 and 36 is 180

Now 180 = 3 x 3 x 2 x 2 x 5

To make it perfect square, it must
be multiplied from 5.

So required no. = 32 x 22 x 52 = 900
The required numbers are 27, 36, 45......450.

This is an A.P. with a = 27 and d = 9

Let it has n terms.

Then Tn = 450 = 27 + (n-1) x9

∴ 450 = 27+ 9n - 9

∴ 9n = 432

∴ n = 48
Let us divide 4000 by 17.

17) 4000 (235
       34
       ....
         60
         51
        .....
           90
           85
          .....
             5

We get 5 as remainder.
Number to be added = 17-5 = 12
Let us divide 5000 by 23.

23) 5000 (217
      46
      ....
        40
        23
        ....
         170
         161
         .....
            9

We get 9 as remainder.

Therefore required number to be subtracted = 9
The required number must be divisible by L.C.M. of 5,6 and 7.
L.C.M. of 5, 6 and 7 = 5 x 6 x 7 = 210

Let us divide 9999 by 210.

210) 9999 (47
      840
     ----
      1599
      1470
      ----
       129

Required number = 9999 – 129 = 9870
Pattern is (22- 1), (32- – 1), (42- – 1), (52- – 1), ....

Next number will be = 72- – 1 = 49 – 1 = 48
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
How to sort collection of MongoDB Database in descending order using Node.js ? - GeeksforGeeks

12 Jan, 2021
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).
MongoDB Module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. (Refer to this article).
sort() Method of MongoDB is used for sorting the documents. This method is used to define the ordering of the documents.
Collection’s particular key  in ascending order
{Collection's key:-1}
Installing module:
npm install mongodb
Project structure:
Running the server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB database:
Database name:GFG
Collection name:aayush
Index.js
Javascript
const mongoclient = require("mongodb");const url = "mongodb://localhost:27017/"  // Database nameconst databasename = "GFG"  // Connecting to MongoDBmongoclient.connect(url).then((db) => {    const connect = db.db(databasename);      // Connecting to collection    const collection = connect.collection("aayush");    console.log("Connection Created")      // Sort the document key    const sort = { rollno: -1 }      collection.find().sort(sort).toArray((err, ans,) => {        if (!err) {              // Printing the documents            console.log(ans);        }    })  }).catch((err) => {    console.log(err.Message);})
Execution command:
node index.js
Console Output:
MongoDB-method
Node.js-Misc
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to get length of a list of lists in Python?

You can employ a nested loop to count number of elements in each sublist of a list
>>> a=[[1, 2, 3], [4, 5, 6]]
>>> c=0
>>> for x in a:
      for y in x:
      c=c+1


>>> c
6
Matplotlib - Subplot2grid() Function

This function gives more flexibility in creating an axes object at a specific location of the grid. It also allows the axes object to be spanned across multiple rows or columns.
Plt.subplot2grid(shape, location, rowspan, colspan)
In the following example, a 3X3 grid of the figure object is filled with axes objects of varying sizes in row and column spans, each showing a different plot.
import matplotlib.pyplot as plt
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
import numpy as np
x = np.arange(1,10)
a2.plot(x, x*x)
a2.set_title('square')
a1.plot(x, np.exp(x))
a1.set_title('exp')
a3.plot(x, np.log(x))
a3.set_title('log')
plt.tight_layout()
plt.show()
Upon execution of the above line code, the following output is generated −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Generate Color Vectors of desired Length in R Programming - rainbow() Function - GeeksforGeeks

30 Jun, 2020
rainbow() function in R Language is a built in color palettes which can be used to quickly generate color vectors of desired length taken as the parameter and returns the hexadecimal code of the colours available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and 00 is transparent).
Syntax: rainbow(n)
Parameters:n: desired length of the returned color vector
Example 1:
# R program to illustrate# rainbow function  # Calling rainbow() functionrainbow(2)rainbow(4)rainbow(6)
Output:
[1] "#FF0000FF" "#00FFFFFF"
[1] "#FF0000FF" "#80FF00FF" "#00FFFFFF" "#8000FFFF"
[1] "#FF0000FF" "#FFFF00FF" "#00FF00FF" "#00FFFFFF" "#0000FFFF" "#FF00FFFF"

Example 2:
# R program to illustrate# rainbow function  # Using rainbow() function to# plot 6 different colorbarplot(1:6, col = rainbow(6))
Output:
R Vector-Function
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
XML-RPC - Data Model

The XML-RPC specification defines six basic data types and two compound data types that represent combinations of types.
<int>27</int>
<i4>27</i4>
<double>27.31415</double>
<double>-1.1465</double>
<boolean>1</boolean>
<boolean>0</boolean>
<string>Hello</string>
<string>bonkers! @</string>
<dateTime.iso8601>
20021125T02:20:04
</dateTime.iso8601>
<dateTime.iso8601>
20020104T17:27:30
</dateTime.iso8601>
<base64>SGVsbG8sIFdvcmxkIQ==</base64>
These basic types are always enclosed in value elements. Strings (and only strings) may be enclosed in a value element but omit the string element. These basic types may be combined into two more complex types, arrays, and structs. Arrays represent sequential information, while structs represent name-value pairs, much like hashtables, associative arrays, or properties.
Arrays are indicated by the array element, which contains a data element holding the list of values. Like other data types, the array element must be enclosed in a value element. For example, the following arraycontains four strings:
<value>
   <array>
      <data>
         <value><string>This </string></value>
         <value><string>is </string></value>
         <value><string>an </string></value>
         <value><string>array.</string></value>
      </data>
   </array>
</value>
The following array contains four integers:
<value>
   <array>
      <data>
         <value><int>7</int></value>
         <value><int>1247</int></value>
         <value><int>-91</int></value>
         <value><int>42</int></value>
      </data>
   </array>
</value>
Arrays can also contain mixtures of different types, as shown here:
<value>
   <array>
      <data>
         <value><boolean>1</boolean></value>
         <value><string>Chaotic collection, eh?</string></value>
         <value><int>-91</int></value>
         <value><double>42.14159265</double></value>
      </data>
   </array>
</value>
Creating multidimensional arrays is simple - just add an array inside of an array:
<value>
   <array>
      <data>
		
         <value>
            <array>
               <data>
                  <value><int>10</int></value>
                  <value><int>20</int></value>
                  <value><int>30</int></value>
               </data>
            </array>
         </value>
			
         <value>
            <array>
               <data>
                  <value><int>15</int></value>
                  <value><int>25</int></value>
                  <value><int>35</int></value>
               </data>
            </array>
         </value>
			
      </data>
   </array>
</value>
A simple struct might look like:
<value>
   <struct>
      <member>
         <name>givenName</name>
         <value><string>Joseph</string></value>
      </member>
		
      <member>
         <name>familyName</name>
         <value><string>DiNardo</string></value>
      </member>
		
      <member>
         <name>age</name>
         <value><int>27</int></value>
      </member>
   </struct>
</value>
This way you can implement almost all data types supported by any programming language.
 Print
 Add Notes
 Bookmark this page
C Program to find maximum occurrence of character in a string

An array of characters is called a string.
Following is the declaration declaring an array is as follows −
char stringname [size];
For example: char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
The logic to find the maximum occurrence of character is −
First, find frequency of characters, by using the following program.
while(string[i] != '\0'){
   value = (int)string[i];
   frequency[value] += 1;
   i++;
}
Based on this, we are finding maximum occurrence character.
maximum = 0;
for(i=0; i<CHARS; i++){
   if(frequency[i] > frequency[maximum])
      maximum = i;
}
Given below is the C program to find max occurring character in a string −
 Live Demo
#include <stdio.h>
#define SIZE 100 // Maximum string size
#define CHARS 255 // Maximum characters allowed
int main(){
   char string[SIZE];
   int frequency[CHARS];
   int i = 0, maximum;
   int value;
   printf("Enter the string:\n ");
   gets(string);
   for(i=0; i<CHARS; i++){
      frequency[i] = 0; // initialize freq of all characters to zero
   }
   /* Finds frequency of each characters */
   i=0;
   while(string[i] != '\0'){
      value = (int)string[i];
      frequency[value] += 1;
      i++;
   }
   /* Finds maximum frequency */
   maximum = 0;
   for(i=0; i<CHARS; i++){
      if(frequency[i] > frequency[maximum])
         maximum = i;
      }
      printf("Maximum occurrence character is '%c' = %d times.", maximum,
      frequency[maximum]);
   return 0;
}
When the above program is executed, it produces the following result −
Enter the string:
tutorials point
Maximum occurrence character is 't' = 3 times.
When should we write our own assignment operator in C++?

Here we will see when we need to create own assignment operator in C++. If a class do not have any pointers, then we do not need to create assignment operator and copy constructor. C++ compiler creates copy constructor and assignment operator for each class. If the operators are not sufficient, then we have to create our own assignment operator.
 Live Demo
#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
   void setValue (int x) {
      *ptr = x;
   }
   void print() {
      cout << *ptr << endl;
   }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}
100
In the main() function, we have set the value of x using setValue() method for ob1. The value is also reflected in object ob2; This type of unexpected changes may generate some problems. There is no user defined assignment operator, so compiler creates one. Here it copies the ptr of RHS to LHS. So both of the pointers are pointing at the same location.
To solve this problem, we can follow two methods. Either we can create dummy private assignment operator to restrict object copy, otherwise create our own assignment operator.
 Live Demo
#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
   void setValue (int x) {
      *ptr = x;
   }
   void print() {
      cout << *ptr << endl;
   }
   MyClass &operator=(const MyClass &ob2) {
      // Check for self assignment
      if(this != &ob2)
         *ptr = *(ob2.ptr);
      return *this;
   }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}
50
Here the assignment operator is used to create deep copy and store separate pointer. One thing we have to keep in mind. We have to check the self-reference otherwise the assignment operator may change the value of current object.
How to Create Modules in Node.js ? - GeeksforGeeks

11 May, 2020
Modules are the collection of JavaScript codes in a separate logical file that can be used in external applications on the basis of their related functionality. Modules are popular as they are easy to use and are reusable.
To create a module in Node.js, you will need the exports keyword. This keyword tells Node.js that the function can be used outside the module.
Syntax:
exports.function_name = function(arg1, arg2, ....argN) {
    // function body
};  

Example of a custom node module:
Create a file that you want to export// File name: calc.js  exports.add = function (x, y) {    return x + y;};  exports.sub = function (x, y) {    return x - y;};  exports.mult = function (x, y) {    return x * y;};  exports.div = function (x, y) {    return x / y;};
// File name: calc.js  exports.add = function (x, y) {    return x + y;};  exports.sub = function (x, y) {    return x - y;};  exports.mult = function (x, y) {    return x * y;};  exports.div = function (x, y) {    return x / y;};
Use the ‘require’ keyword to import the file// File name: App.jsvar calculator = require('./calc');  var x = 50, y = 20;  console.log("Addition of 50 and 20 is "                   + calculator.add(x, y));  console.log("Subtraction of 50 and 20 is "                   + calculator.sub(x, y));  console.log("Multiplication of 50 and 20 is "                   + calculator.mult(x, y));  console.log("Division of 50 and 20 is "                    + calculator.div(x, y));
// File name: App.jsvar calculator = require('./calc');  var x = 50, y = 20;  console.log("Addition of 50 and 20 is "                   + calculator.add(x, y));  console.log("Subtraction of 50 and 20 is "                   + calculator.sub(x, y));  console.log("Multiplication of 50 and 20 is "                   + calculator.mult(x, y));  console.log("Division of 50 and 20 is "                    + calculator.div(x, y));
Output:Addition of 50 and 20 is 70
Subtraction of 50 and 20 is 30
Multiplication of 50 and 20 is 1000
Division of 50 and 20 is 2.5

Addition of 50 and 20 is 70
Subtraction of 50 and 20 is 30
Multiplication of 50 and 20 is 1000
Division of 50 and 20 is 2.5

Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to add Track-bar in OpenCV using C++?

Track-bars are controllable bars which are used to control various parameters in OpenCV. Using track-bars, we can make it easier and change the parameters graphically. Track-bar removes this limitation and enables to create of dynamic effects using OpenCV.
The following program demonstrates how to add track-bars in OpenCV using C++.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat original;//Declaring a matrix//
   original = imread("sky.jpg");//loading the image in the matrix//
   namedWindow("Slider");//Declaring window to show the image//
   int light = 50;//starting value of the trackbar//
   createTrackbar("Brightness", "Slider", &light, 100);//creating a trackbar//
   int contrast = 50;//starting value of the trackbar//
   createTrackbar("Contrast", "Slider", &contrast, 100);//creating a trackbar//
   while (true) {
      Mat edit;//declaring a matrix//
      int Brightness = light - 50;//interaction with trackbar//
      double Contrast = contrast / 50.0;//interaction with trackbar//
      original.convertTo(edit, -1, Contrast, Brightness);//implement the effect of change of trackbar//
      waitKey(50);
   }
   return(0);
}
How to check if a variable is NULL in C/C++?

In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.
Here we will see one program. We will try to open a file in read mode, that is not present in the system. So the function will return null value. We can check it using if statement. See the code for better understanding.
#include <stdio.h>
main() {
   //try to open a file in read mode, which is not present
   FILE *fp;
   fp = fopen("hello.txt", "r");
   if(fp == NULL)
      printf("File does not exists");
   fclose(fp);
}
File does not exists