code-rag-bench/online-tutorials huggingface dataset:
How to create a Scheduled task with a task scheduler using PowerShell?

To create a task using GUI (As shown below image) we need a few settings like the Name of the task, trigger, and Action.
Similarly, to create a new task in task scheduler using PowerShell comprises of several settings.
Name of the task
The time when the task to trigger
Action − Do we need to schedule a program for execution or send an email on some event trigger.
Description − This is optional. You can add a description of the task.
Registering task − Final step is to register the created task.
Above all actions use different cmdlets but they are part of a ScheduledTasks module. To schedule task on local or remote servers, you need to ensure the module should be present on the server.
Get-Module ScheduledTasks | Select -ExpandProperty ExportedCommands
Let's begin creating a task.
Creating a new Task Action.
$tsaction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Temp\TestTask.ps1'
Mention the user account to run the script (optional).
$User= "NT AUTHORITY\SYSTEM"
Creating a time to trigger a task.
$tstrigger = New-ScheduledTaskTrigger -At 4:00PM -Once
You can provide the various timing for a routine task like Daily, monthly, or other as shown in the below example. In this example, we need to run a task once at 4:00 PM.
Register Schedule task.
Once the required settings are configured for a task, we need to register the task at the final step to appear in the task scheduler using the below command line.
               
