code-rag-bench/online-tutorials huggingface dataset:
Angular Material 7 - Paginator

The <mat-paginator>, an Angular Directive, is used to show a navigator with paged information.
In this chapter, we will showcase the configuration required to show a paginator using Angular Material.
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatPaginatorModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatPaginatorModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-paginator [length] = "100"
   [pageSize] = "10"
   [pageSizeOptions] = "[5, 10, 25, 100]"
   (page) = "pageEvent = $event">
</mat-paginator>
<div *ngIf = "pageEvent">
   <h5>Page Change Event</h5>
   <div>List length: {{pageEvent.length}}</div>
   <div>Page size: {{pageEvent.pageSize}}</div>
   <div>Page index: {{pageEvent.pageIndex}}</div>
</div>
Verify the result.
Here, we've created a paginator using mat-paginator and handles its change event.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Performing Database Transactions using Python

Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
You already know how to implement transactions. Here is again similar example −
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
String Interpolation in Dart Programming

There are times when we want to make use of variables inside the statement that is made up of string values.
We know that we can add two strings together in Dart with the help of the + symbol operator. But to make use of a variable in between the strings that we are concatenating, we need to add one more + symbol and then type the name of the variable, which works okay when it comes to small statements.
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials";
   var collegeName = "DTU";
   print("Name is " + name + " college Name is " + collegeName);
}
Name is Tutorials college Name is DTU
In the above example, we have both the variables of type string, but what about the case, where we want to make use of an integer in between the print() function statement.
Consider the example shown below −
void main(){
   String name = "Tutorials";
   var collegeID = 10602;
   print("Name is " + name + " college Name is " + collegeID);
}
In the above example, we have a string and we are trying to assign an int to it (collegeID). Dart doesn't allow such a process, as it is statically typed, and the compiler will throw an error.
Error: A value of type 'int' can't be assigned to a variable of
type 'String'.
   print("Name is " + name + " college Name is " + collegeID);
The workaround for the above problem is to make use of string interpolation, where we pass the variable into the string statement with a special syntax.
'print this ${variable}'
Consider the example shown below −
 Live Demo
void main(){
   String name = "Tutorials";
   var collegeID = 10602;
   print("Name is ${name} and collegeID is ${collegeID}");
}
Name is Tutorials and collegeID is 10602
Difference between SVG and HTML 5 Canvas - GeeksforGeeks

22 Apr, 2020
SVG: The Scalable Vector Graphics (SVG) is an XML-based image format that is used to define two-dimensional vector-based graphics for the web. Unlike raster image (Ex .jpg, .gif, .png, etc.), a vector image can be scaled up or down to any extent without losing the image quality.
An SVG image is drawn out using a series of statements that follow the XML schema — that means SVG images can be created and edited with any text editor, such as Notepad. There are several other advantages of using SVG over other image formats like JPEG, GIF, PNG, etc.
Example:
<!DOCTYPE html><html>  <head>    <style>        #svgelem {            position: relative;            left: 50%;            -webkit-transform: translateX(-20%);            -ms-transform: translateX(-20%);            transform: translateX(-20%);        }    </style>    <title>HTML5 SVG</title></head>  <body>    <h2 align="center">        SVG Circle(Geeks For Geeks)    </h2>      <svg id="svgelem" height="200">        <circle id="greencircle" cx="60"            cy="60" r="50" fill="green" />    </svg></body>  </html>
Output:
Canvas: The HTML element is used to draw graphics on the fly, via scripting (usually JavaScript). The element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML5 Canvas Tag</title></head>  <body>    <h2>Canvas Square(Geeks For Geeks)</h2>      <canvas id="newCanvas" width="100" height="100"        style="border:1px solid #000000;">    </canvas>          <script>        var c = document.getElementById('newCanvas');        var ctx = c.getContext('2d');        ctx.fillStyle = '#7cce2b';        ctx.fillRect(0, 0, 100, 100);    </script></body>  </html>
Output:
Difference between SVG and HTML5 Canvas:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Canvas
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to use Bootstrap to align labels with content into 4 columns ?

