code-rag-bench/online-tutorials huggingface dataset:
How to plot a graph in Python?

Graphs in Python can be plotted by using the Matplotlib library. Matplotlib library is mainly used for graph plotting.
You need to install matplotlib before using it to plot graphs. Matplotlib is used to draw a simple line, bargraphs, histograms and piecharts. Inbuilt functions are available to draw all types of graphs in the matplotlib library.
We will plot a simple line in a graph using matplotlib. The following steps are involved in plotting a line.
Import matplotlib
Import matplotlib
Specify the x-coordinates and y-coordinates of the line
Specify the x-coordinates and y-coordinates of the line
Plot the specified points using specific function using .plot() function
Plot the specified points using specific function using .plot() function
Name the x-axis and y-axis using .xlabel() and .ylabel() functions
Name the x-axis and y-axis using .xlabel() and .ylabel() functions
Give a title to the graph(optional) using .title() function
Give a title to the graph(optional) using .title() function
Show the graph using .show() function
Show the graph using .show() function
These are the simple steps involved in plotting a line using matplotlib.
import matplotlib.pyplot as plt

x=[1,3,5,7]
y=[2,4,6,1]
plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple line graph")
plt.show()
The above code plots the points (1,2),(3,4),(5,6),(7,1) and joins these points with a line which is shown as the graph.
A bar graph is the way of representing data by rectangles of different heights at specific positions on the x-axis.
The following steps are involved in drawing a bar graph −
Import matplotlib
Import matplotlib
Specify the x-coordinates where the left bottom corner of the rectangle lies.
Specify the x-coordinates where the left bottom corner of the rectangle lies.
Specify the heights of the bars or rectangles.
Specify the heights of the bars or rectangles.
Specify the labels for the bars
Specify the labels for the bars
Plot the bar graph using .bar() function
Plot the bar graph using .bar() function
Give labels to the x-axis and y-axis
Give labels to the x-axis and y-axis
Give a title to the graph
Give a title to the graph
Show the graph using .show() function.
Show the graph using .show() function.
import matplotlib.pyplot as plt

left_coordinates=[1,2,3,4,5]
heights=[10,20,30,15,40]
bar_labels=['One','Two','Three','Four','Five']
plt.bar(left_coordinates,heights,tick_label=bar_labels,width=0.6,color=['re
d','black'])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple bar graph")
plt.show()
The width parameter in the plt.bar() specifies the width of each bar. The color lists specify the colors of the bars.
How to Set a Column Value to Null in SQL?

21 Aug, 2021
In this article, we will look into how you can set the column value to Null in SQL.
Firstly, let’s create a table using CREATE TABLE command:
-- create a table
CREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2));
-- insert some values
INSERT INTO students VALUES (1, 'Nikita', 'F');
INSERT INTO students VALUES (2, 'Akshit', 'M');
INSERT INTO students VALUES (3, 'Ritesh', 'F');
INSERT INTO students VALUES (4, 'Himani', 'F');
-- fetch some values
SELECT * FROM students ;
The table would look like this:
To UPDATE Column value, use the below command:
 UPDATE TABLE [TABLE_NAME]
To set column value to NULL use syntax:
 update [TABLE_NAME] set [COLUMN_NAME] = NULL where [CRITERIA] 
Example: For the above table
update students set Gender = NULL where Gender='F';
SELECT * FROM students ;
Output:
Column value can also be set to NULL without specifying the ‘where’ condition.
Example:
update students set Gender = NULL;
SELECT * FROM students ;
Output:
If you have set a constraint that a particular column value can not be NULL, and later try to set it as NULL, then it will generate an error.
Example:
-- create a table
CREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2) NOT NULL);
-- insert some values
INSERT INTO students VALUES (1, 'Nikita', 'F');
INSERT INTO students VALUES (2, 'Akshit', 'M');
INSERT INTO students VALUES (3, 'Ritesh', 'F');
INSERT INTO students VALUES (4, 'Himani', 'F');
-- fetch some values
SELECT * FROM students ;
Output:
ERROR: Gender may not be NULL.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Window functions in SQL
SQL | GROUP BY
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
SQL | Sub queries in From Clause
Python | Pandas Series.ravel()

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.ravel() function returns the flattened underlying data as an ndarray.
Syntax: Series.ravel(order=’C’)
Parameter : order
Returns : ndarray
Example #1: Use Series.ravel() function to return the elements of the given Series object as an ndarray.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray.
# return an ndarrayresult = sr.ravel()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object.
Example #2: Use Series.ravel() function to return the elements of the given Series object as an ndarray.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray.
# return an ndarrayresult = sr.ravel()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the background and foreground colors of tab in Java?

