code-rag-bench/online-tutorials huggingface dataset:
jQuery | length property - GeeksforGeeks

28 Feb, 2019
The length property is used to count number of the elements of the jQuery object.
Syntax:
$(selector).length
where selector is the object whose length is to be calculated.
Return Values: It returns the length of the selector.
Below is the example to show the working of jQuery length property:
<!DOCTYPE html><html>  <head>    <script src=    "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <script>        $(document).ready(function() {            $("button").click(function() {                document.getElementById("Geeks").innerHTML =                                         "<br>" + $("p").length            });        });    </script></head>  <body>      <p style="color:green"> GeeksforGeeks</p>    <p style="color:green">Sudo</p>    <p style="color:green">Code</p>    <p style="color:green">Gate</p>      <button>Click on the button to get     the number of "p" elements</button>      <div id="Geeks"></div>  </body>  </html> 
Output:Before clicking on the button:
After clicking on the button:
jQuery-Propertie
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python calendar module | firstweekday() method

22 Oct, 2018
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
In Python, calendar.firstweekday() is a function provided in calendar module for simple text calendars.
firstweekday() method is used to get the current setting for the weekday to start each week.
Syntax: firstweekday()
Parameter: no parameter
Returns: None
Code #1:
# Python program to explain working of firstweekday() method  # importing calendar moduleimport calendar  # default firstweekdayprint("Default First weekday is - ", calendar.firstweekday())  # setting 2nd day as firstweekdaycalendar.setfirstweekday(2)  # print firstweekdayprint("First weekday after modification is - ", calendar.firstweekday())
Output:
Default First weekday is -  6
First weekday after modification is -  2
 Code #2: Explaining working of firstweekday() method with prmonth() method
# Python code to demonstrate the working of # firstweekday() with help of prmonth() method  # importing calendar module for calendar operations import calendar   # using prmonth() to print calendar of 1997 print ("The 4th month of 1997 is : ") calendar.prmonth(1997, 4, 2, 1)     # using setfirstweekday() to set first week day number calendar.setfirstweekday(4)   print("First weekday after modification is - ",                        calendar.firstweekday())
Output:
The 4th month of 1997 is : 
     April 1997
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
 First weekday after modification is -  4

Python Calander-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Using TreeMap to sort User-defined Objects in Java

11 Dec, 2018
Given example shows how to sort user defined objects TreeMap, you can sort the keys based on the logic provided inside the method.Given a record of employees name and salary as positive integer, it is required to sort the records on the basis of employee salary, using TreeMap in Java. If salary is same, then use employee name for comparison.
Examples:
Input : xbnnskd 100 geek 50
Output : geek 50 xbnnskd 100

Input : shyam 50 ram 50
Output : ram 50 shyam 50
Explanation : 
As both the employees have equal pay, 
sorting is done on the basis of employee's name.

Approach:
1. Traverse through the string 
   and map the employee's salary(S)
   with the list of employee names having salary S.