08 Jul, 2019
<!DOCTYPE html><html>  <head>    <title>        How to use Bootstrap to align labels        with content into 4 columns ?    </title>          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">      <style>        form {            margin-top: 30px;            margin-bottom: 30px;            padding-bottom: 25px;        }        .form-area {            margin-top: 30px;        }        label {            display: block;            color: black;            font-weight: bold;        }    </style></head>  <body>    <h1 style="color:green">GeeksforGeeks</h1>    <hr>    <form>        <div class="row">            <div class="col">                  <div class="row">                    <div class="col">                        <label>HTML</label>                    </div>                    <div class="col">                        <p>                            Learn to Design your First                            Website in Just 1 Week                        </p>                    </div>                </div>                  <div class="row">                    <div class="col">                        <label>CSS</label>                    </div>                    <div class="col">                        <p>                            Cascading Style Sheets, fondly                            referred to as CSS                        </p>                    </div>                </div>                  <div class="row">                    <div class="col">                        <label>JavaScript</label>                    </div>                    <div class="col">                        <p>JavaScript Tutorials</p>                    </div>                </div>              </div>              <div class="col">                <div class="row">                    <div class="col">                        <label>Front-end</label>                    </div>                    <div class="col">                        <p style="font-weight: italic; color: grey">                            “Front End” typically refers to all the                             kinds of stuff that the user actually sees                             on the website, once it loads completely.                             This is why it is also called the “client-side”                            of the front-end.                        </p>                    </div>                </div>            </div>        </div>    </form></body>  </html>                    
Output:
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Should I join a mass recruiter or a startup?

01 Oct, 2018
A Startup as the name suggests, is a young company that is just beginning to develop and usually small in size and have bare minimum finances. These companies generally offer a product or service that is not currently being offered elsewhere in the market, means based on new ideas or that the founders believe is being offered in an inferior manner till now in the market. Startups are operated by a handful of founders or one individual. Working in a startup environment offers to ample work, huge learning, great experience and might not be good initially for a handsome salary. Starting a career at a Tech Startup can give you a massive exposure to learning.
Companies like Infosys, Wipro, Accenture, Tech Mahindra, Tata Consultancy Services or other MNCs on the other hand, do mass recruitment frequently from various colleges usually, IT-Services based Multinational Companies. The work in these companies is usually service based and needs a decent level of aptitude by an engineer. In most of the job profiles, neither the job expectation nor salaries are very high in these workplaces.There are some benefits and drawbacks in working with these Startups or MNCs. Some people like to work with Startups and some of the them like to work with MNCs.
Seeing the pros and cons side by side as follows:
Most employees like to work with startup, but this is up to you. It is recommend to you if you are a fresher, in the early years of building your career put your focus more on learning rather than the pay, cause knowledge will take up further on the long run.
Career-Advices
Picked
GBlog
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List removeAll() method in Java with Examples

02 Jan, 2019
This method is used to remove all the elements present in the collection from the specified list.
Syntax:
boolean removeAll(Collection c)
Parameters: This method has only argument, collection of which elements are to be removed from the given list.
Returns: This method returns True if elements are removed and list changes.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// removeAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(10);        l.add(30);        l.add(50);        l.add(70);        l.add(90);        System.out.println(l);          ArrayList<Integer> arr = new ArrayList<>();        arr.add(30);        arr.add(50);        l.removeAll(arr);          System.out.println(l);    }}
[10, 30, 50, 70, 90]
[10, 70, 90]