To change the background and foreground colors of tab, use the following methods −
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
Above, we have used the Color class to set the colors for the background and foregroud colors −
The following is an example to change the background and foreground colors of tab −
package my;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Devices");
      JTabbedPane tabbedPane = new JTabbedPane();
      JPanel panel1, panel2, panel3, panel4, panel5;
      panel1 = new JPanel();
      panel2 = new JPanel();
      panel3 = new JPanel();
      panel4 = new JPanel();
      panel5 = new JPanel();
      tabbedPane.setBackground(Color.blue);
      tabbedPane.setForeground(Color.white);
      tabbedPane.addTab("Laptop", panel1);
      tabbedPane.addTab("Desktop ", panel2);
      tabbedPane.addTab("Notebook", panel3);
      tabbedPane.addTab("Tablet ", panel4);
      tabbedPane.addTab("Mobile", panel5);
      frame.add(tabbedPane);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(550,350);
      frame.setVisible(true);
   }
}
React Native - MapView

In this chapter we will show you how to use maps in React Native.
Let's create src/components/home/MapViewExample.js
We are adding several props to MapView.
showsUserLocation and followUserLocation are booleans. You will need users permission before it can be used.
We also want to enable zoom by setting zoomEnabled = {true}
src/components/home/MapViewExample.js
import React, { Component } from 'react'
import {
   MapView,
   StyleSheet
} from 'react-native'

export default MapViewExample = (props) => {
   return (
      <MapView
         style = {styles.map}
         showsUserLocation = {false}
         followUserLocation = {false}
         zoomEnabled = {true}
      />
   )
}

const styles = StyleSheet.create ({
   map: {
      height: 400,
      marginTop: 80
   }
})
And finally we need to pass this to HomeContainer component.
src/components/home/HomeContainer.js
import React, { Component } from 'react'
import { MapView } from 'react-native'
import MapViewExample from './MapViewExample'

export default class HomeContainer extends Component {

   constructor() {
      super();
   }
   render() {
      return (
         <MapViewExample/>
      );
   }
}
When we run the app, we can see the map.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
C++ Program to Check Whether Topological Sorting can be Performed in a Graph

In a Directed Acyclic Graph, we can sort vertices in linear order using topological sort.
Topological sort is only work on Directed Acyclic Graph. In a Directed Acyclic Graph (DAG), there can be more than one topological sort.
In the following C++ program, we shall perform topological sort to check existence of a cycle in a graph.
Begin
   Define function Topo_Sort()
      Declare x to the integer datatype, vstd[] of the Boolean array and Stack as a stack.
         Pass them as parameter.
      Initialize vstd[x] = true to mark the current node as vstd.
      Declare an iterator i.
      for (i = a[x].begin(); i != a[x].end(); ++i)
         if (!vstd[*i]) then
      Call Topo_Sort(*i, vstd, Stack) function.
   Call push() function to insert values into stack.
