code-rag-bench/online-tutorials huggingface dataset:
Remove infinite values from a given Pandas DataFrame

26 Jul, 2020
Let’s discuss how to Remove the infinite values from the Pandas dataframe.  First let’s make a dataframe:
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np  # Create a dictionary for the dataframedict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel',                 'Sanskriti', 'Abhishek Jain'],        'Age': [22, 20, np.inf, -np.inf, 22],         'Marks': [90, 84, 33, 87, 82]}  # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict)  # Print Dataframedf
Output:  
 
Method 1: Replacing infinite with Nan and then dropping rows with Nan
We will first replace the infinite values with the NaN values and then use the dropna() method to remove the rows with infinite values. df.replace() method takes 2 positional arguments. First is the list of values you want to replace and second with which value you want to replace the values.  
Python3
# Replacing infinite with nandf.replace([np.inf, -np.inf], np.nan, inplace=True)  # Dropping all the rows with nan valuesdf.dropna(inplace=True)  # Printing dfdf
Output:  
 
Method 2: Changing Pandas option to consider infinite as Nan
Pandas provide the option to use infinite as Nan. It makes the whole pandas module to consider the infinite values as nan.  We can do this by using pd.set_option(). It sets the option globally throughout the complete Jupyter Notebook. Syntax:
pd.set_option('mode.use_inf_as_na', True)

It sets the options to use infinite as a Nan value throughout the session or until the options are not set back to the False.  
Python3
# Changing option to use infinite as nanpd.set_option('mode.use_inf_as_na', True)  # Dropping all the rows with nan valuesdf.dropna(inplace=True)  # Printing dfdf
Output:  
 
Method 3: Consider infinite as Nan but using option_context
Instead of using pd.set_options(), which sets the option globally, we can use pd.option_context(), which changes option within the certain scope only. 
Python3
# Changing option to use infinite as nanwith pd.option_context('mode.use_inf_as_na', True):        # Dropping the rows with nan     # (or inf) values    df.dropna(inplace=True)  # Printing dfdf
Output:  
 
Method 4: Using the filter
We will first create a filter which returns a boolean dataframe and use this filter to mask the infinite values.  
Python3
# Creating filterdf_filter = df.isin([np.nan, np.inf, -np.inf])  # Masking df with the filterdf = df[~df_filter]  # Dropping rows with nan valuesdf.dropna(inplace=True)  # Printing dfdf
Output:  
 
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

HTML Input attributes
Tryit: The multiple attribute
How to handle jQuery AJAX success event?