Program 2: Below is the code to show implementation of list.removeAll() using Linkedlist.
// Java code to show the implementation of// removeAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<String> l = new LinkedList<>();        l.add("10");        l.add("30");        l.add("50");        l.add("70");        l.add("90");        System.out.println(l);          ArrayList<String> arr = new ArrayList<>();        arr.add("30");        arr.add("50");        l.removeAll(arr);          System.out.println(l);    }}
[10, 30, 50, 70, 90]
[10, 70, 90]

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java
Implementing Deep Q-Learning using Tensorflow

18 Jun, 2019
Prerequisites: Deep Q-Learning
This article will demonstrate how to do reinforcement learning on a larger environment than previously demonstrated. We will be implementing Deep Q-Learning technique using Tensorflow.
Note: A graphics rendering library is required for the following demonstration. For Windows operating system, PyOpenGl is suggested while for Ubuntu operating system, OpenGl is recommended.
Step 1: Importing the required libraries
import numpy as npimport gym  from keras.models import Sequentialfrom keras.layers import Dense, Activation, Flattenfrom keras.optimizers import Adam  from rl.agents.dqn import DQNAgentfrom rl.policy import EpsGreedyQPolicyfrom rl.memory import SequentialMemory
Step 2: Building the Environment
Note: A preloaded environment will be used from OpenAI’s gym module which contains many different environments for different purposes. The list of environments can be viewed from their website.
Here, the ‘MountainCar-v0’ environment will be used. In this, a car(the agent) is stuck between two mountains and has to drive uphill on one of them. The car’s engine is not strong enough to drive up on it’s own and thus the car has to build momentum to get uphill
# Building the environmentenvironment_name = 'MountainCar-v0'env = gym.make(environment_name)np.random.seed(0)env.seed(0)  # Extracting the number of possible actionsnum_actions = env.action_space.n
Step 3: Building the learning agent
The learning agent will be built using a deep neural network and for the same purpose, we will be using the Sequential class of the Keras module.
agent = Sequential()agent.add(Flatten(input_shape =(1, ) + env.observation_space.shape))agent.add(Dense(16))agent.add(Activation('relu'))agent.add(Dense(num_actions))agent.add(Activation('linear'))
Step 4: Finding the Optimal Strategy
# Building the model to find the optimal strategystrategy = EpsGreedyQPolicy()memory = SequentialMemory(limit = 10000, window_length = 1)dqn = DQNAgent(model = agent, nb_actions = num_actions,               memory = memory, nb_steps_warmup = 10,target_model_update = 1e-2, policy = strategy)dqn.compile(Adam(lr = 1e-3), metrics =['mae'])  # Visualizing the training dqn.fit(env, nb_steps = 5000, visualize = True, verbose = 2)
The agent tries different methods to reach the top and thus gaining knowledge from each episode.
Step 5: Testing the Learning Agent
# Testing the learning agentdqn.test(env, nb_episodes = 5, visualize = True)
The agent tries to apply it’s knowledge to reach the top.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
KnockoutJS - push() Method

The KnockoutJS Observable push('value') method inserts a new item at the end of an array.
arrayName.push('value')

Accepts only one parameter, that is the value to be inserted.
<!DOCTYPE html>
   <head>
      <title>KnockoutJS Observable Array push() Method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" 
         type = "text/javascript"></script>
   </head>
   
   <body>
      <p>Example to demonstrate push() method.</p>
      <p>Enter name: <input data-bind = 'value: empName' /></p>
      <p><button data-bind = "click: addEmp">Add Emp </button></p>
      <p>Array of employees: <span data-bind = "text: empArray()" ></span></p>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee', 'RoseMary','Kathie']);  //Initial Values
            
            this.addEmp = function() {
               
               if (this.empName() != "") {
                  this.empArray.push(this.empName());    //insert accepted value in array
                  this.empName("");
               }
            }.bind(this);
         }
         
         var emp = new EmployeeModel();
         ko.applyBindings(emp);
      </script>
      
   </body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above code in array-push.htm file.