End.
#include<iostream>
#include <list>
#include <stack>
using namespace std;
class grph { // Class to represent a graph
   int ver;
   list<int> *a; // Pointer to an array containing adjacency listsList
   void Topo_Sort(int x, bool vstd[], stack<int> &Stack); // A function used by TopologicalSort
   public:
      grph(int ver); // Constructor of grpf
   void Insert_Edge(int x, int y); // to insert an edge to graph
   void Topol_Sort(); // prints a Topological Sort of the complete graph
};
grph::grph(int ver) {
   this->ver = ver;
   a = new list<int>[ver];
}
void grph::Insert_Edge(int x, int y) {
   a[x].push_back(y); // Add y to x’s list.
}
// A recursive function used by Topol_Sort
void grph::Topo_Sort(int x, bool vstd[], stack<int> &Stack) {
   vstd[x] = true; // Mark the current node as vstd.
   list<int>::iterator i;
   for (i = a[x].begin(); i != a[x].end(); ++i)
      if (!vstd[*i])
         Topo_Sort(*i, vstd, Stack);
   // Push current vertex to stack which stores result
   Stack.push(x);
}
void grph::Topol_Sort() {
   stack<int> Stack;
   // Mark all the vertices as not vstd
   bool *vstd = new bool[ver];
   for (int i = 0; i < ver; i++)
      vstd[i] = false;
   for (int i = 0; i < ver; i++)
      if (vstd[i] == false)
         Topo_Sort(i, vstd, Stack);
   while (Stack.empty() == false) {
      cout << Stack.top() << " ";
      Stack.pop();
   }
}
int main() {
   grph g(6); // Create a graph given in the above diagram
   g.Insert_Edge(5, 2);
   g.Insert_Edge(5, 0);
   g.Insert_Edge(4, 0);
   g.Insert_Edge(4, 1);
   g.Insert_Edge(2, 3);
   g.Insert_Edge(3, 1);
   cout << "Topological Sort of the graph is: \n";
   g.Topol_Sort();
   return 0;
}
Topological Sort of the graph is:
5 4 2 3 1 0
C++ | Constructors | Question 16 - GeeksforGeeks

28 Jun, 2021
Predict the output of following program?
#include <iostream>using namespace std;class Test{private:    int x;public:    Test(int i)    {        x = i;        cout << "Called" << endl;    }};  int main(){    Test t(20);    t = 30; // conversion constructor is called here.    return 0;}
(A) Compiler Error(B)
Called
Called
(C)
Called
Answer: (B)Explanation: If a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed.
A conversion constructor can be called anywhere when the type of single argument is assigned to the object. The output of the given program is
Called
Called
Quiz of this Question
C++-Constructors
Constructors
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Inheritance | Question 7
C++ | Virtual Functions | Question 12
C++ | new and delete | Question 1
What is traits in PHP?

In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn't permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
<?php
   trait Reader{
      public function add($var1,$var2){
         return $var1+$var2;
      }
   }
   trait writer {
      public function multiplication($var1,$var2){
         return $var1*$var2;
      }
   }
   class File {
      use Reader;
      use writer;
      public function calculate($var1,$var2){
         echo "Ressult of addition:".$this->add($var1,$var2) ."\n";
         echo "Ressult of multiplication:".$this->multiplication($var1,$var2);
      }
   }
   $o = new File();
   $o->calculate(5,3);
?>
Result of addition two numbers:8
Result of multiplication of two numbers:15
In the above example, we have implemented a function from two traits in a single class. Due to trait, we are able to access multiple functions in a single class.
We are using the "USE" keyword to access traits inside a class.
PHP | DOMDocument loadXML() Function

30 Aug, 2019
The DOMDocument::loadXML() function is an inbuilt function in PHP which is used to load the XML file from a string.
Syntax:
mixed DOMDocument::loadXML( string $source, int $options = 0 )
Parameters: This function accepts two parameters as mentioned above and described below:
$source: This parameter holds the string containing the XML document.
$options: This parameter holds the Bitwise OR of the libxml option constants.
Return Value: This function returns TRUE on success or FALSE on failure. This function returns a DOMDocument if it is called statically or FALSE on failure.
Below programs illustrate the DOMDocument::loadXML() function in PHP:
Program 1:
<?php  // Create a new DOMDocument$doc = new DOMDocument();   // Load the XML file$doc->loadXML("<user>     <username>Geeks123</username>     <name>GeeksforGeeks</name>      <address>          <phone>+91-XXXXXXXXXX</phone>        <email>abc@geeksforgeeks.org</email>    </address> </user>");   // Create XML file and display itecho $doc->saveHTML();   ?>
<user> 
    <username>Geeks123</username> 
    <name>GeeksforGeeks</name>  
    <address>  
        <phone>+91-XXXXXXXXXX</phone>
        <email>abc@geeksforgeeks.org</email>
    </address> 
</user>

