code-rag-bench/online-tutorials huggingface dataset:
Scala - Loop Statements

This chapter takes you through the loop control structures in Scala programming languages.
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Scala programming language provides the following types of loops to handle looping requirements. Click the following links in the table to check their detail.
while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
do-while loop
Like a while statement, except that it tests the condition at the end of the loop body.
for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. As such Scala does not support break or continue statement like Java does but starting from Scala version 2.8, there is a way to break the loops. Click the following links to check the detail.
break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.
A loop becomes an infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement infinite loop.
The following program implements infinite loop.
object Demo {
   def main(args: Array[String]) {
      var a = 10;
      
      // An infinite loop.
      while( true ){
         println( "Value of a: " + a );
      }
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

If you will execute above code, it will go in infinite loop which you can terminate by pressing Ctrl + C keys.
Value of a: 10
Value of a: 10
Value of a: 10
Value of a: 10
................


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python - Ranking Rows of Pandas DataFrame

To add a column that contains the ranking of each row in the provided data frame that will help us to sort a data frame and determine the rank of a particular element, for example −
Now, as you can see in the above example, our rankings are the whole numbers but have a decimal beside it, so that means we can have ranking in real numbers also, and that happens when more and one element have the same rank in the data frame than in such cases our ranking is divided between the elements. Hence, they have a real number as their rank.
For assigning the rank to our dataframe’s elements, we use a built-in function of the pandas library that is the .rank() function. We pass the criteria based on which we are ranking the elements to it, and this function returns a new column in each row where the ranking is stored.
Code for using the .rank() function is 
import pandas as pd
games = {'Name' : ['Call Of Duty', 'Total Overdose', 'GTA 3', 'Bully'],
       'Play Time(in hours)' : ['45', '46', '52', '22'],
        'Rate' : ['Better than Average', 'Good', 'Best', 'Average']}
df = pd.DataFrame(games)
df['ranking'] = df['Play Time(in hours)'].rank(ascending = 0)
print(df)# Hello World program in Python
   
print ("Hello World!");
    Name Play Time(in hours)       Rate ranking
0  Call Of Duty   45     Better than Average 3.0
1  TotalOverdose  46     Good                2.0
2  GTA 3          52     Best                1.0
3   Bully        22      Average             4.0
In this code, we are simply using the built-in function of the panda’s library to rank each element present in the given data frame. We can use the best criteria to rank the elements with the column ‘Play Time(in hours).’
Now we add a column named ‘ranking’ in our data frame and use our .rank() function in it and pass the column name for which we need to do the ranking of our elements (in this case, it is Play Time(in hours) column) now when our new column is created we print our data frame.
In this tutorial, we rank the rows in our data frame and then print our data using the pandas library and its built-in functions. Ranking rows of pandas dataframe is an easy process, but you need to follow the above method properly.
Display all the titles of JTabbedPane tabs on Console in Java

To display all the titles of the JTabbedPane, let us first get the count of tabs −
int count = tabbedPane.getTabCount();
Now, loop through the number of tabs in the JTabbedPane. Use the getTitleAt() to get the title of each and every tab −
for (int i = 0; i < count; i++) {
   String str = tabbedPane.getTitleAt(i);
   System.out.println(str);
}
The following is an example to display all the titles of JTabbedPane tabs on Console −
package my;
import javax.swing.*;
import java.awt.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Devices");
      JTabbedPane tabbedPane = new JTabbedPane();
      JTextArea text = new JTextArea(100,100);
      JPanel panel1, panel2, panel3, panel4, panel5, panel6, panel7, panel8;
      panel1 = new JPanel();
      panel2 = new JPanel();
      panel2.add(text);
      panel3 = new JPanel();
      panel4 = new JPanel();
      panel5 = new JPanel();
      panel6 = new JPanel();
      panel7 = new JPanel();
      panel8 = new JPanel();
      tabbedPane.setBackground(Color.blue);
      tabbedPane.setForeground(Color.white);
      tabbedPane.addTab("Laptop", panel1);
      tabbedPane.addTab("Desktop ", panel2);
      tabbedPane.addTab("Notebook", panel3);
      tabbedPane.addTab("Echo ", panel4);
      tabbedPane.addTab("Tablet", panel5);
      tabbedPane.addTab("Alexa ", panel6);
      tabbedPane.addTab("Notebook", panel7);
      tabbedPane.addTab("iPad", panel8);
      int count = tabbedPane.getTabCount();
      for (int i = 0; i < count; i++) {
         String str = tabbedPane.getTitleAt(i);
         System.out.println(str);
      }
      frame.add(tabbedPane);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(600,350);
      frame.setVisible(true);
   }
}
On runnting, the console will display all the values of the tabs −
How can a COBOL-DB2 program call a STORED PROCEDURE? Give an example.