2. Use a TreeMap to have 
   keys(Employee's Salary) in a sorted manner.
3. Now, Traverse through the map 
   and print the sorted records.

Below is the implementation of above approach:
// Java program to print employees// records in a sorted manner  import java.io.*;import java.util.*;  public class GFG {      // Function to sort the records    static void sortRecords(String records)    {          // split the string        // on the basis of delimiter space(" ")        String[] rec = records.split(" ");          // Create a Treemap to store        // employee's salary with employee's name        Map<Integer, ArrayList<String> > map = new TreeMap<>();          // Traverse the records array        // and store values in map        for (int i = 1; i < rec.length; i += 2) {              // Converting String to integer            int sal = Integer.parseInt(rec[i]);              String name = rec[i - 1];              if (map.containsKey(sal)) {                  ArrayList<String> al = map.get(sal);                al.add(name);                  // Sorting list of employees having Salary sal                Collections.sort(al);                map.remove(sal);                map.put(sal, al);            }            else {                ArrayList<String> al = new ArrayList<>();                al.add(name);                map.put(sal, al);            }        }          // Traversing the map        // to print the sorted records        for (Map.Entry<Integer,                       ArrayList<String> >                 entry : map.entrySet()) {              ArrayList<String> al1 = entry.getValue();              for (int i = 0; i < al1.size(); i++)                System.out.print(al1.get(i) + " "                                 + entry.getKey() + " ");        }    }      // Driver code    public static void main(String args[])    {       String records = "Harsh 100 Neha 100 Neha 20 Samay 600 Karan 50";        // Calling function to sort the records        sortRecords(records);    }}
Neha 20 Karan 50 Harsh 100 Neha 100 Samay 600

Java-Map-Programs
java-TreeMap
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
linecache.getline() in Python

22 Apr, 2020
With the help of linecache.getline() method, we can get a particular line by providing a line number, one of the usecase for this method is to find the syntax error in the given line number within a big file by using linecache.getline() method.
Syntax : linecache.getline(filename, lineno)Return : Return the content of given line number.
Input File :
Example #1 :In this example we can see that by using linecache.getline() method, we are able to get the content of a given line from a big file by using this method.
# import linecacheimport linecache as lc  # Using linecache.getline() methodgfg = lc.getline('File.txt', 1)  print(gfg)
Output : Example #2 :
# import linecacheimport linecache as lc  # Using linecache.getline() methodgfg = lc.getline('File.txt', 2)  print(gfg)
Output :
Python-linecache
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | get_object_vars() Function

01 Oct, 2021
The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object. When an object is made, it has some properties. An associative array of properties of the mentioned object is returned by the function. But if there is no property of the object, then it returns NULL.
Syntax: 
get_object_vars( $object )
Parameters: This function accepts a single parameter as mentioned above and described below: $object: This parameter holds the object of an instance.Return Value: This method returns an associative array object accessible non-static properties for the specified object in scope.
Below programs illustrate the get_object_vars() function in PHP:
Program 1: 
PHP
<?php // Declare a classclass gfg {         // Properties of an object    // of this class    private $geeks = 0.02;    public $for = 1;    public $Geeks = "php";    private $GEEKS;    static $e;         public function example() {        var_dump(get_object_vars($this));    }} // Create an object of a class$example = new gfg; // Display properties of the// newly created objectvar_dump(get_object_vars($example));  $example->example();  ?>
array(2) {
  ["for"]=>
  int(1)
  ["Geeks"]=>
  string(3) "php"
}
array(4) {
  ["geeks"]=>
  float(0.02)
  ["for"]=>
  int(1)
  ["Geeks"]=>
  string(3) "php"
  ["GEEKS"]=>
  NULL
}
 
Program 2: 
PHP
<?php // Create a class   class coordinate {                // The properties of the        // object of this class        var $x;        var $y;        var $z;        var $labels;          function coordinate($x, $y, $z) {            $this->x = $x;            $this->y = $y;            $this->z = $z;        }          function to_set($labels) {            $this->labels = $labels;        }    }        $point1 = new coordinate(0.1, 0.2, 0.3);    print_r(get_object_vars($point1));      $point1->to_set("point 1");    print_r(get_object_vars($point1)); ?>
Array
(
    [x] => 0.1
    [y] => 0.2
    [z] => 0.3
    [labels] => 
)
Array
(
    [x] => 0.1
    [y] => 0.2
    [z] => 0.3
    [labels] => point 1
)
 
Reference: https://www.php.net/manual/en/function.get-object-vars.php 
simmytarika5
PHP-function
PHP-OOP
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
ArrayDeque size() Method in Java

10 Dec, 2018
The Java.util.ArrayDeque.size() method in Java is used to get the size of the Deque or the number of elements present in the Deque.
Syntax:
Array_Deque.size()
Parameters: The method does not take any parameter.
Return Value: The method returns the size or the number of elements present in the Deque.
Below programs illustrate the Java.util.ArrayDeque.size() method:Program 1: Adding String elements into the Deque.
// Java code to illustrate size()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<String> de_que = new ArrayDeque<String>();          // Use add() method to add elements into the Deque        de_que.add("Welcome");        de_que.add("To");        de_que.add("Geeks");        de_que.add("4");        de_que.add("Geeks");          // Displaying the ArrayDeque        System.out.println("ArrayDeque: " + de_que);          // Displaying the size of Deque        System.out.println("The size is: " + de_que.size());    }}
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The size is: 5

Program 2: Adding Integer elements into the Deque.
// Java code to illustrate clear()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<Integer> de_que = new ArrayDeque<Integer>();          // Use add() method to add elements into the Deque        de_que.add(10);        de_que.add(15);        de_que.add(30);          // Displaying the ArrayDeque        System.out.println("ArrayDeque: " + de_que);          // Displaying the size of Deque        System.out.println("The size is: " + de_que.size());    }}
ArrayDeque: [10, 15, 30]
The size is: 3

Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Pandas - Create Multiindex from dataframe

To create Multiindex from DataFrame, use the MultiIndex. from_frame() method. At first, let us create a Dictionary of lists −
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22'] }
Next, create a Pandas DataFrame from the above dictionary of lists −
dataFrame = pd.DataFrame(d)
Now create multiindex using from_frame() −
print(pd.MultiIndex.from_frame(dataFrame))
Following is the code −
import pandas as pd

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']}

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print("DataFrame...\n",dataFrame)

# creating multiple indexes
print(pd.MultiIndex.from_frame(dataFrame))
This will produce the following output −
DataFrame...
        Car   Date_of_purchase
0       BMW         2020-10-10
1     Lexus         2020-10-12
2      Audi         2020-10-17
3  Mercedes         2020-10-16
4    Jaguar         2020-10-19
5   Bentley         2020-10-22
MultiIndex ([(     'BMW','2020-10-10'),
             (   'Lexus','2020-10-12'),
             (    'Audi','2020-10-17'),
             ('Mercedes','2020-10-16'),
             (  'Jaguar','2020-10-19'),
             (  'Bentley '2020-10-22')],
          names=['Car,Date _of_purchase'])
Python program to find second maximum value in Dictionary

03 Feb, 2021
Dictionaries in Python is same as Associative arrays or Maps in other languages. Unlike lists, dictionaries stores data in key-value pair.Let’s see how to find the second maximum value in a Python dictionary.Method #1: Naive Approach: A general approach is to find the largest value of the dictionary and then iterate over the dictionary maintaining the value that must be greater than all the other values and less than the maximum value.
Python3
# Python naive approach to find the# second largest element in a dictionary # creating a new dictionarynew_dict ={"google":12, "amazon":9, "flipkart":4, "gfg":13} # maximum valuemax = max(new_dict.values()) # iterate through the dictionarymax2 = 0for v in new_dict.values():     if(v>max2 and v<max):            max2 = v # print the second largest valueprint(max2)
12
 
Method #2: Using sorted() method We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list. 
Python3
# Python code to find second largest# element from a dictionary using sorted() method # creating a new Dictionaryexample_dict = {"mark": 13, "steve": 3, "bill": 6, "linus": 11} # now directly print the second largest# value in the dictionaryprint("Output1:", sorted(example_dict.values())[-2]) # More than 1 keys with maximum value are presentexample_dict = {"fb": 20, "whatsapp": 12, "instagram": 20, "oculus": 10}print("Output2:", sorted(set(example_dict.values()), reverse=True)[-2])
11
 
Explanation: example_dict.values() gives list of all the values in the dictionary. sorted() method will sort the list of dict_values. list(sorted(example_dict.values()))[-2] converts dict_values to list and return the second last element of the sorted list, i.e. the second largest value of dictionary. if more than one maximum values are present in the dictionary as shown in the 2nd example, converting the dictionary values to a set will eliminate the duplicates. 
hanu`valluri
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
One Liner for Python if-elif-else Statements

11 Dec, 2020
If-elif-else statement is used in Python for decision-making i.e the program will evaluate test expression and will execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions.
Syntax :
if test expression:
    Body of if
    
elif test expression:
    Body of elif
    
else: 
    Body of else
The concept can be implemented using the short-hand method using ternary operation.
One Liner for Python if-elif-else Statements
Syntax:
{(condition1 :  <code1>) , (condition2 :  <code2>) }.get(True, <code3>)
This can be easily interpreted as if condition 1 is true run code 1 if condition 2 is true run code 2 and if both of them are false run the third code.
Example:
Python3
x = 87  result = {x > 190: "First condition satisfied!",           x == 87: "Second condition satisfied!"}.get(  True, "Third condition satisfied")  print(result)
Output:
Second condition satisfied!
Disclaimer: the below code won’t get you the desired results for this syntax of if-elif-else in Python:
Python3
x = 87  {x > 190: print("First condition satisfied!"), x == 87: print("Second condition satisfied!")}.get(  True, print("Third condition satisfied!"))
Output:
First condition satisfied!
Second condition satisfied!
Third condition satisfied!
python-basics
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Sort and Search an Element in Java

21 Oct, 2020
In Java sorting and searching an element in an array is very easy. Unlike C, where we have to make all the functions to work, Java has inbuilt functions to do the same work. To sort an array there is a sort function and to search an element in a sorted array there is a binarySearch() function. To learn more about these functions please follow the articles mentioned below:
Sorting: Arrays.sort() in Java with Examples
Time Complexity: O (n log n)
Syntax for Sorting:
Arrays.sort(array_name);

Searching: Arrays.binarySearch() in Java with Examples
For using Binary search array must be sorted previously
Important Points:
If the input array is not sorted, the results are undefined and negative.
If there are duplicates, there is no guarantee which one will be found.
Time Complexity: O (log n)
Syntax for Binary Searching:
Arrays.binarySearch(array_name, key);


We could always create user-defined functions but the inbuilt functions in Java are already using the least complexity algorithms so there is no need to make such functions.
Example 1: Finding an element in a sorted array.
Java
// Java program to find an // element in an sorted array  // Importing util filesimport java.util.*;  public class Gfg {      // Main function    public static void main(String args[]) throws Exception    {          // Sorted Array        int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };          // Using binarySearch to search for desired element        int index = Arrays.binarySearch(array, 2);          // Printing result        if (index >= 0)            System.out.println("Element 2 found at index: "                               + index);        else            System.out.println("Element not found");    }}
Output:
Element 2 found at index: 1


Example 2: Sorting an array and searching for an element in the sorted array.
Java
// Java program for Sorting an array and// searching for an element in the // sorted array  // Importing util filesimport java.util.*;  public class Gfg {      // Main function    public static void main(String args[]) throws Exception    {          // Unsorted Array        int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };          // Sorting the array        Arrays.sort(array);          // Printing sorted array        System.out.println("Sorted Array:");        for (int i = 0; i < array.length; i++) {            System.out.print(array[i] + " ");        }        System.out.println();          // Using binarySearch to search for desired element        int index = Arrays.binarySearch(array, 0);          // Printing result        if (index >= 0)            System.out.println("Element 2 found at index: "                               + index);        else            System.out.println("Element not found");    }}
Output:
Sorted Array:
1 2 3 4 5 6 7 8 9 10 
Element 2 found at index: 1


Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update matplotlib's imshow() window interactively?

To plot interactive matplotlib’s imshow window, we can take the following steps −
Using the subplots() method, create a figure and a set of subplots.
Using the subplots() method, create a figure and a set of subplots.
Create an array to plot an image, using numpy.
Create an array to plot an image, using numpy.
Display the image using the imshow() method.
Display the image using the imshow() method.
To make a slider axis, create an axes and a slider, with facecolor=yellow.
To make a slider axis, create an axes and a slider, with facecolor=yellow.
To update the image, while changing the slider, we can write a user-defined method, i.e., update(). Using the draw_idle() method, request a widget redraw once the control returns to the GUI event loop.
To update the image, while changing the slider, we can write a user-defined method, i.e., update(). Using the draw_idle() method, request a widget redraw once the control returns to the GUI event loop.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
image = np.random.rand(3, 3)
img = ax.imshow(image)
axcolor = 'yellow'
ax_slider = plt.axes([0.20, 0.01, 0.65, 0.03], facecolor=axcolor)
slider = Slider(ax_slider, 'Slide->', 0.1, 30.0, valinit=2)
def update(val):
   ax.imshow(np.random.rand(3, 3))
   fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()
PHP | FPDF-PDF Generator

02 Aug, 2018
FPDF is a PHP class which allows generating PDF files with PHP code. It is free to use and it does not require any API keys. FPDF stands for Free PDF. It means that any kind of modification can be done in PDF files.The main features of this class are:
Allows to setup page format and margins.
Allows to setup page header and footer.
It provides automatic page break and line break.
It supports images in various formats (JPEG, PNG and GIF).
It allows to setup Colors and Links.
It also support encoding.
Along with Page compression feature it provides many other functions.
Note: Download the latest version of this Class from http://www.fpdf.org/en/download.php
Program 1:
<?php  require('fpdf.php');  // New object created and constructor invoked$pdf = new FPDF();  // Add new pages. By default no pages available.$pdf->AddPage();  // Set font format and font-size$pdf->SetFont('Times', 'B', 20);  // Framed rectangular area$pdf->Cell(176, 5, 'Welcome to GeeksforGeeks!', 0, 0, 'C');  // Set it new line$pdf->Ln();  // Set font format and font-size$pdf->SetFont('Times', 'B', 12);  // Framed rectangular area$pdf->Cell(176, 10, 'A Computer Science Portal for geek!', 0, 0, 'C');  // Close document and sent to the browser$pdf->Output();  ?>
Output:
Program 2: Setup Header and Footer along with line break
<?phprequire('fpdf.php');   class PDF extends FPDF{    // Page header    function Header()    {        // GFG logo image        $this->Image('geeks.png', 30, 8, 20);                  // GFG logo image        $this->Image('geeks.png', 160, 8, 20);                  // Set font-family and font-size        $this->SetFont('Times','B',20);                  // Move to the right        $this->Cell(80);                  // Set the title of pages.        $this->Cell(30, 20, 'Welcome to GeeksforGeeks', 0, 2, 'C');                  // Break line with given space        $this->Ln(5);    }           // Page footer    function Footer()    {        // Position at 1.5 cm from bottom        $this->SetY(-15);                  // Set font-family and font-size of footer.        $this->SetFont('Arial', 'I', 8);                  // set page number        $this->Cell(0, 10, 'Page ' . $this->PageNo() .              '/{nb}', 0, 0, 'C');    }}   // Create new object.$pdf = new PDF();$pdf->AliasNbPages();  // Add new pages$pdf->AddPage();  // Set font-family and font-size.$pdf->SetFont('Times','',12);  // Loop to display line number contentfor($i = 0; $i < 50; $i++)    $pdf->Cell(30, 10, 'Line Number ' . $i, 0, 2, 'L');      $pdf->Output();  ?>
Output:Reference: http://www.fpdf.org/
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Multiply two list

27 Dec, 2019
There can be many situations in which one requires to find index wise product of two different lists. This can have a possible applications in day-day programming. Lets discuss various ways in which this task can be performed.
Method #1 : Naive MethodIn this method, we simply run a loop and append to the new list the product of the both list elements at similar index till we reach end of the smaller list. This is the basic method to achieve this task.
# Python code to demonstrate # Multiplying two lists# naive method   # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10]  # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2))  # using naive method to # Multiplying two listsres_list = []for i in range(0, len(test_list1)):    res_list.append(test_list1[i] * test_list2[i])  # printing resultant list print ("Resultant list is : " + str(res_list))
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [4, 15, 24, 12, 80]

 
Method #2 : Using List ComprehensionThe shorthand for the above explained technique, list comprehensions are usually quicker to type and hence must be preferred to perform these kind of programming tasks.
# Python code to demonstrate # Multiplying two lists# list comprehension  # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10]  # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2))  # using list comprehension to # Multiplying two listsres_list = [test_list1[i] * test_list2[i] for i in range(len(test_list1))]  # printing resultant list print ("Resultant list is : " + str(res_list))
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [4, 15, 24, 12, 80]

Python list-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
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python VLC MediaListPlayer – Pause/Resume

29 Aug, 2020
In this article we will see how we can pause/resume the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a series, instead of taking single media it accepts media list. Its working is almost similar like the MediaPlayer object but it is capable of playing list of media. We can pause and resume the media list player any time, when it get paused the frame and the audio get stopped and when it get resumed it start from the paused point.
In order to do this we will use set_pause method with the MediaListPlayer object
Syntax : media_list_player.set_pause(1)
Argument : It takes 0 to play/resume and non-zero to pause
Return : It returns None
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating a media player objectmedia_player = vlc.MediaListPlayer()  # creating Instance class objectplayer = vlc.Instance()  # creating a new media list objectmedia_list = player.media_list_new()  # creating a new mediamedia = player.media_new("death_note.mkv")  # adding media to media listmedia_list.add_media(media)  # setting media list to the media playermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)  # pausing mediamedia_player.set_pause(1)  # wait for 4 second# so that it remained paused for 4 secondstime.sleep(4)
Output :
Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating a media player objectmedia_player = vlc.MediaListPlayer()  # creating Instance class objectplayer = vlc.Instance()  # creating a new media listmedia_list = player.media_list_new()  # creating a new mediamedia = player.media_new("1.mp4")  # adding media to media listmedia_list.add_media(media)  # setting media list to the media playermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)  # pausing mediamedia_player.set_pause(1)  # wait for 4 second# so that it remained paused for 4 secondstime.sleep(4)
Output :
Python vlc-mediaPlayer
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | Get unique values from a list
Create a directory in Python
How to convert NumPy array to list ?

16 Mar, 2021
In this article, we will discuss how to convert NumPy arrays to a list. We can convert the Numpy array to the list by tolist() method, we can have a list of data element which is converted from an array using this method.
Syntax: ndarray.tolist()
Parameters: none
Returns: The possibly nested list of array elements.
Import required module.
Create array.
Display array and class type.
Use tolist() method to convert the array.
Display list and class type.
Example 1: One Dimensional Array
Python
# import moduleimport numpy as np  # create arrayprint("\nArray:")arr = np.array([1, 2, 4, 5])  print(arr)print(type(arr))  # apply methodlis = arr.tolist()  # display listprint("\nList:")print(lis)print(type(lis))
Output:
Example 2: Multidimensional Array
Python3
# import moduleimport numpy as np  # create arrayprint("\nArray:")arr = np.array([[1, 2, 3],                 [4, 5, 6],                 [7, 8, 9]])print(arr)print(type(arr))  # apply methodlis = arr.tolist()  # display listprint("\nList:")print(lis)print(type(lis))
Output:
Picked
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
response.close() – Python requests

24 Jan, 2022
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.close() out of a response object. response.close() closes the connection to the server 
To illustrate the use of response.close(), let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Prerequisites:
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
Example code:
Python3
# import requests moduleimport requests # Making a put requestresponse = requests.get('https://api.github.com') # print responseprint(response) # closing the connectionresponse.close() # Check if this gets executedprint("Connection Closed")
Example Implementation:
Save the above file as request.py and run using  
Python request.py
Output:
Check that Connection closed at the start of the output, which means the response.close() has been successfully executed.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests are one of the best with cool features. If any attribute of requests shows NULL, check the status code using the below attribute.  
response.status_code
If status_code doesn’t lie in the range of 200-29. You probably need to check the method to begin used for making a request + the URL you are requesting for resources. 
supreetbose
varshagumber28
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change line width in ggplot2?

03 Mar, 2021
ggplot2 is a data visualization package for the statistical programming language R. This article discusses how can we change line width in ggplot2. For this, only the size parameter in the geom_line() function has to be initialized to the required value.
Syntax:
geom_line(mapping=NULL, data=NULL, stat=”identity”, position=”identity”,...)
Approach
Import module
Create data frame
Create plot with a line
Display plot
Let us first draw a regular plot so that the difference is better understandable and apparent.
Example:
R
library(ggplot2)  data <- data.frame(  name=c("A","B","C","D","E"),    value=c(3,12,5,18,45))  # For Create a simple line graphggplot(data, aes(x=name, y=value, group=1)) +   geom_line()
Output:
Simple line graph using ggplot2
Setting the required value to the size parameter of geom_line() will produce a line plot of the required width.
Example: 
R
library(ggplot2)  data <- data.frame(  name=c("A","B","C","D","E"),    value=c(3,12,5,18,45))  # For create line graph with change of size and color.ggplot(data, aes(x=name, y=value, group=1)) +   geom_line(size=3, color="green")
Output: 
Modified Line Graph using ggplot2 
     
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python PIL | ImageDraw.Draw.polygon() Method

27 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.polygon()Draws a polygon.The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.
Syntax: PIL.ImageDraw.Draw.polygon(xy, fill=None, outline=None)
Parameters:
Parameters:
xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].
outline – Color to use for the outline.
fill – Color to use for the fill.
Returns: An Image object.
     import mathfrom PIL import Image, ImageDrawfrom PIL import ImagePath   side = 8xy = [    ((math.cos(th) + 1) * 90,     (math.sin(th) + 1) * 60)    for th in [i * (2 * math.pi) / side for i in range(side)]    ]    image = ImagePath.Path(xy).getbbox()  size = list(map(int, map(math.ceil, image[2:])))  img = Image.new("RGB", size, "# f9f9f9") img1 = ImageDraw.Draw(img)  img1.polygon(xy, fill ="# eeeeff", outline ="blue")   img.show()
Output:
Another Example:taking different parameters.
     import mathfrom PIL import Image, ImageDrawfrom PIL import ImagePath   side = 6xy = [    ((math.cos(th) + 1) * 90,     (math.sin(th) + 1) * 60)    for th in [i * (2 * math.pi) / side for i in range(side)]    ]    image = ImagePath.Path(xy).getbbox()  size = list(map(int, map(math.ceil, image[2:])))  img = Image.new("RGB", size, "# f9f9f9") img1 = ImageDraw.Draw(img)  img1.polygon(xy, fill ="# eeeeff", outline ="blue")   img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Ext.js - Multiline User Input Box

This is also like the prompt box but it allows THE user to enter multiline information instead of just one line.
Following is a simple syntax.
Ext.MessageBox.show ({
   title: 'Details',
   msg: 'Please enter your details:',
   width:300,
   buttons: Ext.MessageBox.OKCANCEL,
   multiline: true,    // this property is for multiline user input.
   fn: callbackFunction
});

Following is a simple example showing the usage.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.Button', {
               renderTo: Ext.getElementById('msgBox'),
               text: 'Click Me',
               
               listeners: {
                  click: function() {
                     Ext.MessageBox.show ({
                        title: 'Details',
                        msg: 'Please enter your details:',
                        width:300,
                        buttons: Ext.MessageBox.OKCANCEL,
                        multiline: true,
                        fn: callbackFunction
                     });
                     function callbackFunction() {
                        Ext.Msg.alert('status', 'Details entered succesfully');
                     }
                  }
               }
            });
         });
      </script>
   </head>
   
   <body>
      <p> Click the button for alert box </p>
      <div id = "msgBox" ></div>
   </body>
</html>
The above program will produce the following result −
 Click the button for alert box 
 Print
 Add Notes
 Bookmark this page
XERXES – Penetration Testing Tool using Kali Linux - GeeksforGeeks

25 Mar, 2022
XERXES is a free and Open source tool available on GitHub. You can install and download the tool free of cost. A denial of service attack can be performed by using this tool. Xerxes is written in C. The framework works by maintaining a full TCP connection. After making full TCP Connection it only requires a few hundreds of requests at long term in regular intervals. As a result, Xerxes doesn’t need to spend lots of traffic requests to exhaust all the available connections on a server. Using xerxes any remote machine can be taken down or any server can be taken down easily. The tool use perfectly legitimate HTTP traffic. The tool is very useful for security testing.
Step 1: Open your kali linux operating system and use the following command to install the tool from github.
git clone https://github.com/ngrok90/xerxes.git
Step 2: Now use the following command to move into the directory of the tool.
cd xerxes
Step 3: Now you are the directory of the tool. Use the following command to start ddos attack.
./xerxes <domain> 80
The tool is running successfully and attacking on the domain,
brzoskij
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
Docker - COPY Instruction
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Array Basics in Shell Scripting | Set 1
How to find size of an object in Python?

06 Jun, 2022
In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.
Note: Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
Examples:  
Input: 
# Any Integer Value
sys.getsizeof(4) 

Expected Output: 4 bytes (Size of integer is 4bytes)
Actual Output: 28 bytes
Here’s how we can interpret the actual output. Have a look at the table below: 
Example:
Python3
import sys # Getting size using getsizeof() method and lately# printing the same.a = sys.getsizeof(12)print(a) b = sys.getsizeof('geeks')print(b) c = sys.getsizeof(('g', 'e', 'e', 'k', 's'))print(c) d = sys.getsizeof(['g', 'e', 'e', 'k', 's'])print(d) e = sys.getsizeof({1, 2, 3, 4})print(e) f = sys.getsizeof({1: 'a', 2: 'b', 3: 'c', 4: 'd'})print(f)
Output:
 
bhagyeshdudhediya
solankimayank
python-basics
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
response.status_code – Python requests

01 Mar, 2020
response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.status_code out of a response object. To know more about Status codes for HTTP, visit – HTTP status codes | Successful Responses and HTTP status codes | Informational Responses.
To illustrate use of response.status_code, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
# import requests moduleimport requests  # Making a get requestresponse = requests.get('https://api.github.com/')  # print responseprint(response)  # print request status_codeprint(response.status_code)
Save above file as request.py and run using
Python request.py

Check that and 200 in the output which refer to HttpResponse and Status code respectively.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tellp() in file handling with c++ with example

12 Jul, 2021
The tellp() function is used with output streams, and returns the current “put” position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.Syntax:  
pos_type tellp();
Return – Current output position indicator on success otherwise  return -1.Example 1 –  
CPP
// cpp code to get the position at particular// position using tellp() function#include <iostream>#include <fstream>using namespace std; int main(){    fstream file;     // open file in read and write mode    file.open("myfile.txt", ios::out);    file << "geeksforgeeks";     // print the position of the pointer in file    cout << "the current position of pointer is :"         << file.tellp() << endl;     // close the open file    file.close();}
Output –  
the current position of pointer is :-1
In the above code the tellp() returns the current position to which it point in a file.Example 2 –  
CPP
// code to add content at particular position// using tellp()#include <fstream>using namespace std; int main(){    long position;    fstream file;     // open the file in read and write mode    file.open("myfile.txt");     // write content in the file    file.write("this is an apple", 16);    position = file.tellp();     // set position of pointer using seekp    file.seekp(position - 7);    file.write(" sam", 4);    file.close();}
Output –  
this is a sample
Here tellp() function returns the position of pointer then using seekp() function the pointer is shift back from n position here it shift 7 position back and then insert the content at that position .This article is contributed by Shivani Baghel . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Vaibhav Bajpai
sagartomar9927
cpp-file-handling
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
The C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types