To handle jQuery AJAX success event, use the ajaxSuccess() method. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.
Here is the description of all the parameters used by this method −
callback − The function to execute. The event object, XMLHttpRequest, and settings used for that request are passed as arguments to the callback.
Let’s say we have the following HTML content in result.html −
<h1>THIS IS RESULT...</h1>
The following is an example showing the usage of this method −
Live Demo
<html>

   <head>
      <title>jQuery ajaxSuccess() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            /* Global variable */
            var count = 0;

            $("#driver").click(function(event){
               $('#stage0').load('result.html');
            });
               
            /* Gets called when request starts */
            $(document).ajaxStart(function(){
               count++;
               $("#stage1").html("<h1>Starts, Count :" + count + "</h1>");
            });
               
            /* Gets called when request is sent */
            $(document).ajaxSend(function(evt, req, set){
               count++;
               $("#stage2").html("<h1>Sends, Count :" + count + "</h1>");
               $("#stage2").append("<h1>URL :" + set.url  + "</h1>");
            });
               
            /* Gets called when request completes */
            $(document).ajaxComplete(function(event,request,settings){
               count++;
               $("#stage3").html("<h1>Completes,Count:" + count + "</h1>");
            });
               
            /* Gets called when request is stopped */
            $(document).ajaxStop(function(event,request,settings){
               count++;
               $("#stage4").html("<h1>Stops, Count :" + count + "</h1>");
            });
               
            /* Gets called when all request completes successfully */
            $(document).ajaxSuccess(function(event,request,settings){
               count++;
               $("#stage5").html("<h1>Success,Count :" + count + "</h1>");
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage0" style = "background-color:blue;">
         STAGE - 0
      </div>
       
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
       
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
       
      <div id = "stage3" style = "background-color:blue;">
         STAGE - 3
      </div>
       
      <div id = "stage4" style = "background-color:blue;">
         STAGE - 4
      </div>
       
      <div id = "stage5" style = "background-color:blue;">
         STAGE - 5
      </div>
       
      <input type = "button" id = "driver" value="Load Data" />
       
   </body>
</html>
Java Examples - Search in a String

How to search a word inside a string ?
This example shows how we can search a word within a String object using  indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.
public class SearchStringEmp{
   public static void main(String[] args) {
      String strOrig = "Hello readers";
      int intIndex = strOrig.indexOf("Hello");
      
      if(intIndex == - 1) {
         System.out.println("Hello not found");
      } else {
         System.out.println("Found Hello at index " + intIndex);
      }
   }
}
The above code sample will produce the following result.
Found Hello at index 0

This example shows how we can search a word within a String object
public class HelloWorld {
   public static void main(String[] args) {
      String text = "The cat is on the table";
      System.out.print(text.contains("the"));
   }
}
The above code sample will produce the following result.
true

 Print
 Add Notes
 Bookmark this page
Angular 4 - Overview

There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1.
The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2.
Angular 4 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4.
Let us now see the new features and the changes made in Angular 4.
The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4.
Let us now see the new features added to Angular 4 −
Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template.
<span *ngIf="isavailable; else condition1">Condition is valid.</span>
<ng-template #condition1>Condition is invalid</ng-template>

With the help of as keyword you can store the value as shown below −
<div *ngFor="let i of months | slice:0:5 as total">
   Months: {{i}} Total: {{total.length}}
</div>

The variable total stores the output of the slice using the as keyword.
Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect.
Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4.
Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project.
Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase.
<div>
   <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2>
</div>

The above line of code generates the following output – Angular 4 Titlecase.
Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2.
Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to get file extension in Python? - GeeksforGeeks

16 Nov, 2020
In Python, we can extract the file extension using either of the two different approaches discussed below –
Method 1: Using Python os module splitext() function
This function splits the file path string into file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path). This function is preferred to use when the OS module is being used already.
Example:
Python3
import os    # this will return a tuple of root and extensionsplit_tup = os.path.splitext('my_file.txt')print(split_tup)  # extract the file name and extensionfile_name = split_tup[0]file_extension = split_tup[1]  print("File Name: ", file_name)print("File Extension: ", file_extension)
Output:
('my_file', '.txt')
File Name:  my_file
File Extension:  .txt
Method 2: Using Pathlib module
pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach.
Example:
Python3
import pathlib  # function to return the file extensionfile_extension = pathlib.Path('my_file.txt').suffixprint("File Extension: ", file_extension)
Output:
File Extension:  .txt
Python file-handling-programs
Python OS-path-module
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
How to connect ODBC Database with PHP?

03 Feb, 2021
The Microsoft Open Database Connectivity (ODBC) is a C application programming language interface. So the applications can access data from different database management systems.  The designers of ODBC aimed to make it independent of database systems and operating systems. In this article, we are using the Microsoft Access database to establish a connection.
Requirements: If ODBC Drivers are installed or the old version is installed, then update to the latest version or install the driver first 
Start XAMPP server by starting Apache
Write PHP script for Access database connection.
Run it in a local browser.
The database is successfully connected.
Steps to follow for ODBC connection to an MS Access Database:
Open the Administrative tools icon in your control panel
Double-click on the Data Sources (ODBC) icon inside.
Choose the System DSN tab.
                               
Click on Add in the System DSN tab.
Select the Microsoft Access Driver, Click Finish
In the next screen, click on select to locate the database
Give the database a Data Source Name (DSN) as shown in the above image. Click ok.
Example: The following example demonstrates the simple connection script.
PHP
<!DOCTYPE html><html> <body> <?php   //Storing DSN(Data Source Name created)  $dsn="raj";  $user="root";  $password="";       //storing connection id in $conn  $conn=odbc_connect($dsn,$user, $password);   //Checking connection id or reference  if (!$conn)   {   echo (die(odbc_error()));   }   else  {      echo "Connection Successful !";  }  //Resource releasing  odbc_close($conn);  ?> </body></html>
 Below output will be shown on the browser
Output: 
Connection Successful !
 
coder36
PHP-Misc
PHP
PHP Programs
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between HTTP GET and POST Methods
How to fetch data from localserver database and display on HTML table using PHP ?
PHP Cookies
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
Refresh a page using PHP
PHP | Ternary Operator
HTML <code> Tag

17 Mar, 2022
The <code> tag in HTML is used to define the piece of computer code. During the creation of web pages sometimes there is a need to display computer programming code. It could be done by any basic heading tag of HTML but HTML provides a separated tag which is <code>. 
The code tag is a specific type of text which represents computer output. HTML provides many methods for text-formatting but <code> tag is displayed with fixed letter size, font, and spacing.
Some points about <code> tag: 
It is mainly used to display the code snippet into the web browser.
This tag styles its element to match the computer’s default text format.
The web browsers by default use a monospace font family for displaying <code< tags element content.
Syntax: 
<code> Contents... </code>
The below examples illustrates the HTML code Tag.
Example 1: 
HTML
<!DOCTYPE html><html> <body>    <pre><!--code Tag starts here -->      <code>#include<stdio.h>int main() {    printf("Hello Geeks");}<!--code Tag starts here -->      </code>    </pre></body> </html>
Output:
Example 2: 
HTML
<!DOCTYPE html><html> <body>    <pre><!--code Tag starts here -->        <code>        class GFG        {            // Program begins with a call to main()            // Print "Hello, World" to the terminal window            public static void main(String args[])            {                System.out.println("Hello, World");            }        }<!--code Tag ends here -->        </code>     </pre> </body> </html>
Output: The program which is written inside the <code> tag has some different font size and font type to the basic heading tag and paragraph tag.
Note: <pre> tag is used to display code snippets because it always keeps the text formatting as it.Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to open a website in iOS's web browser from my application?

In this post we will learn how to open website in iOS browser.
We will open Facebook in iOS browser.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “OpenBrowser”
Step 2 − Open Main.storyboard and add a button as shown below. I have given the button title as “Open Facebook”
Step 3 − Attach one @IBAction function in ViewController, name it openBrowser
Step 4 − In openBrowserFunction write the code to open URL like shown below
@IBAction func openBrowsere(_ sender: Any) {
   let url = URL(string: "https://www.facebook.com")!
   if UIApplication.shared.canOpenURL(url) {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
   }
}
In the above code as you can see we are using canOpenURL and openURL APIs.
canOpenURL checks whether the given URL can be opened by the app. Then openURL actually opens the given URL with appropriate app.
Step 5 − Run the app. Click on open Facebook button. You should see the browser opening the Facebook page.
Difference between Maskable and Non Maskable Interrupt - GeeksforGeeks

14 May, 2020
An interrupt is an event caused by a component other than the CPU. It indicates the CPU of an external event that requires immediate attention. Interrupts occur asynchronously. Maskable and non-maskable interrupts are two types of interrupts.
1. Maskable Interrupt :An Interrupt that can be disabled or ignored by the instructions of CPU are called as Maskable Interrupt.The interrupts are either edge-triggered or level-triggered or level-triggered.
Eg: 
RST6.5,RST7.5,RST5.5 of 8085 
2. Non-Maskable Interrupt :An interrupt that cannot be disabled or ignored by the instructions of CPU are called as Non-Maskable Interrupt.A Non-maskable interrupt is often used when response time is critical or when an interrupt should never be disable during normal system operation. Such uses include reporting non-recoverable hardware errors, system debugging and profiling and handling of species cases like system resets.
Eg:
Trap of 8085 
Difference between maskable and nonmaskable interrupt :
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Computer Organization | RISC and CISC
Memory Hierarchy Design and its Characteristics
Direct Access Media (DMA) Controller in Computer Architecture
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Bootstrap Panels

A panel in bootstrap is a bordered box with some padding around its content:
Panels are created with the .panel class, and content inside the panel has a 
.panel-body class:
The .panel-default class is used to style the color of the 
panel. See the last example on this page for more contextual classes.
The .panel-heading class adds a heading to the panel:
The .panel-footer class adds a footer to the panel:
To group many panels together, wrap a <div> with class 
.panel-group around them.
The .panel-group class clears the bottom-margin of each panel:
To color the panel, use contextual classes (.panel-default, .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger):
Create a basic (default) Bootstrap Panel with the words: "Hello World".
<div class="">
  <div class="">Hello World</div>
</div>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Find most significant set bit of a number in C++

Here we will see if a number is given, then how to find the value of Most Significant Bit value, that is set. The value is power of 2. So if the number is 10, MSB value will be 8.
We have to find the position of MSB, then find the value of the number with a set-bit at kth position.
#include<iostream>
#include<cmath>
using namespace std;
int msbBitValue(int n) {
   int k = (int)(log2(n));
   return (int)(pow(2, k));
}
int main() {
   int n = 150;
   cout << "MSB bit value is: "<< msbBitValue(n);
}
MSB bit value is: 128
Python program for most frequent word in Strings List

When it is required to find the most frequent word in a list of strings, the list is iterated over and the ‘max’ method is used to get the count of the highest string.
Below is a demonstration of the same
from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]

print("The list is :")
print(my_list)

my_temp = defaultdict(int)

for sub in my_list:
   for word in sub.split():
      my_temp[word] += 1

result = max(my_temp, key=my_temp.get)

print("The word that has the maximum frequency :")
print(result)
The list is :
['python is best for coders', 'python is fun', 'python is easy to learn']
The word that has the maximum frequency :
python
The required packages are imported into the environment.
The required packages are imported into the environment.
A list of strings is defined and is displayed on the console.
A list of strings is defined and is displayed on the console.
A dictionary of integers is created and assigned to a variable.
A dictionary of integers is created and assigned to a variable.
The list of strings is iterated over and split based on spaces.
The list of strings is iterated over and split based on spaces.
The count of every word is determined.
The count of every word is determined.
The maximum of these values is determined using the ‘max’ method.
The maximum of these values is determined using the ‘max’ method.
This is assigned to a variable.
This is assigned to a variable.
This is displayed as output on the console.
This is displayed as output on the console.
Assigning Values to Variables in Python

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −
 Live Demo
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively.
This produces the following result −
100
1000.0
John
PostgreSQL - CURRENT_TIME Function - GeeksforGeeks

09 Dec, 2021
The PostgreSQL CURRENT_TIME function returns the current time and the currentthe time zone.
Syntax: CURRENT_TIME(precision)
Let’s analyze the above syntax:
The precision argument is used to set the precision of the returned TIMESTAMP type value in fractional seconds precision. By default the function returns a full available precision if not precision data is provided to the function.
The CURRENT_TIME function returns a TIME WITH TIME ZONE value. This value is nothing but the current time with the the current time zone.
Example 1:
The following statement can be used to get the current time:
SELECT CURRENT_TIME;
Output:
Example 2:
The following statement shows the process of using the CURRENT_TIME function with the precision of 2:
SELECT CURRENT_TIME(2);
Output:
Example 3:
The CURRENT_TIME function can also be used as the default value of the TIME columns. To demonstrate this, create a table named log:
CREATE TABLE log (
    log_id SERIAL PRIMARY KEY,
    message VARCHAR(255) NOT NULL,
    created_at TIME DEFAULT CURRENT_TIME,
    created_on DATE DEFAULT CURRENT_DATE
);
The log table has the created_at column whose default value is the value returned by the CURRENT_TIME function. Now insert some data to the demo table:
INSERT INTO log( message )
VALUES('Testing the CURRENT_TIME function');
Now verify if the row was inserted into the log table with the created_at column added correctly by using the following query:
SELECT * FROM log;
Output:
sooda367
simmytarika5
PostgreSQL-Date-function
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - LEFT JOIN
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Copy Table
PostgreSQL - Cursor
PostgreSQL - SELECT
PostgreSQL - Record type variable
PostgreSQL - Select Into
PostgreSQL - TEXT Data Type
SortedList with Examples in C#?

The SortedList class in C# represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.
Following are the properties of the SortedList class −
Following are some of the methods of the Sorted class −
Let us now see some examples −
To get the number of elements contained in the SortedList, the code is as follows −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      SortedList sortedList = new SortedList();
      sortedList.Add("A", "1");
      sortedList.Add("B", "2");
      sortedList.Add("C", "3");
      sortedList.Add("D", "4");
      sortedList.Add("E", "5");
      sortedList.Add("F", "6");
      sortedList.Add("G", "7");
      sortedList.Add("H", "8");
      sortedList.Add("I", "9");
      sortedList.Add("J", "10");
      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in sortedList) {
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
      sortedList.Clear();
      Console.WriteLine("Count of SortedList (updated) = "+sortedList.Count);
   }
}
This will produce the following output −
SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10
Count of SortedList (updated) = 0
To check if two SortedList objects are equal, the code is as follows −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      SortedList list1 = new SortedList();
      list1.Add("One", 1);
      list1.Add("Two ", 2);
      list1.Add("Three ", 3);
      list1.Add("Four", 4);
      list1.Add("Five", 5);
      list1.Add("Six", 6);
      list1.Add("Seven ", 7);
      list1.Add("Eight ", 8);
      list1.Add("Nine", 9);
      list1.Add("Ten", 10);
      Console.WriteLine("SortedList1 elements...");
      foreach(DictionaryEntry d in list1) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      SortedList list2 = new SortedList();
      list2.Add("A", "Accessories");
      list2.Add("B", "Books");
      list2.Add("C", "Smart Wearable Tech");
      list2.Add("D", "Home Appliances");
      Console.WriteLine("\nSortedList2 elements...");
      foreach(DictionaryEntry d in list2) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      SortedList list3 = new SortedList();
      list3 = list2;
      Console.WriteLine("\nIs SortedList2 equal to SortedList3? = "+list3.Equals(list2));
   }
}
This will produce the following output −
SortedList1 elements...
Eight  8
Five 5
Four 4
Nine 9
One 1
Seven  7
Six 6
Ten 10
Three  3
Two  2