A STORED PROCEDURE generally contains the SQLs which are often used in one or more programs. The main advantage of STORED PROCEDURE is that it reduces the data traffic between the COBOL and DB2 as the STORED PROCEDURES resides in DB2.
A COBOL-DB2 program can call a STORED PROCEDURE using a CALL statement and we can have nested STORED PROCEDURE upto 16 levels. For example, if we have STORED PROCEDURE with a name ORDERSTAT, then we can call it in our COBOL-DB2 program using the below command:
EXEC SQL
   CALL ORDERSTAT (:WS-ORDER-ID, :WS-ORDER-STATUS)
END-EXEC
In order to create a DB2 procedure, we can give definition as below.
CREATE PROCEDURE ORDERSTAT ( IN ORDER-ID int,
OUT ORDER-STAT char)
We can define the STORED PROCEDURE as below.
LANGUAGE SQL
PROCA: BEGIN
DECLARE ORDERID int;
SELECT ORDER_STAT FROM ORDERS
   WHERE ORDER_ID = ORDERID;
END P1
Below are some of the advantages of using STORED PROCEDURE.
The core logic and algorithm is stored centrally at DB2 and managed by DBMS. This helps in the reusability and saves effort of modification at only a single central location.
The access to the stored procedures can be restricted based on the permissions set for different profiles within DB2.
The logic is executed at the database server which reduces the traffic at DB2 network and hence decreasing the overall execution time.
How to add a month to a date in R?

We have to deal with date data in time series analysis, also sometimes we have a time variable in data set that is recorded to perform another type of analysis. Depending on our objective, we need to process the data and the time variable is also converted into appropriate form that we are looking for. If we want to create a sequence of months from date data then we can do it by adding a month to each upcoming month. This can be easily done by using AddMonths function of DescTools package.
Installing DescTools package −
install.packages("DescTools")
Loading DescTools package:
library(DescTools)
AddMonths(as.Date('2020/01/31'), 1)
[1] "2020-02-29"
AddMonths(as.Date('2020/01/31'), 2)
[1] "2020-03-31"
AddMonths(as.Date('2020/01/31'), 3)
[1] "2020-04-30"
AddMonths(as.Date('2020/01/31'), 4)
[1] "2020-05-31"
AddMonths(as.Date('2020/01/31'), 6)
[1] "2020-07-31"
AddMonths(as.Date('2020/01/01'), 6)
[1] "2020-07-01"
AddMonths(as.Date('2020/06/01'), 6)
[1] "2020-12-01"
AddMonths(as.Date('2020/06/30'), 6)
[1] "2020-12-30"
AddMonths(as.Date('2020/01/01'), 12)
[1] "2021-01-01"
AddMonths(as.Date('2020/01/01'), 24)
[1] "2022-01-01"
AddMonths(as.Date('2020/01/01'), 36)
[1] "2023-01-01"
AddMonths(as.Date('2020/01/01'), 48)
[1] "2024-01-01"
AddMonths(as.Date('2020/01/01'), 120)
[1] "2030-01-01"
AddMonths(as.Date('2021/01/01'), 120)
[1] "2031-01-01"
AddMonths(as.Date('2021/01/01'), 500)
[1] "2062-09-01"
AddMonths(as.Date('2021/01/01'), 600)
[1] "2071-01-01"
AddMonths(as.Date('2021/01/01'), 1200)
[1] "2121-01-01"
AddMonths(as.Date('2021-01-01'),8)
[1] "2021-09-01"
AddMonths(as.Date('2021-01-01'),10)
[1] "2021-11-01"
AddMonths(as.Date('2021-01-01'),20)
[1] "2022-09-01"
AddMonths(as.Date('2021-01-01'),25)
[1] "2023-02-01"
AddMonths(as.Date('2021-01-01'),16)
[1] "2022-05-01"
What are n, bins and patches in matplotlib?