Save the above code in array-push.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Type 'Tom' as an input and click the Add Emp button.
Type 'Tom' as an input and click the Add Emp button.
Example to demonstrate push() method.
Enter name: 
Add Emp 
Array of employees: Scott,James,Jordan,Lee,RoseMary,Kathie

    38 Lectures 
     2 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How do I get the height and width of the Android Navigation Bar programmatically?

This example demonstrates how do I get the height and width of the android navigation bar programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Android Navigation Bar Height and Width"
   android:textSize="16sp"
   android:textStyle="bold" />
<TextView
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="24sp"
   android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.textView);
      Resources resources = getApplicationContext().getResources();
      int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
      if (resourceId > 0) {
         textView.setText(resourceId);
      }
   }
}

Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
PHP mysqli_num_rows() Function

A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries.
The mysqli_num_rows() function accepts a result object as a parameter, retrieves the number of rows in the given result.
mysqli_num_rows($result);

result(Mandatory)
This is an identifier representing a result object.
The PHP mysqli_num_rows() function returns an integer value representing the number of rows/records in the given result object.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_num_rows() function (in procedural style) −
<?php
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
   print("Table Created.....\n");
   mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')");
   mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
   mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')");
   print("Record Inserted.....\n");

   //Retrieving the contents of the table
   $result = mysqli_query($con, "SELECT * FROM myplayers");

   //Number of rows
   $count = mysqli_num_rows($result);
   print("Number of rows in the result: ".$count);

   //Closing the statement
   mysqli_free_result($result);

   //Closing the connection
   mysqli_close($con);
?>
This will produce following result −
Table Created.....
Record Inserted.....
Number of rows in the result: 3

In object oriented style the syntax of this function is $result->num_rows; Following is the example of this function in object oriented style $minus;
<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)");
   $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)");
   print("Table Created.....\n");

   $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)");
   $stmt -> bind_param("ss", $name1, $name2);
   $name1 = 'Raju';
   $name2 = 'Rahman';

   //Executing the statement
   $stmt->execute();

   //Retrieving the result
   $result = $stmt->get_result();

   //Number of rows
   $count = $result->num_rows;
   print("Number of rows in the result: ".$count);

   //Closing the statement
   $stmt->close();

   //Closing the connection
   $con->close();
?>
This will produce following result −
Table Created.....
Number of fields in the result: 2


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Purpose of Unions in C/ C++

Union is a user-defined datatype. All the members of union share same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that.
Unions are similar to structures. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language.
Here is the syntax of unions in C language,
union union_name {
   member definition;
} union_variables;
Here,
union_name  − Any name given to the union.
union_name  − Any name given to the union.
member definition  − Set of member variables.
member definition  − Set of member variables.
union_variable  − This is the object of union.
union_variable  − This is the object of union.
Here is an example of unions in C language,
 Live Demo
#include <stdio.h>
#include <string.h>

union Data {
   int i;
   float f;
} data, data1;

int main( ) {
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
   return 0;
}
Here is the output
Memory size occupied by data : 4 4
How to convert Matplotlib figure to PIL Image object?

To convert matplotlib figure to PIL image object, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Plot a list using plot() method.
Initialize the in-memory buffer.
Save the buffered image.
Use PIL image to get the image object.
Show the current image.
Close the in-memory I/O buffer.
import io
from PIL import Image
import matplotlib.pyplot as plt

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

plt.figure()
plt.plot([1, 2])

img_buf = io.BytesIO()
plt.savefig(img_buf, format='png')

im = Image.open(img_buf)
im.show(title="My Image")

img_buf.close()
C# program to convert a list of characters into a string

Firstly, declare the character array and set the value of each character −
char[] ch = new char[5];