SortedList2 elements...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
Is SortedList2 equal to SortedList3? = True
Mutex vs Semaphore

Mutex and Semaphore both provide synchronization services but they are not the same. Details about both Mutex and Semaphore are given below −
Mutex is a mutual exclusion object that synchronizes access to a resource. It is created with a unique name at the start of a program. The Mutex is a locking mechanism that makes sure only one thread can acquire the Mutex at a time and enter the critical section. This thread only releases the Mutex when it exits the critical section.
This is shown with the help of the following example −
wait (mutex);
.....
Critical Section
.....
signal (mutex);
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.
A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signaled by another thread. This is different than a mutex as the mutex can be signaled only by the thread that called the wait function.
A semaphore uses two atomic operations, wait and signal for process synchronization.
The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.
wait(S)
{
   while (S<=0);
   S--;
}
The signal operation increments the value of its argument S.
signal(S)
{
   S++;
}
There are mainly two types of semaphores i.e. counting semaphores and binary semaphores.
Counting Semaphores are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources.
The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0.
Area of a polygon with given n ordered vertices in C++

In this program, we have to find the area of a polygon. The coordinates of the vertices of this polygon are given. Before we move further lets brushup old concepts for a better understanding of the concept that follows.
The area is the quantitative representation of the extent of any two-dimensional figure.
Polygon is a closed figure with a given number of sides.
Coordinates of vertices are the value of points in the 2-d plane. For example (0,0).
Now, let's see the mathematical formula for finding the area.
Area = 1⁄2 [(x1y2 + x2y3 + ...... + x(n-1)yn + xny1) - (x2y1 + x3y2 + ....... + xny(n-1) + x1yn ) ]
Using this formula the area can be calculated,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
double areaOfPolygon(double x[], double y[], int n){
   double area = 0.0;
   int j = n - 1;
   for (int i = 0; i < n; i++){
      area += (x[j] + x[i]) * (y[j] - y[i]);
      j = i;
   }
   return abs(area / 2.0);
}
int main(){
   double X[] = {0, 1, 4, 8};
   double Y[] = {0, 2, 5, 9};
   int n = sizeof(X)/sizeof(X[0]);
   cout<<"The area is "<<areaOfPolygon(X, Y, n);
}
The area is 3.5
Select and Deselect Text Inside an Element using JavaScript