The hist() method returns n, bins and patches in matplotlib. Patches are the containers of individual artists used to create the histogram or list of such containers if there are multiple input datasets. Bins define the number of equal-width bins in the range.
Let's take an example to understand how it works.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create random data points using numpy.
Create random data points using numpy.
Make a Hist plot with 100 bins.
Make a Hist plot with 100 bins.
Set a property on an artist object.
Set a property on an artist object.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.random.normal(size=100)

n, bins, patches = plt.hist(x, bins=100)

plt.setp(patches[0], 'facecolor', 'yellow')

plt.show()
How can we detect an event when the mouse moves over any component in Java?

We can implement a MouseListener interface when the mouse is stable while handling the mouse event. A MouseEvent is fired when we can press, release or click (press followed by release) a mouse button (left or right button) at the source object or position the mouse pointer at (enter) and away (exit) from the source object. We can detect a mouse event when the mouse moves over any component such as a label by using the mouseEntered() method and can be exited by using mouseExited() method of MouseAdapter class or MouseListener interface.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseOverTest extends JFrame {
   private JLabel label;
   public MouseOverTest() {
      setTitle("MouseOver Test");
      setLayout(new FlowLayout());
      label = new JLabel("Move the mouse moves over this JLabel");
      label.setOpaque(true);
      add(label);
      label.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent evt) {
            Color c = label.getBackground(); // When the mouse moves over a label, the background color changed.
            label.setBackground(label.getForeground());
            label.setForeground(c);
         }
         public void mouseExited(MouseEvent evt) {
            Color c = label.getBackground();
            label.setBackground(label.getForeground());
            label.setForeground(c);
         }
      });
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new MouseOverTest();
   }
}
How to find parent elements by python webdriver?