ch[0] = 'H';
ch[1] = 'e';
ch[2] = 'l';
ch[3] = 'l';
ch[4] = 'o';
Now, use the string class constructor and create a new string from the above array of characters −
string myChar = new string(ch);
Let us see the code to convert a list of characters to string in C#.
Live Demo
using System;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         char[] ch = new char[5];
         ch[0] = 'H';
         ch[1] = 'e';
         ch[2] = 'l';
         ch[3] = 'l';
         ch[4] = 'o';
         string myChar = new string(ch);
         Console.WriteLine("Converted to string = {0}", myChar);
      }
   }
}
Converted to string = Hello
Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number

When it is required to create a list of tuple, and have the first element as the number, and the second element as the square of the element, list comprehension can be used.
Below is the demonstration of the same −
 Live Demo
my_list = [23, 42, 67, 89, 11, 32]
print(“The list is “)
print(my_list)
print(“The resultant tuple is :”)
my_result = [(val, pow(val, 2)) for val in my_list]
print(my_result)
The list is
[23, 42, 67, 89, 11, 32]
The resultant tuple is :
[(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]
A list is defined, and is displayed on the console.
A list is defined, and is displayed on the console.
The list comprehension is used and the ‘pow’ method is used to find the square of the number.
The list comprehension is used and the ‘pow’ method is used to find the square of the number.
This is converted to a list.
This is converted to a list.
The output is displayed on the console.
The output is displayed on the console.
Clock Speed - GeeksforGeeks

29 Dec, 2020
A CPU can not operate alone when we give huge amount of data and instructions to it simultaneously. It needs other components to work for it and for this it requires a clock which synchronizes all the components of the system.
Rate at which a processor completes its total processing cycle in one second is called as its ‘clock speed’. It is also known as clock rate. The performance of CPU has a major impact on the speed at which a program is loaded and then executed. It is usually measured in Megahertz or Gigahertz .In modern CPU, we measure clock speed in Gigahertz.
1 Megahertz = 1, 000, 000 cycles / sec
1 Gigahertz = 1, 000, 000, 000 cycles / sec 
Examples :
A CPU with a clock speed of 4.2 MHz executes 4.2 Million cycles per second.
A CPU with a clock speed of 4.2 GHz executes 4.2 Billion cycles per second.
Generally, it is said that higher the clock speed, faster the CPU. But this may not be the only reason for a faster CPU. There are many factors behind it like number of processors, speed of RAM, bus speed, size of cache etc. Some instructions require more cycles from CPU to be completed . Depending upon the architecture of CPU the clock speed can be more or less important. Some CPU can actually perform faster at slower clock speed while some processor’s architecture focuses more on high clock speed with few instructions per cycle.
Speed of CPU determines number of calculations it can perform in one second of time. However, the speed of the CPU clock for processing power can be increased by ‘overclocking’. But as you raise the clock speed there can be stability issues and your system might get crashed. Higher clock speeds can generate more heat so, to keep themselves away from dangerous overheating, processors will strangle down to a lower frequency when they get overheated. This can happen when you don’t give enough power to your CPU. Overclocking may also lead to over volting.
Overvolting is when you raise the voltage given to the chip in order to increase the clock speed.
Altair 8800, the first commercial PC used an Intel 8080 CPU with clock rate of 2 MHz (2 Million cycles / sec) and Intel P5 Pentium has clock rate of 100 MHz (100 Million cycles / sec) . In 2000, AMD was the first processor that reached 1 GHz (1 Billion cycles / sec). In 2002, an Intel Premium 4 was the first CPU with clock rate of 3GHz (3 Billion cycles / sec).
Computer Organization & Architecture
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Direct Access Media (DMA) Controller in Computer Architecture
Pin diagram of 8086 microprocessor
Difference between SRAM and DRAM
Computer Organization | Different Instruction Cycles
Shift Micro-Operations in Computer Architecture
I2C Communication Protocol
Difference between RISC and CISC processor | Set 2
General purpose registers in 8086 microprocessor
Core Dump (Segmentation fault) in C/C++

In this tutorial, we will be discussing a program to understand core dump (segmentation fault) in C/C++.
It happens due to reasons like when code tries to write on read only memory or tries to access corrupt memory location.
int main(){
   char *str;
   str = "GfG";
   *(str+1) = 'n';
   return 0;
}
#include <iostream>
using namespace std;
int main(){
   int arr[2];
   arr[3] = 10;
   return 0;
}
#include <stdio.h>
#include<alloc.h>
int main(void){
   int* p = malloc(8);
   *p = 100;
   free(p);
   *p = 110;
   return 0;
}
Abnormal termination of program
How to use Consumer and BiConsumer interfaces in lambda expression in Java?

A Consumer interface is a predefined functional interface that can be used when creating lambda expressions or method references. This interface represents an operation that accepts a single input parameter and doesn't return anything. It contains only one method named accept(). The BiConsumer interface is similar to a Consumer interface and accepts two input parameters and doesn’t return anything.
@FunctionalInterface
public interface Consumer<T>

@FunctionalInterface
public interface BiConsumer<T, U>
import java.util.*;
import java.util.function.*;

public class ConsumerBiConsumerTest {
   public static void main(String[] args) {
      Consumer<String> c = (x) -> System.out.println(x.toLowerCase());  // lambda expression
      c.accept("Raja");
 
      Consumer<Integer> con = (x) -> {  // lambda expression
         System.out.println(x + 10);
         System.out.println(x - 10);
      };
      con.accept(10);

      BiConsumer<Strng, String> bc = (x, y) -> { System.out.println(x + y);};
      bc.accept("1", "2");

      List<Person> plist = Arrays.asList(new Person("RAJA"), new Person("ADITHYA"));
      acceptAllEmployee(plist, p -> System.out.println(p.name));
      acceptAllEmployee(plist, p -> {p.name = "unknown";});
      acceptAllEmployee(plist, p -> System.out.println(p.name));
   }
   public static void acceptAllEmployee(List<Person> plist, Consumer<P> con) {
      for(Person p : plist) {
         con.accept(p);
      }
   }
}

// Person class
class Person {
   public String name;
   public Person(String name) {
      this.name = name;
   }
}
raja
20
0
12
RAJA
ADITHYA
unknown
unknown
Matplotlib.pyplot.fill() function in Python - GeeksforGeeks

25 Nov, 2020
Matplotlib.pyplot.fill() function is used to fill the area enclosed by polygon /curve.
Syntax: matplotlib.pyplot.fill(*args, data=None, **kwargs)
Parameters:*args: sequence of x, y, [color]      sequence of x,y = To traverse the boundaries of the polygon or curve defined by lists of x and y positions of its nodes.color = To change the default fill color to the desired one.You can plot multiple polygons by providing multiple x, y, [color] groups.data: indexable object, optional     default value = none     You can directly provide labeled data in the form of a dictionary. For better understanding refer to Example2
Returns: A list of Polygon
Other Parameters:**kwargs: Supports all other properties of Polygon patch.
Example 1:
Python3
# Importing the libraryimport matplotlibimport matplotlib.pyplot as pltimport numpy as np  # Data for plottingx = np.arange(0.0, 2.0, 0.01)y = 1 + np.sin(2 * np.pi * x)plt.plot(x, y)  # Assighning plot attributesplt.xlabel("angle")plt.ylabel("sine")plt.title('sine wave')  # Filling sign wave curv with cyan colorplt.fill(x, y, "c")plt.show()
 Output:
Example 1_Output_GFG
Example 2: 
Python3
# Importing librariesimport matplotlibimport matplotlib.pyplot as plt    # Below we are using data attributeplt.fill("j", "k", 'm',         data={"j": [0, 1, 2],               "k": [0, 1, 0]})  # here 'm' for magenta
Output:
Example 2_Output_GFG
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to get the row count of a Pandas DataFrame?

To get the row count of a Pandas DataFrame, we can use the length of DataFrame index.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame.
Print the input DataFrame.
Print the length of the DataFrame index list, len(df.index).
Print the length of the DataFrame index list, len(df.index).
 Live Demo
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print "Input DataFrame is:\n", df
print "Row count of DataFrame is: ", len(df.index)
Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0
Row count of DataFrame is: 4
Java Program to enable drag and drop between two text fields in Java

Yes, we can enable drag and drop between two text fields in Java. Let us first create two JTextFields and set content in it as shown below −
JTextField one = new JTextField(20);
one.setText("You can drag!");
JTextField two = new JTextField(20);
two.setText("Drag here or there");
Now, we will enable and drag and drop for both the components created above −
one.setDragEnabled(true);
two.setDragEnabled(true);
The following is an example to enable drag and drop between two text fields −
package my;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("Drag and Drop the two TextFields below: ", SwingConstants.LEFT);
      JTextField one = new JTextField(20);
      one.setText("You can drag!");
      one.setDragEnabled(true);
      JTextField two = new JTextField(20);
      two.setText("Drag here or there");
      two.setDragEnabled(true);
      frame.add(label);
      frame.add(one);
      frame.add(two);
      Container content = frame.getContentPane();
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
      content.add(one);
      content.add(two);
      frame.setSize(600,250);
      frame.setVisible(true);
   }
}
Now, we will drag from TextField 1 to the 2nd TextField. We have dragged successfully above −
Python - Create a Time Series Plot with multiple columns using Line Plot