Register-ScheduledTask `
  -TaskName 'Test Task' `
  -User $User `
  -Action $tsaction `
  -Trigger $tstrigger `
  -RunLevel Highest -Force
Final Script:
$tsaction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Temp\TestTask.ps1'$User= "NT AUTHORITY\SYSTEM"
$tstrigger = New-ScheduledTaskTrigger -At 4:00PM -Once
$tstrigger = New-ScheduledTaskTrigger -At 4:00PM -Once
Register-ScheduledTask `
 -TaskName 'Test Task' `
  -User $User `   -Action $tsaction `  -Trigger $tstrigger `   -RunLevel Highest -Force
  -User $User `
   -Action $tsaction `
  -Trigger $tstrigger `
Once you run the above command, task will be created. Output will be as shown in the console.
You can check the same in the task scheduler.
How to sort a dictionary in Python by values?

Standard distribution of Python contains collections module. It has definitions of high performance container data types. OrderedDict is a sub class of dictionary which remembers the order of entries added in dictionary object. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
>>> from collections import OrderedDict
>>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'}
>>> OrderedDict(D.items())
 OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])
We also need to us sorted() function that sorts elements in an iterable in a specified order. The function takes a function as argument which is used as key for sorting. Since we intend to sort dictionary on values, we take 1st element of tuple as key for sorting.
>>> OrderedDict(sorted(D.items(), key=lambda t: t[1]))
   OrderedDict([(4, 'bbb'), (2, 'ddd'), (5, 'fff'), (1, 'ooo'), (3, 'ttt')])
The OrderedDict object can be parsed into a regular dictionary object
>>> D1 = dict(OrderedDict(sorted(D.items(), key = lambda t: t[1])))
>>> D1
   {4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}
Find Minimum, Maximum, and Average Value of PySpark Dataframe column - GeeksforGeeks

29 Jun, 2021
In this article, we are going to find the Maximum, Minimum, and Average of particular column in PySpark dataframe.
For this, we will use agg() function. This function Compute aggregates and returns the result as DataFrame.
Syntax: dataframe.agg({‘column_name’: ‘avg/’max/min})
Where,
dataframe is the input dataframe
column_name is the column in the dataframe
Creating DataFrame for demonstration:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql # modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app# namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  datadata = [["1", "sravan", "vignan", 67, 89],        ["2", "ojaswi", "vvit", 78, 89],        ["3", "rohith", "vvit", 100, 80],        ["4", "sridevi", "vignan", 78, 80],        ["1", "sravan", "vignan", 89, 98],        ["5", "gnanesh", "iit", 94, 98]]  # specify column namescolumns = ['student ID', 'student NAME',           'college', 'subject 1', 'subject 2']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  # display dataframedataframe.show()
Output:
Example 1: Python program to find the average of dataframe column
Python3
# find average of subjects columndataframe.agg({'subject 1': 'avg'}).show()
Output:
Example 2: Get average from multiple columns
Python3
# find average of multiple  columndataframe.agg({'subject 1': 'avg',               'student ID': 'avg',               'subject 2': 'avg'}).show()
Output:
Example 1: Python program to find the minimum value in dataframe column.
Python3
# minimum value from student ID columndataframe.agg({'student ID': 'min'}).show()
Output:
Example 2: Get minimum value from multiple columns
Python3
# minimum value from multiple columndataframe.agg({'college': 'min',               'student NAME': 'min',               'student ID':'min'}).show()
Output:
Example 1: Python program to find the maximum value in dataframe column
Python3
# maximum value from student ID columndataframe.agg({'student ID': 'max'}).show()
Output:
Example 2: Get maximum value from multiple columns
Python3
# maximum value from multiple columndataframe.agg({'college': 'max',               'student NAME': 'max',               'student ID':'max'}).show()
Output:
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Print lists in Python (4 Different Ways)
NumPy Creating Arrays

NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
We can create a NumPy
ndarray object by using the array() function.
type(): This built-in Python function tells us the type of the object passed to it. Like in above code 
  it shows that arr is 
  numpy.ndarray type.
To create an ndarray,
we can pass a list, tuple or any array-like object into the array() 
method, and it will be converted into an
ndarray:
Use a tuple to create a NumPy array:
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.
0-D arrays, 
or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Create a 0-D array with value 42
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Create a 1-D array containing the values 1,2,3,4,5:
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations called
numpy.mat
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Create a 3-D array with two 2-D arrays, both containing two arrays with the 
values 1,2,3 and 4,5,6:
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
Check how many dimensions the arrays have:
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using 
the ndmin argument.
Create an array with 5 dimensions and verify that it has 5 dimensions:
In this array the innermost dimension (5th dim) has 4 elements,
the 4th dim has 1 element that is the vector,
the 3rd dim has 1 element that is the matrix with the vector,
the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
Insert the correct method for creating a NumPy array.
arr = np.([1, 2, 3, 4, 5])

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to load a page in div using jQuery?

To load a page in div in jQuery, use the load() method. Firstly, add the web page you want to add.
Here’s the code for new.html −
<html>
<head>    
</head>
<body>
<p>This is demo text.<p>
</body>
</html>
Now, the code snippet for the file which adds the above page,
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   
   $('#content').load("new.html");

});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Matplotlib - Quiver Plot

A quiver plot displays the velocity vectors as arrows with components (u,v) at the points (x,y).
quiver(x,y,u,v)
The above command plots vectors as arrows at the coordinates specified in each corresponding pair of elements in x and y.
The following table lists down the different parameters for the Quiver plot −
The following code draws a simple quiver plot −
import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25))
z = x*np.exp(-x**2 - y**2)
v, u = np.gradient(z, .2, .2)
fig, ax = plt.subplots()
q = ax.quiver(x,y,u,v)
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Pytest - Starting With Basic Test

Now, we will start with our first pytest program. We will first create a directory and thereby, create our test files in the directory.
Let us follow the steps shown below −
Create a new directory named automation and navigate into the directory in your command line.
Create a new directory named automation and navigate into the directory in your command line.
Create a file named test_square.py and add the below code to that file.
Create a file named test_square.py and add the below code to that file.
import math

def test_sqrt():
   num = 25
   assert math.sqrt(num) == 5

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

def tesequality():
   assert 10 == 11
Run the test using the following command −
pytest

The above command will generate the following output −
test_square.py .F
============================================== FAILURES 
==============================================
______________________________________________ testsquare 
_____________________________________________
   def testsquare():
   num=7
>  assert 7*7 == 40
E  assert (7 * 7) == 40
test_square.py:9: AssertionError
================================= 1 failed, 1 passed in 0.06 seconds 
=================================

See the first line of the result. It displays the file name and the results. F represents a test failure and dot(.) represents a test success.
Below that, we can see the details of the failed tests. It will show at which statement the test has failed. In our example, 7*7 is compared for equality against 40, which is wrong. In the end, we can see test execution summary, 1 failed and 1 passed.
The function tesequality is not executed because pytest will not consider it as a test since its name is not of the format test*.
Now, execute the below command and see the result again −
pytest -v

-v increases the verbosity.
test_square.py::test_sqrt PASSED
test_square.py::testsquare FAILED
============================================== FAILURES 
==============================================
_____________________________________________ testsquare 
_____________________________________________
   def testsquare():
   num = 7
>  assert 7*7 == 40
E  assert (7 * 7) == 40
test_square.py:9: AssertionError
================================= 1 failed, 1 passed in 0.04 seconds 
=================================

Now the result is more explanatory about the test that failed and the test that passed.
Note − pytest command will execute all the files of format test_* or *_test in the current directory and subdirectories.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
CodeIgniter - Adding JS & CSS

Adding JavaScript and CSS (Cascading Style Sheet) file in CodeIgniter is very simple. You have to create JS and CSS folder in root directory and copy all the .js files in JS folder and .css files in CSS folder as shown in the figure.
For example, let us assume, you have created one JavaScript file sample.js and one CSS file style.css. Now, to add these files into your views, load URL helper in your controller as shown below.
$this->load->helper('url');

After loading the URL helper in controller, simply add the below given lines in the view file, to load the sample.js and style.css file in the view as shown below.
<link rel = "stylesheet" type = "text/css" 
   href = "<?php echo base_url(); ?>css/style.css">

<script type = 'text/javascript' src = "<?php echo base_url(); 
   ?>js/sample.js"></script>
Create a controller called Test.php and save it in application/controller/Test.php
<?php 
   class Test extends CI_Controller {
	
      public function index() { 
         $this->load->helper('url'); 
         $this->load->view('test'); 
      } 
   } 
?>
Create a view file called test.php and save it at application/views/test.php
<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>CodeIgniter View Example</title> 
      <link rel = "stylesheet" type = "text/css" 
         href = "<?php echo base_url(); ?>css/style.css"> 
      <script type = 'text/javascript' src = "<?php echo base_url(); 
         ?>js/sample.js"></script> 
   </head>
	
   <body> 
      <a href = 'javascript:test()'>Click Here</a> to execute the javascript function. 
   </body>
	
</html>
Create a CSS file called style.css and save it at css/style.css
body { 
   background:#000; 
   color:#FFF; 
}
Create a JS file called sample.js and save it at js/sample.js
function test() { 
   alert('test'); 
}
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['profiler'] = "Profiler_controller"; 
$route['profiler/disable'] = "Profiler_controller/disable"
Use the following URL in the browser to execute the above example.
http://yoursite.com/index.php/test

 Print
 Add Notes
 Bookmark this page
Python | Get values of particular key in list of dictionaries

26 Jul, 2019
Sometimes, we may require a way in which we have to get all the values of specific key from a list of dictionary. This kind of problem has a lot of application in web development domain in which we sometimes have a json and require just to get single column from records. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionUsing list comprehension is quite straight forward method to perform this particular task. In this, we just iterate over the list of dictionary for desired value.
# Python3 code to demonstrate working of# Get values of particular key in list of dictionaries# Using list comprehension  # initializing listtest_list = [{'gfg' : 1, 'is' : 2, 'good' : 3},              {'gfg' : 2}, {'best' : 3, 'gfg' : 4}]  # printing original listprint("The original list is : " + str(test_list))  # Using list comprehension# Get values of particular key in list of dictionariesres = [ sub['gfg'] for sub in test_list ]  # printing result print("The values corresponding to key : " + str(res))
The original list is : [{‘is’: 2, ‘gfg’: 1, ‘good’: 3}, {‘gfg’: 2}, {‘best’: 3, ‘gfg’: 4}]The values corresponding to key : [1, 2, 4]
 
Method #2 : Using map() + itemgetter()This problem can also be solved using another technique using map() and itemgetter(). In this, map is used to link the value to all the dictionary keys and itemgetter gets the desired key.
# Python3 code to demonstrate working of# Get values of particular key in list of dictionaries# Using map() + itemgetter()from operator import itemgetter  # initializing listtest_list = [{'gfg' : 1, 'is' : 2, 'good' : 3},             {'gfg' : 2}, {'best' : 3, 'gfg' : 4}]  # printing original listprint("The original list is : " + str(test_list))  # Using map() + itemgetter()# Get values of particular key in list of dictionariesres = list(map(itemgetter('gfg'), test_list))  # printing result print("The values corresponding to key : " + str(res))
The original list is : [{‘is’: 2, ‘gfg’: 1, ‘good’: 3}, {‘gfg’: 2}, {‘best’: 3, ‘gfg’: 4}]The values corresponding to key : [1, 2, 4]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Constructors in Java- GeeksQuiz

07 Mar, 2018

1) Constructor name should be same as class name.
2) If you don't define a constructor for a class, 
    a default parameterless constructor is automatically
    created by the compiler. 
3) The default constructor calls super() and initializes all 
   instance variables to default value like 0, null.
4) If we want to parent class constructor, it must be called in 
   first line of constructor.
Copy constructor called
(10.0 + 15.0i)
Copy constructor called
(0.0 + 0.0i)
(10.0 + 15.0i)
(0.0 + 0.0i)
inside static block
a = 4
inside constructor
a = 11
inside static block
a = 4
inside constructor
a = 5

inside static block
a = 10
inside constructor
a = 11

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Download Image From URL in Android
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Spring Boot - Architecture
Swapping items of a list in Java : Collections.swap() with Example

11 Dec, 2018
java.util.Collections.swap() method is a java.util.Collections class method. It swaps elements at the specified positions in given list.
// Swaps elements at positions "i" and "j" in myList.
public static void swap(List mylist, int i, int j)

It throws IndexOutOfBoundsException if either i
or j is out of range.

// Java program to demonstrate working of Collections.swapimport java.util.*;  public class GFG{    public static void main(String[] args)    {        // Let us create a list with 4 items        ArrayList<String>  mylist =                        new ArrayList<String>();        mylist.add("code");        mylist.add("practice");        mylist.add("quiz");        mylist.add("geeksforgeeks");          System.out.println("Original List : \n" + mylist);          // Swap items at indexes 1 and 2        Collections.swap(mylist, 1, 2);          System.out.println("\nAfter swap(mylist, 1, 2) : \n"                           + mylist);          // Swap items at indexes 1 and 3        Collections.swap(mylist, 3, 1);          System.out.println("\nAfter swap(mylist, 3, 1) : \n"                           + mylist);    }}
Output:
Original List : Original List : 
[code, practice, quiz, geeksforgeeks]

After swap(mylist, 1, 2) : 
[code, quiz, practice, geeksforgeeks]

After swap(mylist, 3, 1) : 
[code, geeksforgeeks, practice, quiz]

This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks..
Java - util package
Java-ArrayList
Java-Collections
Java-Collections-Class
Java-Functions
java-list
Java-List-Programs
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
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
How to convert a data frame column to date that contains integer values in R?

If we have an integer column that actually contains date values, for example having 29th September 2020 as 20200929 then we can convert it to date by using transform function by reading the dates with as.Date function but as.character will also be needed so that as.Date function can read the date values.
 Live Demo
Consider the below data frame −
ID<−1:20
Dates<−c(20200101, 20200401, 20201015, 20200111, 20200222, 20200121, 20200701, 20201231, 20200417, 20200601, 20200811, 20200927, 20200512, 20200713, 20200225, 20200324, 20200203, 20200819, 20200916, 20200428)
df1<−data.frame(ID,Dates)
df1
   ID    Dates
1 1 20200101
2 2 20200401
3 3 20201015
4 4 20200111
5 5 20200222
6 6 20200121
7 7 20200701
8 8 20201231
9 9 20200417
10 10 20200601
11 11 20200811
12 12 20200927
13 13 20200512
14 14 20200713
15 15 20200225
16 16 20200324
17 17 20200203
18 18 20200819
19 19 20200916
20 20 20200428
Converting Dates to appropriate date format −
df1<−transform(df1,Dates=as.Date(as.character(Dates),"%Y%m%d"))
df1
   ID    Dates
1 1 2020−01−01
2 2 2020−04−01
3 3 2020−10−15
4 4 2020−01−11
5 5 2020−02−22
6 6 2020−01−21
7 7 2020−07−01
8 8 2020−12−31
9 9 2020−04−17
10 10 2020−06−01
11 11 2020−08−11
12 12 2020−09−27
13 13 2020−05−12
14 14 2020−07−13
15 15 2020−02−25
16 16 2020−03−24
17 17 2020−02−03
18 18 2020−08−19
19 19 2020−09−16
20 20 2020−04−28
 Live Demo
S.NO<−1:20
Date<−c(19980313, 19980604, 19980409, 19980104, 19980501, 19980101, 19980521, 19980412, 19980601, 19980711, 19980615, 19980810, 19980509, 19980221, 19981101, 19981121, 19981009, 19980915, 19980929, 19980813)
df2<−data.frame(S.NO,Date)
df2
   S.NO    Date
1 1 19980313
2 2 19980604
3 3 19980409
4 4 19980104
5 5 19980501
6 6 19980101
7 7 19980521
8 8 19980412
9 9 19980601
10 10 19980711
11 11 19980615
12 12 19980810
13 13 19980509
14 14 19980221
15 15 19981101
16 16 19981121
17 17 19981009
18 18 19980915
19 19 19980929
20 20 19980813
Converting Date to appropriate date format −
df2<−transform(df2,Date=as.Date(as.character(Date),"%Y%m%d"))
df2
   S.NO    Date
1 1 1998−03−13
2 2 1998−06−04
3 3 1998−04−09
4 4 1998−01−04
5 5 1998−05−01
6 6 1998−01−01
7 7 1998−05−21
8 8 1998−04−12
9 9 1998−06−01
10 10 1998−07−11
11 11 1998−06−15
12 12 1998−08−10
13 13 1998−05−09
14 14 1998−02−21
15 15 1998−11−01
16 16 1998−11−21
17 17 1998−10−09
18 18 1998−09−15
19 19 1998−09−29
20 20 1998−08−13
Determine Matplotlib axis size in pixels

To determine the axis size in pixels, we can take the following steps −
Create a figure and a set of subplots, using subplots() method, fig and ax.
Create a figure and a set of subplots, using subplots() method, fig and ax.
To get the DPI, use fig.dpi. Print the details.
To get the DPI, use fig.dpi. Print the details.
Find bounding box in the display box.
Find bounding box in the display box.
Find the width and height, using bbox.width and bbox.height.
Find the width and height, using bbox.width and bbox.height.
Print the width and height.
Print the width and height.
from matplotlib import pyplot as plt

fig, ax = plt.subplots()
print("Dot per inch(DPI) for the figure is: ", fig.dpi)
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
print("Axis sizes are(in pixels):", width, height)
Dot per inch(DPI) for the figure is: 100.0
Axis sizes are(in pixels): 4.96 3.696
How to avoid overlapping of labels & autopct in a Matplotlib pie chart?

To avoid overlapping of labels and autopct in a matplotlib pie chart, we can follow label as a legend, using legend() method.
Initialize a variable n=20 to get a number of sections in a pie chart.
Initialize a variable n=20 to get a number of sections in a pie chart.
Create slices and activities using numpy.
Create slices and activities using numpy.
Create random colors using hexadecimal alphabets, in the range of 20.
Create random colors using hexadecimal alphabets, in the range of 20.
Use pie() method to plot a pie chart with slices, colors, and slices data points as a label.
Use pie() method to plot a pie chart with slices, colors, and slices data points as a label.
Make a list of labels (those are overlapped using autopct).
Make a list of labels (those are overlapped using autopct).
Use legend() method to avoid overlapping of labels and autopct.
Use legend() method to avoid overlapping of labels and autopct.
To display the figure, use show() method.
To display the figure, use show() method.
import random
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 20
slices = np.arange(n)
activities = np.arange(n)
colors = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
for i in range(n)]

patches, texts = plt.pie(slices,
   colors=colors,
   startangle=90,
   labels=slices)

labels = ['{0} - {1:1.2f} %'.format(i, j) for i, j in zip(activities,
100.*slices/slices.sum())]
plt.legend(patches, labels, loc='center left', bbox_to_anchor=(-0.35, .5), fontsize=8)
plt.show()
Catching base and derived classes as exceptions - GeeksforGeeks

06 Jan, 2022
Exception Handling – catching base and derived classes as exceptions:If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class. If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception”  
C++
#include<iostream>using namespace std; class Base {};class Derived: public Base {};int main(){   Derived d;   // some other stuff   try {       // Some monitored code       throw d;   }   catch(Base b) {        cout<<"Caught Base Exception";   }   catch(Derived d) {  //This catch block is NEVER executed        cout<<"Caught Derived Exception";   }   getchar();   return 0;}
In the above C++ code, if we change the order of catch statements then both catch statements become reachable. Following is the modified program and it prints “Caught Derived Exception” 
C++
#include<iostream>using namespace std; class Base {};class Derived: public Base {};int main(){   Derived d;   // some other stuff   try {       // Some monitored code       throw d;   }   catch(Derived d) {        cout<<"Caught Derived Exception";   }   catch(Base b) {        cout<<"Caught Base Exception";   }   getchar();   return 0;}
In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code. For example, following Java code fails in compilation with error message “exception Derived has already been caught”  
Java
//filename Main.javaclass Base extends Exception {}class Derived extends Base  {}public class Main {  public static void main(String args[]) {    try {       throw new Derived();    }    catch(Base b) {}    catch(Derived d) {}  }}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
anikakapoor
venkateshkumar4
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vector in C++ STL
Socket Programming in C/C++
Initialize a vector in C++ (6 different ways)
Iterators in C++ STL
std::sort() in C++ STL
Virtual Function in C++
Templates in C++ with Examples
Bitwise Operators in C/C++
Friend class and function in C++
getline (string) in C++
numpy.partition() in Python - GeeksforGeeks

28 Dec, 2018
numpy.partition() function is used to create a partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.
Syntax : numpy.partition(arr, kth, axis=-1, kind=’introselect’, order=None)
Parameters :arr : [array_like] Input array.kth : [int or sequence of ints ] Element index to partition by.axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.kind : Selection algorithm. Default is ‘introselect’.order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc.
Return : [ndarray] Partitioned array of the same type and shape as arr.
Code #1 :
# Python program explaining# partition() function   import numpy as geek  # input arrayin_arr = geek.array([ 2, 0,  1, 5, 4, 9])print ("Input array : ", in_arr)   out_arr = geek.partition(in_arr, 3)print ("Output partitioned array : ", out_arr)
Input array :  [2 0 1 5 4 9]
Output partitioned array :  [0 1 2 4 5 9]

 Code #2 :
# Python program explaining# partition() function   import numpy as geek  # input arrayin_arr = geek.array([ 2, 0,  1, 5, 4, 9, 3])print ("Input array : ", in_arr)   out_arr = geek.partition(in_arr, (0, 3))print ("Output partitioned array : ", out_arr)
Input array :  [2 0 1 5 4 9 3]
Output partitioned array :  [0 1 2 3 4 9 5]

Python numpy-Sorting Searching
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 ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
p5.js | background() function - GeeksforGeeks

09 Apr, 2019
The background() function in p5.js is used to set the color used for the background of the p5.js canvas. The default background is transparent. The color accepted by this function can be of the RGB, HSB, or HSL color depending on the current colorMode.
Syntax:
background(c)
Parameters: This function accepts single parameter c which stores the p5.Color object, color components, or CSS color.
Below programs illustrate the background() function in p5.js:
Example 1: This example uses background() function to set the background color.
function setup() {          // Create Canvas of size 300*300    createCanvas(300, 300);}  function draw() {    background(220, 141, 155); //RGB Value}
Output:
Example 2: This example uses background() function to set the background color.
function setup() {          // Create Canvas of size 300*300    createCanvas(300, 300);}  function draw() {          // Set background color to green    background('green');}
Output:
Reference: https://p5js.org/reference/#/p5/background
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How can I disable typing in a ttk.Combobox tkinter?

The ttk.Combobox is used to create dropdown menus in the Entry Widgets. To create the options, we just simply pass the strings to the values object of combobox. We can disable the combobox by passing the state as “readonly”.
In the following example, we will create a combobox whose state is disabled.
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter window
win.geometry("750x250")
#Create an instance of StringVar
var= StringVar()
#Create an Label
Label(win, text="Select any Language", font= ('Helvetica 15 bold')).pack(pady=20)
#Create Object of Tkinter Combobox
combobox= ttk.Combobox(win, textvariable= var, values=["C++","Java","Python","Rust","Go","JavaScript"])
combobox.pack()
win.mainloop()
Running the above code will display a window containing a combobox menu. We can select any option in the dropdown list.
Now add state = "readonly" in the Combobox object, it will make the Combobox Entry Widget disabled.
HashMap entrySet() Method in Java - GeeksforGeeks

26 Nov, 2018
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them.
Syntax:
hash_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the hash map.
Below programs are used to illustrate the working of java.util.HashMap.entrySet() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the entrySet() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();          // Mapping string values to int keys        hash_map.put(10, "Geeks");        hash_map.put(15, "4");        hash_map.put(20, "Geeks");        hash_map.put(25, "Welcomes");        hash_map.put(30, "You");          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Using entrySet() to get the set view        System.out.println("The set is: " + hash_map.entrySet());    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The set is: [20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4]

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the entrySet() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Using entrySet() to get the set view        System.out.println("The set is: " + hash_map.entrySet());    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The set is: [4=15, Geeks=20, You=30, Welcomes=25]

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
Queue Interface In Java
Functional Interfaces in Java
MySQL Tryit Editor v1.0

SELECT ROUND(345.156, 0);
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to quickly swap two arrays of the same size in C++?

In this tutorial, we will be discussing a program to understand how to quickly swap two arrays of same size in C++.
For this we will be using a quick method called std::swap() for swapping the elements of the two given arrays.
 Live Demo
#include <iostream>
#include <utility>
using namespace std;
   int main (){
   int a[] = {1, 2, 3, 4};
   int b[] = {5, 6, 7, 8};
   int n = sizeof(a)/sizeof(a[0]);
   swap(a, b);
   cout << "a[] = ";
   for (int i=0; i<n; i++)
      cout << a[i] << ", ";
   cout << "\nb[] = ";
   for (int i=0; i<n; i++)
      cout << b[i] << ", ";
   return 0;
}
a[] = 5, 6, 7, 8,
b[] = 1, 2, 3, 4,
C++ Vector Library - begin() Function

The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector.
Following is the declaration for std::vector::begin() function form std::vector header.
iterator begin();
const_iterator begin() const;

iterator begin() noexcept;
const_iterator begin() const noexcept;

None
Returns a random access iterator pointing to the first element of the vector.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::begin() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   auto il = {1, 2, 3, 4, 5};
   vector<int> v(il);

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
Redis - Server Client Kill Command

Redis CLIENT KILL command closes a given client connection.
Simple string reply − OK if the connection exists and has been closed.
Following is the basic syntax of Redis CLIENT KILL command.
redis 127.0.0.1:6379> CLIENT KILL [ip:port] [ID client-id] 
[TYPE normal|slave|pubsub] [ADDR ip:port] [SKIPME yes/no]

With Redis 2.8.12 or greater, the command can be run with multiple options as shown below −
CLIENT KILL ADDR ip:port. This is exactly the same as the old three-arguments behavior.
CLIENT KILL ADDR ip:port. This is exactly the same as the old three-arguments behavior.
CLIENT KILL ID client-id. Allows to kill a client by its unique ID field, which was introduced in the CLIENT LIST command starting from Redis 2.8.12.
CLIENT KILL ID client-id. Allows to kill a client by its unique ID field, which was introduced in the CLIENT LIST command starting from Redis 2.8.12.
CLIENT KILL TYPE type, where type is one of normal, slave, pubsub. This closes the connections of all the clients in the specified class. Note: Clients blocked into the MONITOR command are considered to belong to the normal class.
CLIENT KILL TYPE type, where type is one of normal, slave, pubsub. This closes the connections of all the clients in the specified class. Note: Clients blocked into the MONITOR command are considered to belong to the normal class.
CLIENT KILL SKIPME yes/no. By default, this option is set to yes, that is, the client calling the command will not get killed. However, setting this option to no will have the effect of also killing the client calling the command.
CLIENT KILL SKIPME yes/no. By default, this option is set to yes, that is, the client calling the command will not get killed. However, setting this option to no will have the effect of also killing the client calling the command.

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to concatenate a std::string and an int in C++?

In this program we will see how to concatenate a string and integer type data in C++. To concatenate string and integer data, we have to convert integer to string at first. To convert it we are using stringstream. This provides some features. It takes number or string then make it string.
Input: String “str” and Number 10
Output: Concatenated string “str10”
Step 1: Take string and number
Step 2: Convert number to string
Step 3: Concatenate them
Step 4: End
 Live Demo
#include <iostream>
#include <sstream>
using namespace std;
string int_to_str(int x) {
   stringstream ss;
   ss << x;
   return ss.str();
}
int main() {
   string my_str = "This is a string: ";
   int x = 50;
   string concat_str;
   concat_str = my_str + int_to_str(x);
   cout << concat_str;
}
This is a string: 50
Python | Duplicate element indices in list

27 Aug, 2019
While working with Python list, sometimes, we require to check for duplicates and may also sometimes require to track their indices. This kind of application can occur in day-day programming. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + set()This task can be solved using the combination of above functions. In this, we just insert all the elements in set and then compare each element’s existence in actual list. If it’s the second occurrence or more, then index is added in result list.
# Python3 code to demonstrate working of# Duplicate element indices in list# Using set() + loop  # initializing listtest_list = [1, 4, 5, 5, 5, 9, 1]  # printing original listprint("The original list is : " + str(test_list))  # Duplicate element indices in list# Using set() + loopoc_set = set()res = []for idx, val in enumerate(test_list):    if val not in oc_set:        oc_set.add(val)             else:        res.append(idx)               # printing resultprint("The list of duplicate elements is :  " + str(res))
The original list is : [1, 4, 5, 5, 5, 9, 1]
The list of duplicate elements is :  [3, 4, 6]

 
Method #2 : Using list comprehension + list slicingThis method is one liner alternative to perform this task. In this we just check for the non repeating element using list slicing and keep adding index in case it’s repeated.
# Python3 code to demonstrate working of# Duplicate element indices in list# Using list comprehension + list slicing  # initializing listtest_list = [1, 4, 5, 5, 5, 9, 1]  # printing original listprint("The original list is : " + str(test_list))  # Duplicate element indices in list# Using list comprehension + list slicingres = [idx for idx, val in enumerate(test_list) if val in test_list[:idx]]          # printing resultprint("The list of duplicate elements is :  " + str(res))
The original list is : [1, 4, 5, 5, 5, 9, 1]
The list of duplicate elements is :  [3, 4, 6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib - Transforms

The matplotlib package is built on top of a transformation framework to easily move between coordinate systems. Four coordinate systems can be used. The systems are described in brief in the table given below −
The user land data coordinate system. controlled by the xlim and ylim
The coordinate system of the Axes. (0,0) is bottom left and (1,1) is top right of the axes.
The coordinate system of the Figure. (0,0) is bottom left and (1,1) is top right of the figure
This is the pixel coordinate system of the display. (0,0) is the bottom left and (width, height) is the top right of display in pixels.
Alternatively, the(matplotlib.transforms.IdentityTransform()) may be used instead of None.
Consider the following example −
axes.text(x,y,"my label") 

The text is placed at the theoretical position of a data point (x,y). Thus we would speak of "data coords".
Using other transformation objects, placement can be controlled. For example, if the above test is to be placed in the centre of axes coordinate system, execute the following line of code −
axes.text(0.5, 0.5, "middle of graph", transform=axes.transAxes)

These transformations can be used for any kind of Matplotlib objects. The default transformation for ax.text is ax.transData and the default transformation for fig.text is fig.transFigure.
The axes coordinate system is extremely useful when placing text in your axes. You might often want a text bubble in a fixed location; for example, on the upper left of the axes pane and have that location remain fixed when you pan or zoom.

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Comparing two strings in C++

Here we will see how to compare two strings in C++. The C++ has string class. It also has the compare() function in the standard library to compare strings. This function checks the string characters one by one, if some mismatches are there, it returns the non-zero values. Let us see the code to get better idea.
 Live Demo
#include<iostream>
using namespace std;
void compareStrings(string s1, string s2) {
   int compare = s1.compare(s2);
   if (compare != 0)
      cout << s1 << " is not equal to "<< s2 << endl;
   else if(compare == 0)
      cout << "Strings are equal";
   if (compare > 0)
      cout << s1 << " is greater than "<< s2 << " difference is: " << compare << endl;
   else if(compare < 0)
      cout << s2 << " is greater than "<< s1 << " difference is: " << compare << endl;
}
int main() {
   string s1("hello");
   string s2("helLo");
   compareStrings(s1, s2);
}
hello is not equal to helLo
hello is greater than helLo difference is: 1
C | Dynamic Memory Allocation | Question 1 - GeeksforGeeks

28 Jun, 2021
The most appropriate matching for the following pairs (GATE CS 2000)
X: m=malloc(5); m= NULL;        1: using dangling pointers
Y: free(n); n->value=5;         2: using uninitialized pointers
Z: char *p; *p = ’a’;           3. lost memory is:
(A) X—1 Y—3 Z-2(B) (X—2 Y—1 Z-3(C) X—3 Y—2 Z-1
(D) X—3 Y—1 Z-2Answer: (D)Explanation: X -> A pointer is assigned to NULL without freeing memory so a clear example of memory leakY -> Trying to retrieve value after freeing it so dangling pointer.Z -> Using uninitialized pointersQuiz of this Question
C-Dynamic Memory Allocation
Dynamic Memory Allocation
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | Loops & Control Structure | Question 8
Output of C programs | Set 64 (Pointers)
C | File Handling | Question 1