We can find parent elements with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name,xpath or css. Then we have to identify the parent element with the find_element_by_xpath() method.
We can identify the parent from the child, by localizing it with the child and then passing (..) as a parameter to the find_element_by_xpath().
Syntax−
child.find_element_by_xpath("..")
Let us identify class attribute of parent ul from the child element li in below html code−
The child element with class heading should be able to get the parent element having toc chapters class attribute.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="
C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify child element
l= driver.find_element_by_xpath("//li[@class='heading']")
#identify parent from child element with (..) in xpath
t= l.find_element_by_xpath("..")
# get_attribute() method to obtain class of parent
print("Parent class attribute: " + t.get_attribute("class"))
driver.close()
Python | Pandas Series.dt.week - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.week attribute return a numpy array containing the week ordinal of the year in the underlying data of the given series object.
Syntax: Series.dt.week
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.week attribute to return the week ordinal of the year in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.week attribute to return the week ordinal of the year in the underlying data of the given Series object.
# return the week ordinal# of the yearresult = sr.dt.week  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.week attribute has successfully accessed and returned the week ordinal of the year in the underlying data of the given series object. Example #2 : Use Series.dt.week attribute to return the week ordinal of the year in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.week attribute to return the week ordinal of the year in the underlying data of the given Series object.
# return the week ordinal# of the yearresult = sr.dt.week  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.week attribute has successfully accessed and returned the week ordinal of the year in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
How to remove element in a MongoDB array?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Let us first create a collection with documents −
db.demo541.insertOne({"software":{"services":["gmail","facebook","yahoo"]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ca845ef4dcbee04fbbc11")
}
> db.demo541.insertOne({"software":{"services":["whatsapp","twitter"]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ca85cef4dcbee04fbbc12")
}
Display all documents from a collection with the help of find() method −
> db.demo541.find();
This will produce the following output −
{ "_id" : ObjectId("5e8ca845ef4dcbee04fbbc11"), "software" : { "services" : [ "gmail", "facebook", "yahoo" ] } }
{ "_id" : ObjectId("5e8ca85cef4dcbee04fbbc12"), "software" : { "services" : [ "whatsapp", "twitter" ] } } 
Following is the query to remove an element in a MongoDB array −
> db.demo541.update({ _id: ObjectId("5e8ca845ef4dcbee04fbbc11") },
...    { $pull: { 'software.services': "yahoo" }}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo541.find();
This will produce the following output −
{ "_id" : ObjectId("5e8ca845ef4dcbee04fbbc11"), "software" : { "services" : [ "gmail", "facebook" ] } }
{ "_id" : ObjectId("5e8ca85cef4dcbee04fbbc12"), "software" : { "services" : [ "whatsapp", "twitter" ] } }
C# program to split and join a string

To split and join a string in C#, use the split() and join() method. Let us say the following is our string −
string str = "This is our Demo String";
To split the string, we will use the split() method −
var arr = str.Split(' ');
Now to join, use the join() method and join rest of the string. Here, we have skipped the part of the string using the skip() method −
string rest = string.Join(" ", arr.Skip(1));
You can try to run the following code in C# to split and join a string.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         string str = "This is our Demo String";
         var arr = str.Split(' ');
         // skips the first element and joins rest of the array
         string rest = string.Join(" ", arr.Skip(1));
         Console.WriteLine(rest);
      }
   }
}
is our Demo String
Pytest - Stop Test Suite after N Test Failures

In a real scenario, once a new version of the code is ready to deploy, it is first deployed into pre-prod/ staging environment. Then a test suite runs on it.
The code is qualified for deploying to production only if the test suite passes. If there is test failure, whether it is one or many, the code is not production ready.
Therefore, what if we want to stop the execution of test suite soon after n number of test fails. This can be done in pytest using maxfail.
The syntax to stop the execution of test suite soon after n number of test fails is as follows −
pytest --maxfail = <num>

Create a file test_failure.py with the following code.
import pytest
import math

def test_sqrt_failure():
   num = 25
   assert math.sqrt(num) == 6

def test_square_failure():
   num = 7
   assert 7*7 == 40

def test_equality_failure():
   assert 10 == 11
All the 3 tests will fail on executing this test file. Here, we are going to stop the execution
of the test after one failure itself by −
pytest test_failure.py -v --maxfail 1

test_failure.py::test_sqrt_failure FAILED
=================================== FAILURES
=================================== _______________________________________
test_sqrt_failure __________________________________________
   def test_sqrt_failure():
   num = 25
>  assert math.sqrt(num) == 6
E  assert 5.0 == 6
E  + where 5.0 = <built-in function sqrt>(25)
E  + where <built-in function sqrt>= math.sqrt
test_failure.py:6: AssertionError
=============================== 1 failed in 0.04 seconds
===============================

In the above result, we can see the execution is stopped on one failure.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
DuckDB — SQLite for Data Analysis | by Alan Jones | Towards Data Science

When I wrote Python Pandas and SQLite, for Towards Data Science, I was unaware of another embedded database sytem called DuckDB. I received a tweet about it a day or so after publication so thought I should take a look at it.
DuckDB is not buit in to Python like SQLite but after a simple install, you’d hardly know the difference.
Except that there is a difference. The DuckDB developers claim that their database system is up to 10 times faster than SQLite for analytics applications. There are of course technical reasons in the design of the database for this but the main reason is that there are relational databases for two types of application: Online Transactional Processing(OLTP) and Online Analytical Processing (OLAP).
OLTP applications are typically business processes that modify database tables in response to external requests. A banking system is an example: people are taking money out, putting it in and their balances are shifting up and down all the time meaning that the data in the database in constantly changing in response to the transaction that are occuring. A database tracking sales and stock levels might have a similar types of data updates going on as items are sold to customers or received from suppliers.
Essentially, OLTP systems spend most of their time, inserting, deleting and updating rows in database tables.
OLAP sytems are less dynamic. They are more like data warehouses. Data is stored but doesn’t change that often. The main types of operation will be selecting, reading, comparing and analysing data. An online retailer might analyse customer purchasing data, compare it to other customers and try and analyse similarities. By doing this they can attempt to predict an individual’s preferences so that visitors to their web site can get a personalized experience.
OLAP systems tend to spend most of their time dealing with columns of data, summing, finding means and that sort of thing.
Although database systems all have the same basic functionality, those designed for OLTP are less good at OLAP applications and vice versa due to the way data is stored — in a way that easier to access columns or one that easier to access rows.
So SQLite is good for OLTP and DuckDB is better for OLAP.
You can try it out with my original article by doing a pip install:
pip install duckdb
and changing the first line of the code from
import sqlite3 as sql
to
import duckdb as sql
The rest of the code should work as before.
Don’t expect to see much difference in the operation of the simple code that I presented in that article but if you need to do any heavy duty data analytics then you might find that DuckDB is a better bet.
I’ll be writing more about this topic in the future but, for now, thanks for reading and happy data analysis.
Disclosure: I have no connection with DuckDB or its developers
And if you would like to be informed about future articles please subscribe to my free newsletter.
Extracting MAC address using C#

A MAC address of a device is a media access control address. It is a unique identifier assigned to a network.
The MAC address technology is used by many technologies such as Ethernet, Bluetooth, Fibre Channel, etc.
Here, we will use the following method to check for all the network interfaces on the computer.
NetworkInterface.GetAllNetworkInterfaces
For this, the NetworkInterfaceType Enumeration is also used to specify the type of network interfaces.
string addr = "";
foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces()) {
   if (n.OperationalStatus == OperationalStatus.Up) {
      addr += n.GetPhysicalAddress().ToString();
      break;
   }
}
return addr;
Above, we have used the GetPhysicalAddress() method to extract the MAC address.
C++ program to read file word by word

08 May, 2019
Given a text file, extract words from it. In other words, read the content of file word by word.Example :
Input: And in that dream, we were flying.
Output:
And
in
that
dream,
we
were
flying.

Approach :
1) Open the file which contains string. For example, file named “file.txt” contains a string “geeks for geeks”.2) Create a filestream variable to store file content.3) Extract and print words from the file stream into a string variable via while loop.
// C++ implementation to read// file word by word#include <bits/stdc++.h>using namespace std;  // driver codeint main(){    // filestream variable file    fstream file;    string word, t, q, filename;      // filename of the file    filename = "file.txt";      // opening file    file.open(filename.c_str());      // extracting words from the file    while (file >> word)    {        // displaying content        cout << word << endl;    }      return 0;}
Output:
geeks
for
geeks.