Program 2:
<?php  // Create new DOMDocument$doc = new DOMDocument();    // Create a comment document$comm1 = $doc->createComment('Starting of XML document');   // Append element to the document$doc->appendChild($comm1);   // Create XML file and display itecho $doc->saveHTML();   // Load the XML file$doc->loadXML("<user>     <username>Geeks123</username>     <name>GeeksforGeeks</name>      <address>          <phone>+91-XXXXXXXXXX</phone>        <email>abc@geeksforgeeks.org</email>    </address> </user>");   // Create comment element$comm2 = $doc->createComment('Ending of XML document');   // Append element to the document$doc->appendChild($comm2);   // Create XML element and display itecho $doc->saveHTML();   ?>
<!--Starting of XML document-->
<user> 
    <username>Geeks123</username> 
    <name>GeeksforGeeks</name>  
    <address>  
        <phone>+91-XXXXXXXXXX</phone>
        <email>abc@geeksforgeeks.org</email>
    </address> 
</user><!--Ending of XML document-->

Reference: https://www.php.net/manual/en/domdocument.loadxml.php
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to embed audio element in a HTML document ?

30 Sep, 2020
Since the release of HTML5, audio can be added to webpages using the <audio> tag. Previously audio could be only played on webpages using web plugins like Flash. The <audio> tag is an inline element which is used to embed sound files into a web page. It is a very useful tag if you want to add audio such as songs, interviews, etc on your webpage.
Syntax:
<audio>
    <source src="sample.mp3" type="audio/mpeg">
</audio>

Example 1:
HTML
<!DOCTYPE html><html>  <body>    <h1 style="color:green;">        GeeksforGeeks    </h1>      <h3>        How to embed audio in a HTML document?    </h3>      <audio controls>        <source src="test.mp3" type="audio/mp3">        <source src="test.ogg" type="audio/ogg">    </audio>  </body>  </html>
Output:
Example 2: In this example, audio will play automatically after loading the web page.
HTML
<!DOCTYPE html><html>  <body>    <h1 style="color:green;">        GeeksforGeeks    </h1>      <h3>        How to embed audio in a HTML document?    </h3>      <audio controls autoplay>        <source src="test.mp3" type="audio/mp3">        <source src="test.ogg" type="audio/ogg">    </audio>  </body>  </html>
Output:
HTML-Misc
HTML
Web Technologies
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 ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
YAML - Collections and Structures

YAML includes block collections which use indentation for scope. Here, each entry begins with a new line. Block sequences in collections indicate each entry with a dash and space (-). In YAML, block collections styles are not denoted by any specific indicator. Block collection in YAML can distinguished from other scalar quantities with an identification of key value pair included in them.
Mappings are the representation of key value as included in JSON structure. It is used often in multi-lingual support systems and creation of API in mobile applications. Mappings use key value pair representation with the usage of colon and space (:).
Consider an example of sequence of scalars, for example a list of ball players as shown below −
- Mark Joseph
- James Stephen
- Ken Griffey

The following example shows mapping scalars to scalars −
hr: 87
avg: 0.298
rbi: 149

The following example shows mapping scalars to sequences −
European:
- Boston Red Sox
- Detroit Tigers
- New York Yankees

national:
- New York Mets
- Chicago Cubs
- Atlanta Braves

Collections can be used for sequence mappings which are shown below −
-
name: Mark Joseph
hr: 87
avg: 0.278
-
name: James Stephen
hr: 63
avg: 0.288

With collections, YAML includes flow styles using explicit indicators instead of using indentation to denote space. The flow sequence in collections is written as comma separated list enclosed in square brackets. The best illustration for collection which is included in PHP frameworks like symphony.
[PHP, Perl, Python]

These collections are stored in documents. The separation of documents in YAML is denoted with three hyphens or dashes (---). The end of document is marked with three dots (...).
The separation of documents in YAML is denoted by three dashes (---). The end of document is represented with three dots (...).
The document representation is referred as structure format which is mentioned below −
# Ranking of 1998 home runs
---
- Mark Joseph
- James Stephen
- Ken Griffey 

# Team ranking
---
- Chicago Cubs
- St Louis Cardinals

A question mark with a combination of space indicates a complex mapping in structure. Within a block collection, a user can include structure with a dash, colon and question mark. The following example shows the mapping between sequences −
- 2001-07-23
? [ New York Yankees,Atlanta Braves ]
: [ 2001-07-02, 2001-08-12, 2001-08-14]
Extracting filenames from a path in MySQL?