Following is the code to select and deselect text inside an element using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Select and Deselect Text Inside an Element</h1>
<div style="color: green;" class="result">
Here is some text inside the div
</div>
<button class="Btn">SELECT</button>
<button class="Btn">DESELECT</button>
<h3>Click on the above button to select/de-select text inside the div</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelectorAll(".Btn");
   BtnEle[0].addEventListener("click", () => {
      window.getSelection().selectAllChildren(resEle);
   });
   BtnEle[1].addEventListener("click", () => {
      window.getSelection().removeAllRanges();
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘SELECT’ button −
On clicking the ‘DESELECT’ button −
How to get attribute of an element when using the 'click' event in jQuery?

To get attribute of an element, use the attr() method in jQuery. You can try to run the following code to get attribute of an element using the ‘click’ event −
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(){
    $("button").click(function(){
        alert("Width of image: " + $("img").attr("width"));
    });
});
</script>
</head>
<body>

<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="284" height="280"><br>

<button>Get Width</button>

</body>
</html>
Namedtuple in Python

The NamedTuple is another class, under the collections module. Like the dictionary type objects, it contains keys and that are mapped to some values. In this case we can access the elements using keys and indexes.
To use it at first we need to import it the collections standard library module.
import collections

In this section we will see some functions of the NamedTuple class.
From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes.
The NamedTuple converts the field names as attributes. So using getattr() it is possible to get the data from that attribute.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add two employees
e1 = Employee('Asim', 'Delhi', '25000')
e2 = Employee('Bibhas', 'Kolkata', '30000')
#Access the elements using index
print('The name and salary of e1: ' + e1[0] + ' and ' + e1[2])
#Access the elements using attribute name
print('The name and salary of e2: ' + e2.name + ' and ' + e2.salary)
#Access the elements using getattr()
print('The City of e1 and e2: ' + getattr(e1, 'city') + ' and ' + getattr(e2, 'city'))
The name and salary of e1: Asim and 25000
The name and salary of e2: Bibhas and 30000
The City of e1 and e2: Delhi and Kolkata

There are some methods to convert other collections to NamedTuple. The _make() method can be used to convert an iterable object like list, tuple, etc to NamedTuple object.
We can also convert a dictionary type object to NamedTuple object. For this conversion, we need the ** operator.
NamedTuple can return the values with keys as OrderedDict type object. To make it OrderedDict, we have to use the _asdict() method.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#List of values to Employee
my_list = ['Asim', 'Delhi', '25000']
e1 = Employee._make(my_list)
print(e1)
#Dict to convert Employee
my_dict = {'name':'Bibhas', 'city' : 'Kolkata', 'salary' : '30000'}
e2 = Employee(**my_dict)
print(e2)
#Show the named tuple as dictionary
emp_dict = e1._asdict()
print(emp_dict)
Employee(name='Asim', city='Delhi', salary='25000')
Employee(name='Bibhas', city='Kolkata', salary='30000')
OrderedDict([('name', 'Asim'), ('city', 'Delhi'), ('salary', '25000')])

There are some other method like _fields() and _replace(). Using the _fields() method we can check what are the different fields of NamedTuple. The _replace() method is used to replace the value of some other value.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add an employees
e1 = Employee('Asim', 'Delhi', '25000')
print(e1)
print('The fields of Employee: ' + str(e1._fields))
#replace the city of employee e1
e1 = e1._replace(city='Mumbai')
print(e1)
Employee(name='Asim', city='Delhi', salary='25000')
The fields of Employee: ('name', 'city', 'salary')
Employee(name='Asim', city='Mumbai', salary='25000')
Print all possible combinations of r elements in a given array of size n in C++

In this problem, we are given an array of size n and a positive integer r. Our
task is to print all possible combinations of the elements of the array of size
r.
Let’s take an example to understand the problem −
Input: {5,6,7,8} ; r = 3
Output : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}
To solve this problem an approach would be fixing elements and then recuring or looping over others to find all combinations. In this, we have to fix first n-r+1 elements only and loop or recur over the rest.
#include<iostream>
using namespace std;
void printRElementCombination(int arr[], int combination[], int start, int
end, int index, int r){
   if (index == r){
      cout<<"{ ";
      for (int j = 0; j < r; j++)
         cout << combination[j] << " ";
         cout<<"}\t";
      return;
   }
   for (int i = start; i <= end && end - i + 1 >= r - index; i++){
      combination[index] = arr[i];
      printRElementCombination(arr, combination, i+1, end, index+1, r);
   }
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combination[r];
   cout<<"The combination is : \n";
   printRElementCombination(arr, data, 0, n-1, 0, r);
}
The combination is −
{ 1 2 3 } { 1 2 4 } { 1 2 5 } { 1 3 4 } { 1 3 5 } { 1 4 5 }
{ 2 3 4 } { 2 3 5 } { 2 4 5 } { 3 4 5 }
Other methods to solve the same problem can be by checking the inclusion of
current element in the combination and print all combinations of required
size. The idea is the same, we will recure over the element and store the combination in combo array. But the fixing of the element is not done.
The below program will make the problem more understandable to you −
 Live Demo