imim123345667899
cpp-file-handling
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to embed Google Forms on any Website ?

01 Oct, 2020
Google Forms are one of the most famous online platform developed and supported by Google. One can create and customize the created forms and can perform various tasks from review to automatic certificate generator. One can also embed it on a website so that anyone visiting the website can submit or view the form. This article will describe the method to embed a Google Form to any website.
Step 1: Create a Google Form that has to be embedded. The How to Create and Customize Google Forms? article has the steps needed to create and customize Google Forms as per the requirements.
Step 2: After the form has been created, click on the Send button as shown in the image below.
Step 3: Select the embed option from the available options of sending. This would show an <iframe> link that has to be copied.
Step 3: Add this <iframe> link in the HTML source code of the page where the form has to be embedded. This will automatically display the form and allow it to be filled on the page itself. The example below illustrates how the form has to be embedded.
Example:
HTML
<!DOCTYPE html><html>  <body>    <h1 style="color: green;">        GeeksforGeeks    </h1>      <p>        How to embed Google Forms         on any website?    </p>        <!-- Specify the <iframe> given by the        the Google Forms embed page -->    <iframe src="Your Copied Form Source"         width="550" height="600"         frameborder="0" marginheight="0"        marginwidth="0">        Loading...    </iframe></body>  </html>
Output:
The output screen will look like this
How To
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – K Maximum elements with Index in List

01 Aug, 2020
GIven a List, extract K Maximum elements with their indices.
Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2Output : [(4, 7), (5, 8)]Explanation : 8 is maximum on index 5, 7 on 4th.
Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1Output : [(5, 10)]Explanation : 10 is maximum on index 5.
Method #1 : Using sorted() + index()
The combination of above functions provide a way of finding solution to this problem. In this, we initially perform sort and extract K maximum elements, then are encapsulated in tuple with their ordering in original list.
Python3
# Python3 code to demonstrate working of # K Maximum elements with Index in List# Using sorted() + index()  # initializing listtest_list = [5, 3, 1, 4, 7, 8, 2]  # printing original list print("The original list : " + str(test_list))  # initializing KK = 3  # Using sorted() + index()# using sorted() to sort and slice K maximum elements temp = sorted(test_list)[-K:]res = []for ele in temp:          # encapsulating elements with index using index()    res.append((test_list.index(ele), ele))  # printing result print("K Maximum with indices : " + str(res))
The original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]