To create a Time Series Plot with multiple columns using Line Plot, use the lineplot(). At first, import the required libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame. We have multiple columns in our DataFrame −
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 51, 70, 70, 87, 76],'Units Returned' : [60, 50, 40, 57, 62, 51, 60]
})
Plot time series plot for multiple columns −
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)
sb.lineplot(x="Date_of_Purchase", y="Units Returned", data=dataFrame)
Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# creating DataFrame
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 51, 70, 70, 87, 76],'Units Returned' : [60, 50, 40, 57, 62, 51, 60]
})

# time series plot for multiple columns
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)
sb.lineplot(x="Date_of_Purchase", y="Units Returned", data=dataFrame)

# set label
plt.ylabel("Units Returned Unites Sold")

plt.show()
This will produce the following output −
wxPython – Change labels using button

10 May, 2020
In this article we are going to learn how to make button interactive with the frame. In this article we will change the text label on the pressing button. So let’s start with the steps.
Step 1: Create a static text on the frame.Step 2: Add button to the frame.Step 3: Create event function for the button.Step 4: Add code to change text label in this function.
Code :
# import wxPythonimport wx  class Example(wx.Frame):    def __init__(self, *args, **kw):        super(Example, self).__init__(*args, **kw)          # function to get response after click        def onButton(event):            print("Button")            st.SetLabel("GeeksforGeeks")          # static text        st = wx.StaticText(self, label ="Welcome to ")          # create button        button = wx.Button(self, wx.ID_ANY, 'Test', (10, 40))          # bind onButton() function with button        button.Bind(wx.EVT_BUTTON, onButton)  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()  if __name__ == '__main__':    main()
Output:1. Before clicking:
2.After Clicking
Python-gui
Python-wxPython
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
Read a file line by line 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
Python OOPs Concepts
LocalDate parse() method in Java with Examples