To extract filenames from a path MySQL, you can use SUBSTRING_INDEX(). The syntax is as follows −
SELECT SUBSTRING_INDEX(ypurColumnName, '\\', -1) as anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ExtractFileNameDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> AllProgrammingFilePath varchar(100)
   -> );
Query OK, 0 rows affected (0.50 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\Users\\John\\AddTwoNumberProgram.java');
Query OK, 1 row affected (0.13 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('E:\\CProgram\\MasterMindGame.c');
Query OK, 1 row affected (0.23 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('F:\\WebApplication\\WebApp.php');
Query OK, 1 row affected (0.19 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\Users\\John\\Desktop\\AllMySQLScript.sql');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from ExtractFileNameDemo;
The following is the output −
+----+------------------------------------------+
| Id | AllProgrammingFilePath                   |
+----+------------------------------------------+
|  1 | C:\Users\John\AddTwoNumberProgram.java   |
|  2 | E:\CProgram\MasterMindGame.c             |
|  3 | F:\WebApplication\WebApp.php             |
|  4 | C:\Users\John\Desktop\AllMySQLScript.sql |
+----+------------------------------------------+
4 rows in set (0.00 sec)
Here is the query to extract file names from a path in MySQL −
mysql> select SUBSTRING_INDEX(AllProgrammingFilePath, '\\', -1) as AllFileName from ExtractFileNameDemo;
The following is the output −
+--------------------------+
| AllFileName              |
+--------------------------+
| AddTwoNumberProgram.java |
| MasterMindGame.c         |
| WebApp.php               |
| AllMySQLScript.sql       |
+--------------------------+
4 rows in set (0.00 sec)
PyQt5 QListWidget – Getting Current Item

01 Aug, 2020
In this article we will see how we can get the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item.Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method.
In order to do this we will use currentItem method with the list widget object.
Syntax : list_widget.currentItem()
Argument : It takes no argument
Return : It returns QListWidgetItem object
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting current item        list_widget.setCurrentItem(item2)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)            # getting current item        value = list_widget.currentItem()          # setting text to the label        label.setText("Current Item : " + str(value))        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
MATLAB - The Nested switch Statements

It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
The syntax for a nested switch statement is as follows −
switch(ch1) 
   case 'A' 
      fprintf('This A is part of outer switch');
      switch(ch2) 
         case 'A'
         fprintf('This A is part of inner switch' );
         
         case 'B'  
         fprintf('This B is part of inner switch' );
      end   
   case 'B'
      fprintf('This B is part of outer switch' );
end
Create a script file and type the following code in it −
a = 100;
b = 200;
switch(a) 
   case 100 
      fprintf('This is part of outer switch %d\n', a );
      switch(b) 
         case 200
            fprintf('This is part of inner switch %d\n', a );
      end
end

fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
When you run the file, it displays −
This is part of outer switch 100
This is part of inner switch 100
Exact value of a is : 100
Exact value of b is : 200
Docker – EXPOSE Instruction

28 Oct, 2020
The EXPOSE instruction exposes a particular port with a specified protocol inside a Docker Container.  In the simplest term, the EXPOSE instruction tells Docker to get all its information required during the runtime from a specified Port. These ports can be either TCP or UDP, but it’s TCP by default. It is also important to understand that the EXPOSE instruction only acts as an information platform (like Documentation) between the creator of the Docker image and the individual running the Container.  Some points to be noted are: 
It can use TCP or UDP protocol to expose the port.
Default Protocol is TCP if no other protocol is specified.
It does not map ports on the host machine.
It can be overridden using the publish flag (-p) while starting a Container.
The syntax to EXPOSE the ports by specifying a protocol is:
Syntax: EXPOSE <port>/<protocol>

In this article, we are going to discuss some practical examples of how to use EXPOSE instruction in your Dockerfile and overriding it using the publish flag while starting a Docker Container.
Follow the below steps to implement the EXPOSE instruction in a docker container:
Let’s create a Dockerfile with two EXPOSE Instructions, one with TCP protocol and the other with UDP protocol.
FROM ubuntu:latest
EXPOSE 80/tcp
EXPOSE 80/udp

To build the Docker Image using the above Dockerfile, you can use the Docker Build command.
sudo docker build -t expose-demo .

To run the Docker Container, you can use the Docker run command.
sudo docker run -it expose-demo bash

To verify the ports exposed, you can use the Docker inspect command.
sudo docker image inspect --format='' expose-demo 

In the above screenshot, you can see the ExposedPorts object contains two exposed ports that we have specified in the Dockerfile.
To publish all the exposed ports, you can use the -p flag.
sudo docker run -P -d expose-demo

You can just the list containers to check the published ports using the following command. But make sure that the Container is running.
sudo docker start <container-id>
sudo docker container ls

To conclude, in this article, we discussed how to use the EXPOSE instruction inside a Dockerfile to expose ports of a Container using a specified protocol and use -p flag to publish the ports.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Fuzzy Logic | Introduction
Monolithic vs Microservices architecture
Mounting a Volume Inside Docker Container
C# | UInt32 Struct - GeeksforGeeks

01 May, 2019
In C#, UInt32 struct is used to represent 32-bit unsigned integers(also termed as uint data type) starting from range 0 to 4,294,967,295. It also provides different types of methods to compare instances of this type, convert the value of an instance to its String representation, convert the String representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt32 struct inherits the ValueType class which inherits the Object class.
Example:
// C# program to illustrate the // fields of UInt32 structusing System;  class GFG {      // Main Method    static public void Main()    {          // Unsigned 32-bit integer        uint val = 4294967295;          // Checking the unsigned integer        if (val.Equals(UInt32.MinValue))         {            Console.WriteLine("Equal to MinValue!");        }          else if (val.Equals(UInt32.MaxValue))         {            Console.WriteLine("Equal to MaxValue!");        }        else {            Console.WriteLine("Not Equal!");        }    }}
Equal to MaxValue!

Example:
// C# program to illustrate how to get the// hash code of the 32-bit Unsigned integerusing System;  class GFG {      // Main Method    static public void Main()    {          // UInt32 variable        uint myval = 33453242;          // Get the hash code        // Using GetHashCode Method        int res = myval.GetHashCode();        Console.WriteLine("The hash code of myval is: {0}", res);    }}
The hash code of myval is: 33453242

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uint32?view=netframework-4.8
CSharp-UInt32-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Delegates
C# | Data Types
C# | Abstract Classes
C# | Replace() Method
Add a row at top in pandas DataFrame

In Pandas a DataFrame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can create a DataFrame using list, dict, series and another DataFrame. But when we want to add a new row to an already created DataFrame, it is achieved through a in-built method like append which add it at the end of the DataFrame. In this article we will find ways to add the new row DataFrame at the top of the DataFrame using some tricks involving the index of the elements in the DataFrame.
Let's first create a new DataFrame in Pandas shown as below.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
print df
Running the above code gives us the following result -
Age       Gender      Name
0         28          MTom
1         34          MJack
2         29          FMary
3         42          F Ricky
Approach 1 - The first approach we follow to add a new row at the top of the above DataFrame is to convert the new incoming row to a DataFrame and concat it with the existing DataFrame while resetting the index values. Because of Index reset the new row gets added at the top.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
top_row = pd.DataFrame({'Name':['Lavina'],'Age':[2],'Gender':['F']})
# Concat with old DataFrame and reset the Index.
df = pd.concat([top_row, df]).reset_index(drop = True)
print df
Running the above code gives us the following result -
         Age       Gender      Name
0         2          F         Lavina
1         28         M         Tom
2         34         M         Jack
3         29         F         Mary
4         42         F         Ricky
Approach 2 - In this approach we use the Dataframe.iloc[] method which allows us to add a new row at the index position 0. In the below example we are adding a new row as a list by mentioning the index value for the .loc method as 0 which is the index value for the first row.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
# Add a new row at index position 0 with values provided in list
df.iloc[0] = ['7', 'F','Piyu']
print df
Running the above code gives us the following result:
      Age    Gender   Name
0      7      F       Piyu
1      34     M       Jack
2      29     F       Mary
3      42     F       Ricky
AbstractCollection toString() method in Java with Examples - GeeksforGeeks

19 Dec, 2018
The toString() method of JavaAbstractClass is used to return a string representation of the elements of the Collection.
The String representation comprises a list representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.
Syntax:
Object.toString();
Parameter The method does not take any parameters.
Return This method returns a string representation of the collection.
Below examples illustrate the toString() method:
Example 1:
// Java program to demonstrate// Abstract Collection toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty AbstractCollection        AbstractCollection<String> abs            = new PriorityQueue<String>();          // Use add() method        // to add elements to the Collection        abs.add("Welcome");        abs.add("To");        abs.add("Geeks");        abs.add("For");        abs.add("Geeks");          // Using toString() method        System.out.println(abs.toString());    }}
[For, Geeks, To, Welcome, Geeks]

Example 2:
// Java program to demonstrate// Abstract Collection toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty AbstractCollection        AbstractCollection<Integer> abs            = new PriorityQueue<Integer>();          // Use add() method        // to add elements to the Collection        abs.add(10);        abs.add(20);        abs.add(30);        abs.add(40);          // Using toString() method        System.out.println(abs.toString());    }}
[10, 20, 30, 40]

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/AbstractCollection.html#toString–
Java - util package
Java-AbstractCollection
Java-Collections
Java-Functions
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
Clock Skew in synchronous digital circuit systems - GeeksforGeeks

17 Jan, 2022
In Synchronous circuits where all the logic elements share the same clock signal, it becomes imperative to design these elements as close to the clock source as possible because a system-on-chip, FPGA, CPLD contain Billions of transistors. Even though these distances are minute due to their sheer number there is a propagation delay which leads to the clock signal arriving at different parts of the chip at different times. This is called Clock Skew. 
In Digital Circuit Design a ” Sequentially Adjacent ” circuit is one where if a pulse emitted from a common source is supposed to arrive at the same time. Using this definition we can write a mathematical expression for clock skew as 
 
Sequentially Adjacent Circuit
 
Non-Sequentially Adjacent Circuit.
Ta(Time of arrival of clock pulse at component a) Tb(Time of arrival of clock pulse at component b) 
Then,  
Clock skew Ts = Ta - Tb 
Factors causing Clock Skew :  
Interconnect Length  
Temperature Variations  
Capacitive Coupling  
Material Imperfections  
Differences in input capacitance on the clock inputs  
Types of Clock Skew :  
Positive Skew – This occurs when the receiving register receives the clock pulse later than it is required.  
Negative Skew – This occurs when the receiving register receives the clock pulse earlier than required.  
 
Types of Clock Skews
 
varshagumber28
DIgital Logic & Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python?
C Program for Reversal algorithm for array rotation

An algorithm is a set of instructions that are performed in order to solve the given problem. Here, we will discuss the reversal algorithm for array rotation and create a program for a reversal algorithm.
Now, let's get to some terms that we need to know to solve this problem −
Array − A container of elements of the same data type. The size (number of elements) of the array is fixed at the time of the declaration of the array.
Array rotation − Rotating an array is changing the order of the elements of the array. Increasing the index of the element by one and changing the index of the last element to 0 and so on.
Example of array rotation,
Array[] = {3, 6, 8,1, 4, 10}
Rotated 2 times gives,
Array[] = {4, 10, 3, 6, 8, 1, 4}
Reversal Algorithm
One of the algorithms for array rotation is the reversal algorithm. In this algorithm, subarrays are created and reversed to perform the rotation of the array. Subarrays are created, rotated individually and then joined together and reversed back to get the rotated array.
Input : array arr[] , positions that are needed to be rotated r , length of array n.
Step 1: Split the array into two sub arrays of 0 - (d-1) and d - (n-1) size, a1 [d] and a2[n-d];
Step 2: Reverse both arrays using the reverse method.
Step 3: Join a1 and a2 back to get an array of original size.
Step 4: Reverse this joined array to get the rotated array.
Step 5: Print the array using the standard output method.
Example,
arr[] = {1 ,4, 2, 8, 3, 6, 5}, d = 3, n = 7
a1[]  = {1,4,2} ; a2 = {8,3,6,5}
a1r[] = {2,4,1} // reversed a1
a2r[] = {5,6,3,8} // reversed a2
ar[]  = {2,4,1,5,6,3,8} // a1r+a2r
arr[] = {8,3,6,5,1,4,2} // final answer.
 Live Demo
#include <stdio.h>
void reverse(int arr[], int start, int end){
   int temp;
   while (start < end) {
      temp = arr[start];
      arr[start] = arr[end];
      arr[end] = temp;
      start++;
      end--;
   }
}
int main(){
   int arr[] = { 54, 67, 12, 76, 25, 16, 34 };
   int n = 7;
   int d = 2;
   printf("The initial array is :\n");
   for (int i = 0; i < n; i++)
      printf("%d ", arr[i]);
   reverse(arr, 0, d - 1);
   reverse(arr, d, n - 1);
   reverse(arr, 0, n - 1);
   printf("\nThe left reversed array by %d elements is:\n",d);
   for (int i = 0; i < n; i++)
      printf("%d ", arr[i]);
   return 0;
}
The initial array is :
54 67 12 76 25 16 34
The left reversed array by 2 elements is:
12 76 25 16 34 54 67
How to plot rows of a data frame as lines in R?

To plot row of a data frame as lines, we can use matplot function but we would need to transpose the data frame because transposed values of the data frame will be read as columns and the matplot function plot the columns not rows. For example, if we have a data frame called df then the plot of rows as lines can be created by using the command −
matplot(t(df),type="l")
Consider the below data frame −
Live Demo
> x1<-rpois(5,2)
> x2<-rpois(5,5)
> x3<-rpois(5,3)
> df1<-data.frame(x1,x2,x3)
> df1
  x1 x2 x3
1  0  9  5
2  3  4  2
3  0  2  1
4  3  7  3
5  5 10  3
Creating plot of rows in df1 as lines −
> matplot(t(df1),type="l")
Live Demo
> y1<-rnorm(3)
> y2<-rnorm(3)
> y3<-rnorm(3)
> df2<-data.frame(y1,y2,y3)
> df2
          y1         y2         y3
1 -0.9992381 -1.3802480 -0.7228096
2  1.3677936  0.1813761  1.3711921
3  0.8905198 -1.0607813  0.3895616
1 -0.9992381 -1.3802480 -0.7228096
2  1.3677936  0.1813761  1.3711921
3  0.8905198 -1.0607813  0.3895616
Creating plot of rows in df2 as lines −
> matplot(t(df2),type="l")
Elm - Environment Setup

This chapter discusses steps to install Elm on Windows, Mac and Linux platforms.
Consider the steps shown below to install Elm in your local environment.
Step 1 − Install node
Since elm is compiled to JavaScript, the target machine should have node installed. Refer to TutorialsPoint NodeJS course for steps to setup node and npm
Step 2 − Install elm
Execute the following command on the terminal to install elm. Note that the stable version of elm was 0.18 at the time of writing this course.
npm install -g elm@0.18

After installation, execute the following command to verify the version of Elm.
C:\Users\dell>elm --version
0.18.0

Step 2 − Install the Editor
The development environment used here is Visual Studio Code (Windows platform).
Visual Studio Code is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VSCode is available at
In this section, we will discuss the steps to install Elm on Windows.
Download https://code.visualstudio.com/. for Windows.
Double-click on VSCodeSetup.exe to launch the setup process. This will only take a minute.
You may directly traverse to the file’s path by right clicking on File → Open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer.
Visual Studio Code’s Mac OS X specific installation guide can be found at VSCode Installation-MAC.
Visual Studio Code’s Linux specific installation guide can be found at VSCode Installation-Linux.
Step 4 − Install the elm Extension
Install the elm extension in VSCode as shown below.
REPL stands for Read Eval Print Loop. It represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode.
Elm comes bundled with a REPL environment. It performs the following tasks −
Read − Reads user's input, parses the input into elm data-structure, and stores in memory.
Read − Reads user's input, parses the input into elm data-structure, and stores in memory.
Eval − Takes and evaluates the data structure.
Eval − Takes and evaluates the data structure.
Print − Prints the result.
Print − Prints the result.
Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal.
Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal.
A simple example to add two numbers in REPL is shown below −
Open the VSCode terminal and type the command elm REPL.
The REPL terminal waits for the user to enter some input. Enter the following expression 10 + 20. The REPL environment processes the input as given below −
Reads numbers 10 and 20 from user.
Reads numbers 10 and 20 from user.
Evaluates using the + operator.
Evaluates using the + operator.
Prints result as 30.
Prints result as 30.
Loops for next user input. Here we exit from loop.
Loops for next user input. Here we exit from loop.

    27 Lectures 
     2.5 hours 

 Ahmed Elfakharany
 Print
 Add Notes
 Bookmark this page