Method #2 : Using enumerate() + itemgetter()
The combination of above functions can be used to solve this problem. In this, we perform the task of getting indices using enumerate() and itemgetter() is used to get the elements. 
Python3
# Python3 code to demonstrate working of# K Maximum elements with Index in List# Using enumerate() + itemgetter()from operator import itemgetter  # initializing listtest_list = [5, 3, 1, 4, 7, 8, 2]  # printing original listprint("The original list : " + str(test_list))  # initializing KK = 3  # Using enumerate() + itemgetter()# Making index values pairs at 1st stageres = list(sorted(enumerate(test_list), key = itemgetter(1)))[-K:]  # printing resultprint("K Maximum with indices : " + str(res))
The original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TypeScript | Array unshift() Method

15 Dec, 2021
The Array.unshift() is an inbuilt TypeScript function that is used to add one or more elements to the beginning of an array and returns the new length of the array. 
Syntax:
array.unshift( element1, ..., elementN )
Parameter: This method accepts n number of similar elements.
element1, ..., elementN : This parameter is the elements to add to the front of the array.
Return Value: This method returns the length of the new array. Below example illustrate the  String unshift() method in TypeScriptJS:
Example 1: 
JavaScript
<script>    // Driver code    var arr = [ 11, 89, 23, 7, 98 ];     // use of unshift() method    var string= arr.unshift(11);          // printing    console.log( string);</script>
 Output:  
6
Example 2:  
JavaScript
<script>    // Driver code    var arr = ["G", "e", "e", "k", "s", "f", "o",               "r", "g", "e", "e", "k", "s"];    var val;      // use of unshift() method    val = arr.unshift("f");    console.log( val );    console.log( arr );</script>
 Output:  
14
["f","G","e","e","k","s","f","o","r","g","e","e","k","s"]
 
anikakapoor
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js util.types.isDate() Method

08 Oct, 2021
The util.types.isDate() method is an inbuilt application programming interface of the util module which is used to check type for Date in the node.js.
Syntax:
util.types.isDate( value )
Parameters: This method accepts single parameter as mentioned above and described below.
value: It is a required parameter of any datatype.
Return Value: This returns a boolean value, TRUE if the value is a Date object, FALSE otherwise.
Below examples illustrate the use of util.types.isDate() method in Node.js:
Example 1:
// Node.js program to demonstrate the   // util.types.isDate() Method  // Allocating util moduleconst util = require('util');  // Value to be passed as parameter// of util.types.isDate() methodvar v1 = new Date();var v2 = 3 / 6 / 96;  // Printing the returned value from// util.types.isDate() methodconsole.log(util.types.isDate(v1));console.log(util.types.isDate(v2));
Output:
true
false

Example 2:
// Node.js program to demonstrate the   // util.types.isDate() Method  // Allocating util moduleconst util = require('util');  // Value to be passed as parameter// of util.types.isDate() methodvar v1 = new Date();var v2 = 3 / 6 / 96;  // Calling util.types.isDate() methodif (util.types.isDate(v1))    console.log("The passed value is a Date.");else    console.log("The passed value is not a Date");  if (util.types.isDate(v2))    console.log("The passed value is a Date.");else    console.log("The passed value is not a Date");
Output:
The passed value is a Date.
The passed value is not a Date

Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/util.html#util_util_types_isdate_value
Node.js-util-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQtGraph – Bar Graph

05 May, 2021
In this article we will see how we can create bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).
A bar graph is a method for visualizing a set of data. Simple bar graphs compare data with one independent variable and can relate to a set point or range of data. Complex bar graphs compare data with two independent variables. Either type of graph can be oriented horizontally or vertically. Bar graph is created with the help of BarGraphItem class in PyQtGraph.
In order to plot the bar graph in PyQtGraph we have to do the following1. Importing the PyQtgraph module2. Creating a plot window3. Create or get the plotting data i.e horizontal and vertical data4. Create a BarGraphItem object to plot the bar graph between the data5. Append the BarGraphItem object to the plot window
Below is the implementation
# importing pyqtgraph as pgimport pyqtgraph as pg  # importing QtCore and QtGui from # the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui  # importing numpy as npimport numpy as np  import time  # creating a pyqtgraph plot windowwindow = pg.plot()  # setting window geometry# left = 100, top = 100# width = 600, height = 500window.setGeometry(100, 100, 600, 500)  # title for the plot windowtitle = "GeeksforGeeks PyQtGraph"  # setting window title to plot windowwindow.setWindowTitle(title)  # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2]  # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # create pyqt5graph bar graph item# with width = 0.6# with bar colors = greenbargraph = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g')  # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph)    # main methodif __name__ == '__main__':          # importing system    import sys          # Start Qt event loop unless running in interactive mode or using    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):        QtGui.QApplication.instance().exec_()
Output :
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Default constructor in Java