27 Jan, 2022
In LocalTime class, there are two types of parse() method depending upon the parameters passed to it. 
parse() method of a LocalTime class used to get an instance of LocalTime from a string such as ‘2018-10-23’ passed as parameter.The string must have a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.Syntax:  
public static LocalTime parse(CharSequence text)
Parameters: This method accepts only one parameter text which is the text to parse in LocalTime. It should not be null.Return value: This method returns LocalTime which is the parsed local date-time.Exception: This method throws DateTimeParseException if the text cannot be parsed.Below programs illustrate the parse() method: Program 1:  
Java
// LocalDate.parse() method import java.time.*; public class GFG {    public static void main(String[] args)    {         // create an LocalDate object        LocalDate lt            = LocalDate.parse("2018-12-27");         // print result        System.out.println("LocalDate : "                           + lt);    }}
LocalDate : 2018-12-27
 
parse() method of a LocalTime class used to get an instance of LocalTime from a string such as ‘2018-10-23’ passed as parameter using a specific formatter.The date-time is parsed using a specific formatter.Syntax:  
public static LocalTime parse(CharSequence text,
                              DateTimeFormatter formatter)
Parameters: This method accepts two parameters text which is the text to parse and formatter which is the formatter to use.Return value: This method returns LocalTime which is the parsed local date-time.Exception: This method throws DateTimeParseException if the text cannot be parsed.Below programs illustrate the parse() method: Program 1:  
Java
// Java program to demonstrate// LocalDate.parse() method import java.time.*;import java.time.format.*; public class GFG {    public static void main(String[] args)    {         // create a formatter        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM uuuu");         // create a LocalDate object and        LocalDate lt            = LocalDate.parse("31 Dec 2018", formatter);         // print result        System.out.println("LocalDate : "                           + lt.toString());    }}
LocalDate : 2018-12-31
 