#include <iostream>
using namespace std;
void combinationUtil(int arr[], int n, int r, int index, int combo[], int i){
   if (index == r){
      cout<<"{";
      for (int j = 0; j < r; j++)
         cout << combo[j] << " ";
         cout<<"}\t";
         return;
   }
   if (i >= n)
      return;
   combo[index] = arr[i];
   combinationUtil(arr, n, r, index + 1, combo, i + 1);
   combinationUtil(arr, n, r, index, combo, i+1);
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combo[r];
   cout<<"The combination is : \n";
   combinationUtil(arr, n, r, 0, combo, 0);
   return 0;
}
The combination is −
{1 2 3 }    {1 2 4 }    {1 2 5 }    {1 3 4 }    {1 3 5 }    {1 4 5 }
      {2 3 4 }    {2 3 5 }    {2 4 5 }     {3 4 5 }
p5.js | duration() Function - GeeksforGeeks

17 Jan, 2020
The duration() function is an inbuilt function in p5.js library. This function is used to return the duration of a sound file in seconds which is loaded the audio on the web. Basically when you trigger this function then it will return the time in the second dot microsecond format of that audio’s playing time.
Syntax:
duration()
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 does not accept any parameter.
Return Values: This function return the duration of a sound file when this function is triggered.
Below example illustrate the p5.js duration() function in JavaScript:Example:
var sound; var dur;   function preload() {        // Initialize sound     sound = loadSound("pfivesound.mp3"); }    function setup() {                //Checking duration time of the audio    var dur = sound.duration();    console.log(dur);          // Playing the preloaded sound     sound.play(); } 
Output:
212.53875 // Duration of that audio approx 3 min 32 seconds
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers supported by p5.js duration() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
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
Difference between var, let and const keywords in JavaScript
Ruby | Enumerator each_with_index function - GeeksforGeeks

06 Jan, 2020
The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.
Syntax: A.each_with_indexHere, A is the initialised object.
Parameters: This function does not accept any parameters.
Returns: the value of the given object.
Example 1:
# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|      # Getting the values of the array      puts "#{num}"  if ((idx) % 2 == 0)    puts "end of line"   end end 
Output:
5
end of line
10
15
end of line
20
25
end of line
30
Example 2:
# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|      # Getting the values of the array      puts "#{num}"  if ((idx + 1) % 2 == 0)    puts "end of line"   end end 
Output:
5
10
end of line
15
20
end of line
25
30
end of line

Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Case Statement
Ruby | Array select() function
Ruby | Numeric round() function
Ruby | Data Types
Node.js os.constants - GeeksforGeeks

01 Feb, 2022
The os.constants is an inbuilt application programming interface of the os module which is used to get operating system specified constants for error code, signal constants, priority constant, dlopen constants, etc.Syntax:  
os.constants
Return Value: It returns an object that contains operating system specified constants. Example: error codes, signal constants, priority constant, dlopen constants, etc.Signal constants can be accessed by using os.constants.signals and priority constants can be accessed by using os.constants.priority. Some of the constants are listed below:Signal Constants:  
Error constants: 1. POSIX error constant  
2. Windows specific error  
dlopen Constants:  
Priority constants:  
libuv Constants:  
Below examples illustrate the use of os.constants in Node.js:Example 1:  
javascript
// Import os moduleconst os = require('os'); constants = os.constants; // Printing all os.constantsconsole.log(constants);
Output:  
[Object: null prototype] {
  UV_UDP_REUSEADDR: 4,
  dlopen: [Object: null prototype] {},
  errno:
   [Object: null prototype] {
     E2BIG: 7,
     EACCES: 13,
     EADDRINUSE: 100,
     . . .
     PRIORITY_HIGH: -14,
     PRIORITY_HIGHEST: -20 } }
Example 2:  
javascript
// Import os moduleconst os = require('os'); constants = os.constants; // Printing os.constants // Signals constantsif(constants.signals != undefined){    console.log("Signals:");    console.log(constants.signals);} // Priority constantsif(constants.priority!=undefined){    console.log("priority:");    console.log(constants.priority);}
Output:  
Signals:
[Object: null prototype] {
  SIGHUP: 1,
  SIGINT: 2,
  . . .
  PRIORITY_HIGH: -14,
  PRIORITY_HIGHEST: -20 }
Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_constants 
avtarkumar719
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
JavaScript | Function Invocation - GeeksforGeeks

07 Mar, 2019
JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”. The code inside a function is executed when the function is invoked.
Syntax:
Invoking a Function as a Function:function myFunction( var ) {
    return var;
}
myFunction( value );
function myFunction( var ) {
    return var;
}
myFunction( value );
Invoking a Function as a Method:var myObject = {
    var : value,
    functionName: function () {
        return this.var;
    }
}
myObject.functionName();  
var myObject = {
    var : value,
    functionName: function () {
        return this.var;
    }
}
myObject.functionName();  
Parameters: It contains two parameters as mentioned above and described below:
functionName: The functionName method is a function and this function belongs to the object and myObject is the owner of the function.
this: The parameter this is the object that owns the JavaScript code and in this case the value of this is myObject.
Example 1: This example use function invocation to add two numbers.
<!DOCTYPE html><html>  <head>    <title>        JavaScript Function Invocation    </title></head>  <body style="text-align:center;">          <h2>GeeksForGeeks</h2>              <p>        Function returns the addition        of 50 and 60    </p>              <p id="geeks"></p>          <!-- Script to add two numbers -->    <script>        function myFunction(a, b) {            return a + b;        }                      document.getElementById("geeks").innerHTML                = window.myFunction(50, 60);     </script></body>  </html>                    
Output:
Example 2: This example use function invocation to concatenate strings.
<!DOCTYPE html><html>  <head>    <title>        JavaScript Function Invocation    </title></head>  <body style="text-align:center;">          <h2>GeeksForGeeks</h2>          <p>        myObject.fullName() will return        GeeksforGeeks    </p>          <p id="geeks"></p>          <!-- Script to implement Function Invocation -->    <script>        var myObject = {            firstName:"Geeks",            middleName:"for",            lastName: "Geeks",            fullName: function() {                return this.firstName + this.middleName                        + this.lastName;            }        }        document.getElementById("geeks").innerHTML                = myObject.fullName();     </script></body>  </html>                    
Output:
javascript-functions
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
Lodash _.debounce() Method
Angular File Upload
How to get selected value in dropdown list using JavaScript ?