10 Jul, 2018
Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default values (numeric values are initialized as 0, booleans are initialized as false and references are initialized as null).
For example, output of the below program is
0nullfalse00.0
// Main.javaclass Test {   int i;   Test t;   boolean b;   byte bt;   float ft;}  public class Main {    public static void main(String args[]) {      Test t = new Test(); // default constructor is called.      System.out.println(t.i);      System.out.println(t.t);      System.out.println(t.b);      System.out.println(t.bt);      System.out.println(t.ft);    }}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:http://leepoint.net/notes-java/oop/constructors/constructor.html
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Interesting facts about data-types and modifiers in C/C++

17 Apr, 2020
Here are some logical and interesting facts about data-types and the modifiers associated with data-types:-
1. If no data type is given to a variable, the compiler automatically converts it to int data type.
C++
C
#include <iostream>using namespace std;  int main(){    signed a;    signed b;      // size of a and b is equal to the size of int    cout << "The size of a is " << sizeof(a) <<endl;     cout << "The size of b is " << sizeof(b);     return (0);}  // This code is contributed by shubhamsingh10
#include <stdio.h>int main(){    signed a;    signed b;      // size of a and b is equal to the size of int    printf("The size of a is %d\n", sizeof(a));     printf("The size of b is %d", sizeof(b));     return (0);}
The size of a is 4
The size of b is 4

2. Signed is the default modifier for char and int data types.
C++
C
#include <iostream>using namespace std;  int main(){    int x;    char y;    x = -1;    y = -2;    cout << "x is "<< x <<" and y is " << y << endl;}  // This code is contributed by shubhamsingh10
#include <stdio.h>int main(){    int x;    char y;    x = -1;    y = -2;    printf("x is %d and y is %d", x, y);}
x is -1 and y is -2.

3. We can’t use any modifiers in float data type. If programmer tries to use it ,the compiler automatically gives compile time error.
C++
C
#include <iostream>using namespace std;int main(){    signed float a;    short float b;    return (0);}//This article is contributed by shivanisinghss2110
#include <stdio.h>int main(){    signed float a;    short float b;    return (0);}
[Error] both 'signed' and 'float' in declaration specifiers
[Error] both 'short' and 'float' in declaration specifiers

4. Only long modifier is allowed in double data types. We cant use any other specifier with double data type. If we try any other specifier, compiler will give compile time error.
C++
C
#include <iostream>using namespace std;int main(){    long double a;    return (0);}  // This code is contributed by shubhamsingh10
#include <stdio.h>int main(){    long double a;    return (0);}
C++
C
#include <iostream>using namespace std;int main(){    short double a;    signed double b;    return (0);}  // This code is contributed by shubhamsingh10
#include <stdio.h>int main(){    short double a;    signed double b;    return (0);}
[Error] both 'short' and 'double' in declaration specifiers
[Error] both 'signed' and 'double' in declaration specifiers

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rhythm1
SHUBHAMSINGH10
shivanisinghss2110
cpp-data-types
interesting-facts
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array filtering using first string letter in JavaScript

Suppose we have an array that contains name of some people like this:
const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
We are required to write a JavaScript function that takes in one such string as the first argument, and two lowercase alphabet characters as second and third argument. Then, our function should filter the array to contain only those elements that start with the alphabets that fall within the range specified by the second and third argument.
Therefore, if the second and third argument are 'a' and 'j' respectively, then the output should be −
const output = ['Amy','Dolly','Jason'];
Let us write the code −
const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
const filterByAlphaRange = (arr = [], start = 'a', end = 'z') => {
   const isGreater = (c1, c2) => c1 >= c2;
   const isSmaller = (c1, c2) => c1 <= c2;
   const filtered = arr.filter(el => {
      const [firstChar] = el.toLowerCase();
      return isGreater(firstChar, start) && isSmaller(firstChar, end);
   });
   return filtered;
};
console.log(filterByAlphaRange(arr, 'a', 'j'));
And the output in the console will be −
[ 'Amy', 'Dolly', 'Jason' ]
Polymorphism in Python