References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#parse(java.lang.CharSequence) https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#parse(java.lang.CharSequence, java.time.format.DateTimeFormatter) 
saurabh1990aror
java-basics
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Stack Class in Java
Initialize an ArrayList in Java
How to check if a variable exists in JavaScript?

To check if a variable exists in JavaScript, you need to check it against null as in the following code. Here, we’re checking the existence of variable myVar −
<html>
   <body>
      <script>
         var myVar = 20;
         if(myVar !== undefined && myVar !== null) {
            document.write("Variable exists");
         }
      </script>
   </body>
</html>
How to change font size using jQuery ?

30 Sep, 2021
In this article, we will see how to change the font size of an element using jQuery. To change the font size of an element, we will use css() method. 
The css() method is used to change the style property of the selected element.
Syntax:
$(selector).css(property)
Return value: It will return the value of the property for the selected element. 
In the below example, we have created a div element that contains some text and also created a button element. When the user clicks on the button, the css() method is called and this method sets the font-size property value to 32px.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <!-- Including jQuery -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script></head>  <body>    <center>        <h1 style="color: green;">            GeeksforGeeks        </h1>          <h3>            How to change font size using jQuery?        </h3>          <div id="content">Welcome to GeeksforGeeks</div>        <br>          <button>Change font size</button>    </center>      <script>        $(document).ready(function() {            $('button').click(function() {                $("#content").css("fontSize", "32px");            });        });    </script></body>  </html>
Output: 
HTML-Questions
jQuery-Methods
jQuery-Questions
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples
How to click a link whose href has a certain substring in Selenium?

We can click a link whose href has a certain substring in the Selenium webdriver. There are multiple ways to perform this action. We can use find_element_by_partial_link_text() method to click on a link having a substring.
The find_element_by_partial_link_text() method is used to identify an element by partially matching with the text within the anchor tag as specified in the method parameter. If there is no matching text, NoSuchElementException is thrown.
Syntax −
find_element_by_partial_link_text("Tutors")
Also we can use css selector to identify the element whose href has a substring via * symbol. This is called wild character notation and implies that a string contains a certain substring.
Syntax −
find_element_by_css_selector("a[href*"='tutor'] ")
Let us try to identify the Net Meeting link in the above html code with the substring concept.
Code Implementation with find_element_by_partial_link_text().
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/codingground.htm")
# identify element with partial link text and click()
l=driver.find_element_by_partial_link_text("Net")
l.click()
print("Page title after click on substring link name:" + driver.title)
driver.quit()
Code Implementation with href attribute.
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/codingground.htm")
# identify element with href attribute and click()
l= find_element_by_css_selector("a[href*"='net'] ")
l.click()
print("Page title after click on substring link name:" + driver.title)
driver.quit()