Polymorphism means multiple forms. In python we can find the same operator or function taking multiple forms. It also useful in creating different classes which will have class methods with same name. That helps in re using a lot of code and decreases code complexity. Polymorphism is also linked to inheritance as we will see in some examples below.
The + operator can take two inputs and give us the result depending on what the inputs are. In the below examples we can see how the integer inputs yield an integer and if one of the input is float then the result becomes a float. Also for strings, they simply get concatenated. This happens automatically because of the way the + operator is created in python.
a = 23
b = 11
c = 9.5
s1 = "Hello"
s2 = "There!"
print(a + b)
print(type(a + b))
print(b + c)
print(type (b + c))
print(s1 + s2)
print(type(s1 + s2))
Running the above code gives us the following result −
34
20.5
HelloThere!
We can also see that different python functions can take inputs of different types and then process them differently. When we supply a string value to len() it counts every letter in it. But if we five tuple or a dictionary as an input, it processes them differently.
str = 'Hi There !'
tup = ('Mon','Tue','wed','Thu','Fri')
lst = ['Jan','Feb','Mar','Apr']
dict = {'1D':'Line','2D':'Triangle','3D':'Sphere'}
print(len(str))
print(len(tup))
print(len(lst))
print(len(dict))
Running the above code gives us the following result −
10
5
4
3
We can create methods with same name but wrapped under different class names. So we can keep calling the same method with different class name pre-fixed to get different result. In the below example we have two classes, rectangle and circle to get their perimeter and area using same methods.
from math import pi

class Rectangle:
   def __init__(self, length, breadth):
      self.l = length
      self.b = breadth
   def perimeter(self):
      return 2*(self.l + self.b)
   def area(self):
      return self.l * self.b

class Circle:
   def __init__(self, radius):
      self.r = radius
   def perimeter(self):
      return 2 * pi * self.r
   def area(self):
      return pi * self.r ** 2

# Initialize the classes
rec = Rectangle(5,3)
cr = Circle(4)
print("Perimter of rectangel: ",rec.perimeter())
print("Area of rectangel: ",rec.area())

print("Perimter of Circle: ",cr.perimeter())
print("Area of Circle: ",cr.area())
Running the above code gives us the following result −
Perimter of rectangel: 16
Area of rectangel: 15
Perimter of Circle: 25.132741228718345
Area of Circle: 50.26548245743669
Detect Cat Faces in Real-Time using Python-OpenCV - GeeksforGeeks

03 Jul, 2020
Face Detection is a technology to identify faces from the image. We use Python’s OpenCV for this. We can also use Face Detection in the case of Animals too. If one can take a close look at the OpenCV repository, the haar cascades directory to be specific (where the OpenCV stores all its pre-trained haar classifiers to detect various objects, body parts, etc.), there are two files:
haarcascade_frontalcatface.xml
haarcascade_frontalcatface_extended.xml
The objective of the program given is to detect the object of interest(cat face) in real-time and to keep tracking the same object. This is a simple example of how to detect the cat face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects.
Below is the implementation.
# OpenCV program to detect cat face in real time # import libraries of python OpenCV # where its functionality resides import cv2   # load the required trained XML classifiers # https://github.com/Itseez/opencv/blob/master/ # data/haarcascades/haarcascade_frontalcatface.xml # Trained XML classifiers describes some features of some # object we want to detect a cascade function is trained # from a lot of positive(faces) and negative(non-faces) # images. face_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml')     # capture frames from a camera cap = cv2.VideoCapture(0)   # loop runs if capturing has been initialized. while 1:       # reads frames from a camera     ret, img = cap.read()       # convert to gray scale of each frames     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)       # Detects faces of different sizes in the input image     faces = face_cascade.detectMultiScale(gray, 1.3, 5)       for (x,y,w,h) in faces:         # To draw a rectangle in a face         cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)         roi_gray = gray[y:y+h, x:x+w]         roi_color = img[y:y+h, x:x+w]         # Display an image in a window     cv2.imshow('img',img)       # Wait for Esc key to stop     k = cv2.waitKey(30) & 0xff    if k == 27:         break  # Close the window cap.release()   # De-allocate any associated memory usage cv2.destroyAllWindows() 
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()