code-rag-bench/online-tutorials huggingface dataset:
How can to get list of values from dictionary in Python? - GeeksforGeeks

01 Dec, 2021
In this article, we will discuss how to get a list of values from a dictionary using Python.
We can use dictionary.values() along with list() function to get the list. Here, values() method is an dictionary method used to access the values from key:value pairs and we are then converting the values to list by using list() function
Syntax:
list(dictionary.values())
Example: Python program to create a dictionary with student names as key and values as subjects
Python3
# create a dictionary# with student names as key# values as subjectsdata = {'manoja': 'java', 'tripura': 'python',        'manoj': 'statistics', 'manoji': 'cpp'} # get list of valueslist(data.values())
Output:
['java', 'python', 'statistics', 'cpp']
We can use [] along with * to get all list of dictionary values. Here values() is a dictionary method is used to get the values from key:value pair in the dictionary and * is used to get only values instead of getting dict_values and then we are getting into a list by using list() function
Syntax:
[*dictionary.values()]
Example:
Python3
# create a dictionary# with student names as key# values as subjectsdata = {'manoja': 'java', 'tripura': 'python',        'manoj': 'statistics', 'manoji': 'cpp'} # get list of values[*data.values()]
Output:
Using List comprehension we can get the list of dictionary values. Here we are using an list comprehension to iterate in a dictionary by using iterator. This will return each value from the key:value pair.
Syntax:
[dictionary[i] for i in dictionary]
Example:
Python3
# create a dictionary# with student names as key# values as subjectsdata = {'manoja': 'java', 'tripura': 'python',        'manoj': 'statistics', 'manoji': 'cpp'} # get list of values using comprehension[data[i] for i in data]
Output:
['java', 'python', 'statistics', 'cpp']
kapoorsagar226
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.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
GATE | GATE CS 2012 | Question 23 - GeeksforGeeks

06 Oct, 2021
Given the language L = {ab, aa, baa}, which of the following strings are in L*?
1) abaabaaabaa
2) aaaabaaaa
3) baaaaabaaaab
4) baaaaabaa 
(A) 1, 2 and 3(B) 2, 3 and 4(C) 1, 2 and 4(D) 1, 3 and 4Answer: (C)Explanation: See question 2 of https://www.geeksforgeeks.org/automata-theory-set-2/
YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGATE PYQ's on Regular Languages with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0043:22 / 59:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=13C2qpmD9f8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
Theory of Computation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
Show all columns of Pandas DataFrame in Jupyter Notebook
Hash Functions and list/types of Hash functions
How to Create and Setup Spring Boot Project in Eclipse IDE?
Enumeration nextElement() Method in Java with Examples - GeeksforGeeks

27 Jun, 2019
An object that implements the Enumeration interface generates a series of elements, one at a time. The nextElement() method of Enumeration used to return the next element of this enumeration if this enumeration object has at least one more element to provide.This method is used to get elements from the enumuration.
Syntax:
E nextElement()

Parameters: This method accepts nothing.
Return value: This method returns true the next element of this enumeration.
Exception: This method throws NoSuchElementException if no more elements exist.
Below programs illustrate nextElement() method:Program 1:
// Java program to demonstrate// Enumeration.nextElement() method  import java.util.*;  public class GFG {      @SuppressWarnings({ "unchecked", "rawtypes" })    public static void main(String[] args)    {          // create a Enumeration and vector object        Enumeration<Integer> company;        Vector<Integer> employees = new Vector<Integer>();          // add values to employees        employees.add(1001);        employees.add(2001);        employees.add(3001);        employees.add(4001);        company = employees.elements();          while (company.hasMoreElements()) {            // get elements using nextElement()            System.out.println("Emp ID = "                               + company.nextElement());        }    }}
Emp ID = 1001
Emp ID = 2001
Emp ID = 3001
Emp ID = 4001

Program 2:
// Java program to demonstrate// Enumeration.nextElement() method  import java.util.*;  public class GFG {      @SuppressWarnings({ "unchecked", "rawtypes" })    public static void main(String[] args)    {          // create a Enumeration and vector object        Enumeration<String> Users;        Vector<String> user = new Vector<String>();          // add Users        user.add("Aman Singh");        user.add("Raunak Singh");        user.add("Siddhant Gupta");        Users = user.elements();          while (Users.hasMoreElements()) {            // get elements using nextElement()            System.out.println(Users.nextElement());        }    }}
Aman Singh
Raunak Singh
Siddhant Gupta

References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#nextElement()
Java - util package
Java-Enumeration
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
How to automatically redirect a Web Page to another URL?

Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after.
Set the content attribute to 0, if you want the page to load the new URL immediately.
The following is an example of redirecting current page to another website after 3 seconds.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Meta Tag</title>
      <meta http-equiv = "refresh" content = "3; url = https://www.qries.com" />
   </head>
   <body>
      <p>Redirecting to another URL</p>
   </body>
</html>
SQL - LIKE Clause

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator.
The percent sign (%)
The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations.
The basic syntax of % and _ is as follows −
SELECT FROM table_name
WHERE column LIKE 'XXXX%'

or 

SELECT FROM table_name
WHERE column LIKE '%XXXX%'

or

SELECT FROM table_name
WHERE column LIKE 'XXXX_'

or

SELECT FROM table_name
WHERE column LIKE '_XXXX'

or

SELECT FROM table_name
WHERE column LIKE '_XXXX_'

You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.
The following table has a few examples showing the WHERE part having different LIKE clause with '%' and '_' operators −
WHERE SALARY LIKE '200%'
Finds any values that start with 200.
WHERE SALARY LIKE '%200%'
Finds any values that have 200 in any position.
WHERE SALARY LIKE '_00%'
Finds any values that have 00 in the second and third positions.
WHERE SALARY LIKE '2_%_%'
Finds any values that start with 2 and are at least 3 characters in length.
WHERE SALARY LIKE '%2'
Finds any values that end with 2.
WHERE SALARY LIKE '_2%3'
Finds any values that have a 2 in the second position and end with a 3.
WHERE SALARY LIKE '2___3'
Finds any values in a five-digit number that start with 2 and end with 3.
Let us take a real example, consider the CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would display all the records from the CUSTOMERS table, where the SALARY starts with 200.
SQL> SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
+----+----------+-----+-----------+----------+


    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Find common elements in three sorted arrays in C++

Suppose we have three arrays with some elements. We have to find all the common elements that are present in these three arrays. Suppose these elements are [10, 12, 15, 20, 25], [10, 12, 13, 15] and [10, 12, 15, 24, 25, 26], then the common elements in these three arrays are 10, 12 and 15.
Suppose current element traversed in array A1 be x, A2 be y and A3 be z. We can have the following cases for them −
If x, y, and z are same, then we will print any of them, and increase each array elements by 1
If x, y, and z are same, then we will print any of them, and increase each array elements by 1
When x < y, then we will move ahead in A1 as x cannot be a common element
When x < y, then we will move ahead in A1 as x cannot be a common element
When x > z and y > z, then we will move ahead for A3, as z cannot be a common element.
When x > z and y > z, then we will move ahead for A3, as z cannot be a common element.
 Live Demo
#include<iostream>
using namespace std;
void findCommonValues(int A1[], int A2[], int A3[], int n1, int n2, int n3) {
   int i = 0, j = 0, k = 0;
   while (i < n1 && j < n2 && k < n3) {
      if (A1[i] == A2[j] && A2[j] == A3[k]) {
         cout << A1[i] << " "; i++; j++; k++;
      }
      else if (A1[i] < A2[j])
         i++;
      else if (A2[j] < A3[k])
         j++;
      else
         k++;
   }
}
int main() {
   int A1[] = {10, 12, 15, 20, 25};
   int n1 = sizeof(A1)/sizeof(A1[0]);
   int A2[] = {10, 12, 13, 15};
   int n2 = sizeof(A2)/sizeof(A2[0]);
   int A3[] = {10, 12, 15, 24, 25, 26};
   int n3 = sizeof(A3)/sizeof(A3[0]);
   cout << "Common elements are: ";
   findCommonValues(A1, A2, A3, n1, n2, n3);
}
Common elements are: 10 12 15
Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1<=a<=b<=c<= n in C++

We are given an integer n. The goal is to find triplets ( set of 3 numbers ) that satisfy the conditions −
a2+b2=c2
a2+b2=c2
1<=a<=b<=c<=n
1<=a<=b<=c<=n
We will do this by running two loops for values of 1<=a<=n and 1<=b<=n. Calculate c accordingly (c=sqrt(a2+b2 )) and increment count if both conditions 1 and 2 are met.
Let’s understand with examples.
Input − N=5
Output − Number of triplets − 1
Explanation −
for a=3, b=4 and c=5 both conditions are met.
Input − N=3
Output − Number of triplets − 0
Explanation −
No such triplets that meet conditions 1 and 2.
Integer N stores the last limit of the range [1,N].
Integer N stores the last limit of the range [1,N].
Function countTriplets(int n) takes n and returns the count of triplets which satisfy the conditions a2+b2=c2 and 1<=a<=b<=c<=n
Function countTriplets(int n) takes n and returns the count of triplets which satisfy the conditions a2+b2=c2 and 1<=a<=b<=c<=n
Variable count stores the number of such triplets, initially 0.
Variable count stores the number of such triplets, initially 0.
Variable sum stores the sum of squares of a and b.
Variable sum stores the sum of squares of a and b.
Starting from a=1 to n and b=a to n, calculate sum=a*a+b*b and c as square root of sum (sqrt(sum)).
Starting from a=1 to n and b=a to n, calculate sum=a*a+b*b and c as square root of sum (sqrt(sum)).
If calculated c has value such that c*c==sum and b<=c && c<=n ( both condition 1 and 2 are met ).
If calculated c has value such that c*c==sum and b<=c && c<=n ( both condition 1 and 2 are met ).
Increment count as current a,b,c satisfy both conditions.
Increment count as current a,b,c satisfy both conditions.
Perform this until a=n and b=n. In the end, count will have a number of such triplets that satisfy the conditions.
Perform this until a=n and b=n. In the end, count will have a number of such triplets that satisfy the conditions.
Return the count as desired result.
Return the count as desired result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int countTriplets(int n){
   int count = 0;
   int a,b,c;
   a=b=c=1;
   int sum=0;
   for (a = 1; a <= n; a++) //1<=a<=n{
      for (b = a; b <= n; b++) //1<=a<=b<=n{
         sum = a*a + b*b; //a^2 + b^2 =c^2
         c = sqrt(sum);
         if (c * c == sum && b<=c && c<=n) //check 1<=a<=b<=c<=n{
            count++;
            cout<<endl<<"a :"<<a<<" b :"<<b<<" c :"<<c; //to print triplets
         }
      }
   }
   return count;
}
int main(){
   int N = 15;
   cout <<endl<< "Number of triplets : "<<countTriplets(N);
   return 0;
}
If we run the above code it will generate the following output −
Number of triplets :
a :3 b :4 c :5
a :5 b :12 c :13
a :6 b :8 c :10
a :9 b :12 c :154
Number of triplets : 4
GATE | GATE-CS-2015 (Set 2) | Question 61 - GeeksforGeeks

01 Oct, 2021
Which of the following languages is/are regular?
L1: {wxwR ⎪ w, x ∈ {a, b}* and ⎪w⎪, ⎪x⎪ >0} wR is the reverse of string w
L2: {anbm ⎪m ≠ n and m, n≥0
L3: {apbqcr ⎪ p, q, r ≥ 0}  
(A) L1 and L3 only(B) L2 only(C) L2 and L3 only(D) L3 onlyAnswer: (A)Explanation:
L3 is simple to guess, it is regular.
Below is DFA for L1.



L1 is interesting. The important thing to note 
about L1 is length of x is greater than 0, i.e.,
|x| > 0.
So any string than starts and ends with same character
is acceptable by language and remaining string becomes w.
Below is DFA for L1.


YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs on Regular Language (Continued) with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:46 / 46:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SyuPwlgjTuQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Java Examples - Fill colors using Applet?

How to fill colors in shapes using Applet?
Following example demonstrates how to create an applet which will have fill color in a rectangle using setColor(), fillRect() methods of Graphics class to fill color in a Rectangle.
import java.applet.*;
import java.awt.*;

public class fillColor extends Applet {
   public void paint(Graphics g) {
      g.drawRect(300,150,200,100);
      g.setColor(Color.yellow);   
      g.fillRect( 300,150, 200, 100 );
      g.setColor(Color.magenta);
      g.drawString("Rectangle",500,150);
   }
}
The above code sample will produce the following result in a java enabled web browser.
A Rectangle with yellow color filled in it will be drawn in the browser.

 Print
 Add Notes
 Bookmark this page
C++ Program to Search for an Element in a Binary Search Tree

In this program we need to. Implement binary search to find the existence of a search sequence in a binary search tree. The worst case time complexity of Binary search is O(n) but for the average case O(log(n)).
Begin
   Construct binary search tree for the given unsorted data array by inserting data into tree one by one.
   Take the input of data to be searched in the BST.
   Now starting from the root node, compare the data with data part of the node.
   if data < temp->d, move the temp pointer to the left child.
   if data > temp->d move the temp pointer to the right child.
   if data = temp->d print the tree depth where it is found and return to main.
   Else print item not found.
End
#include<iostream>
using namespace std;
struct node {
   int d;
   node *left;
   node *right;
};
node* CreateNode(int d) {
   node *newnode = new node;
   newnode->d = d;
   newnode->left = NULL;
   newnode->right = NULL;
   return newnode;
}
node* InsertIntoTree(node* root, int d) {
   node *temp = CreateNode(d);
   node *t = new node;
   t = root;
   if(root == NULL)
      root = temp;
   else {
      while(t != NULL) {
         if(t->d < d) {
            if(t->right == NULL) {
               t->right = temp;
               break;
            }
            t = t->right;
         } else if(t->d > d) {
            if(t->left == NULL) {
               t->left = temp;
               break;
            }
            t = t->left;
         }
      }
   }
   return root;
}
void Search(node *root, int d) {
   int depth = 0;
   node *temp = new node;
   temp = root;
   while(temp != NULL) {
      depth++;
      if(temp->d == d) {
         cout<<"\nitem found at depth: "<<depth;
         return;
      } else if(temp->d > d)
         temp = temp->left;
         else
            temp = temp->right;
   }
   cout<<"\n item not found";
   return;
}
int main() {
   char ch;
   int n, i, a[10] = {93, 53, 45, 2, 7, 67, 32, 26, 71, 76};
   node *root = new node;
   root = NULL;
   for (i = 0; i < 10; i++)
      root = InsertIntoTree(root, a[i]);
   up:
   cout<<"\nEnter the Element to be searched: ";
   cin>>n;
   Search(root, n);
   cout<<"\n\n\tDo you want to search more...enter choice(y/n)?";
   cin>>ch;
   if(c == 'y' || c == 'Y')
      goto up;
   return 0;
}
Enter the Element to be searched: 26
item found at depth: 7
Do you want to search more...enter choice(y/n)?
Enter the Element to be searched: 1
item not found
Do you want to search more...enter choice(y/n)?
How to give manual input from user while running Selenium IDE script?

We can give manual input from the user while running Selenium IDE script. This can be done with the help of the Command, Target and Value steps given below −
Command −
execute script
Target −
return prompt("Subject","");
Value −
Input
Command −
echo
Target −
${Input}
Click on Run current test as highlighted in the below image.
A prompt for user input comes up.
The text Selenium Java is entered within the prompt.
Selenium IDE log captures the text entered.
How to center a <div> using Flexbox property of CSS ?

25 Jun, 2021
In this article, we will learn to center an HTML div element using flexbox property of CSS. 
Please refer this article to know more about flexbox.
Approach: To center the <div> element horizontally using flexbox.
We use the property of display set to flex i.e. display: flex;
Align items to center using align-items: center;
The last step is to set justify-content to center i.e. justify-content: center;
Example 1: The following example is using flex property.
HTML
<!DOCTYPE html><html>  <head>    <style>        .center {            display: flex;            justify-content: center;            color: green;        }    </style></head>  <body>    <h2 style="color:green">GeeksforGeeks</h2>    <div class='center'>        This text is centered    </div></body>  </html>
Output:
Example 2: If we want to center the <div> horizontally and vertically, we just add height: 500px; in the CSS part of the code.
HTML
<!DOCTYPE html><html>  <head>    <style>        .center {            display: flex;            justify-content: center;            align-items: center;            height: 500px;        }    </style></head>  <body>    <h2 style="color:green">GeeksforGeeks</h2>    <div class="center">        This text is centered    </div></body>  </html>
Output:
CSS-Properties
CSS-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting the Total Number of Days in a Month Using If-else and Switch Statements in C#

28 May, 2020
Given a number N, the task is to write a C# program to print the number of days in the Month N.
Examples:
Input: N = 12Output: 31
Input: N = 2Output: 28/29
This task can be done using the following approaches:
1. Using if else statement : Appropriate month number is checked and then number of days in a month is print using else if statement. Number of days are follows :
Month = [1, 3, 5, 7, 8, 10, 12] , Number of days = 31
Month = [2] , Number of days = 28/29
Month = [4, 6, 9, 11] , Number of days = 30

Below is the implementation of the above approach:
Output:
C#
// C# Program to Print Number of Days// in a Month using Else If Statement  using System;  public class GFG{      // Function to print the Number    // of Days in a N    static void PrintNumberofDays(int N)     {       // Check for the Ns        if (N == 1 || N == 3 || N == 5 || N == 7          || N == 8 || N == 10 || N == 12) {              Console.Write("31");        }                   else if (N == 4 || N == 6 || N == 9 ||               N == 11) {               Console.Write("30");        }                   else if (N == 2) {               Console.Write("28/29");        }    }          // Driver Code    static public void Main ()    {        int N = 5; // 1 <= N <= 12        PrintNumberofDays(N);    }}
Output:
31

2. Using Switch Condition : Same as Else if , here month number is checked and it is redirected to cases,and then number of days in a month is print. Below is the implementation of the above approach:
C#
// C# Program to Print Number of Days// in a Month using Switch Condition  using System;  public class GFG{      // Function to print the Number    // of Days in a N    static void PrintNumberofDays(int N)     {        // Check for the N        switch(N )        {            case 1:            case 3:            case 5:                 case 7:            case 8:            case 10:            case 12:                             Console.Write("31");                break;                          case 4:             case 6:            case 9:            case 11:                                 Console.Write("30");                 break;                          case 2:            Console.Write("28/29");            break;        }    }          // Driver Code    static public void Main ()    {        int N = 5; // 1 <= N <= 12        PrintNumberofDays(N);    }}
Output:
31

C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas tseries.offsets.CustomBusinessDay

23 Apr, 2019
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F).
DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created.
Pandas tseries.offsets.CustomBusinessDay() function is used to create your own custom business days. DateOffset subclass representing possibly n custom business days, excluding holidays.
Syntax: pandas.tseries.offsets.CustomBusinessDay()
Parameter :n : intnormalize : Normalize start/end dates to midnight before generating date rangeweekmask : weekmask of valid business days, passed to numpy.busdaycalendarholidays : list/array of dates to exclude from the set of valid business days, passed to numpy.busdaycalendarcalendar : pd.HolidayCalendar or np.busdaycalendaroffset : timedelta, default timedelta(0)
Returns : custom business day
Example #1: Use pandas.tseries.offsets.CustomBusinessDay() function to create your own custom business days.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-4-23 11:15:00')  # Create an offsetcbd = pd.tseries.offsets.CustomBusinessDay(weekmask = 'Mon Tue Wed')  # Print the Timestampprint(ts)  # Print the Offsetprint(cbd)
Output :
Now we will add the offset to the given timestamp object to increment the datetime value.
# Adding the offset to the given timestampnew_timestamp = ts + cbd  # Print the updated timestampprint(new_timestamp)
Output :As we can see in the output, we have successfully created an offset and added it to the given timestamp.
Example #2: Use pandas.tseries.offsets.CustomBusinessDay() function to create your own custom business days.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-4-23 11:15:00')  # Create an offsetcbd = pd.tseries.offsets.CustomBusinessDay(n = 3, weekmask = 'Mon Tue Wed Thu')  # Print the Timestampprint(ts)  # Print the Offsetprint(cbd)
Output :
Now we will add the offset to the given timestamp object to increment the datetime value.
# Adding the offset to the given timestampnew_timestamp = ts + cbd  # Print the updated timestampprint(new_timestamp)
Output :
As we can see in the output, we have successfully created an offset and added it to the given timestamp.
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Restrict EditText Input to Some Special Characters in Android

09 Dec, 2021
In some of the other applications, most of us must have witnessed that while typing in some field, we get a warning or a flash message that certain characters are not allowed or are not accepted as valid input. For example, sometimes, while renaming a file or a folder in Windows, if we simply type in ‘?’, we get a message that ‘?’ is not accepted as valid input. This happens because the character ‘?’ must be having some functional meaning in the file systems of that OS. Similarly, there can be restrictions on other special characters as they might be having some functional significance in the file systems of the OS. Similarly, this concept can be applied to any kind of user inputs. Let us say if the input is the desired username while sign-up, we can apply a similar concept to avoid the use of numbers or special characters. So, in this article, we will show you how you could limit the input to a specific set of characters for EditText in Android.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We created an EditText, where input can be taken. Note that android:digits attribute allows the given characters only in the input stream.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <EditText        android:layout_width="match_parent"        android:layout_height="50sp"        android:hint="Type something..."        android:inputType="text"        android:digits="abcd@#$123"/>  </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. No additional code is needed inside this file. 
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)    }}
Output:
You can see that only those characters are printed in the EditText that has been declared against the android:digits attribute of the EditText.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is "network ID" and "host ID" in IP Addresses? - GeeksforGeeks

24 Nov, 2021
IP addresses are divided into 5 classes namely, Class A, Class B, Class C, Class D, Class E. This concept came in around the 1980s. Where,
Class A is generally used for big networks such as the ISP networks.
Class B is used for medium to large networks like some big organizations.
Class C addresses are generally used for smaller networks.
Class D addresses are used for Multicasting.
Class E addresses are reserved addresses and they are used for experimental purposes.
Range of All Classes:
Class A: 1.0.0.0 to 127.255.255.255
Class B: 128.0.0.0 to 191.255.255.255
Class C: 192.0.0.0 to 223.255.255.255
Class D: 224.0.0.0 to 239.255.255.255
Class E: 240.0.0.0 to 255.255.255.255
Network ID:
A network ID or NetID is the fragment of IP address that classifies the network for a specified host i.e., it tells us which network the host belongs to, generally comprised of one to up to four octets in dotted-decimal representation. 
In dotted-decimal representation, an IP address is divided into four octets and based on which class the IP address belongs to its octets are further divided into network ID and HOST ID. 
For Class A first octet represents network ID as the prefix of the first octet is 0, it uses the remaining 7 bits for network ID, for Class B first and second octets represent network ID the prefix for class B is 10 so it uses the remaining 14 bits for network ID, for Class C first, second and third octet represents network ID the prefix of class C is 110 so it uses the remaining 21 bits for network ID, Class D, and Class E are reserved.
Host ID:
It is the fragment of an IP address that uniquely classifies a host on a specified TCP/IP network. A host ID can be found simply by ANDing the IP address in binary form with its respective default subnet mask (in binary form). The other fragment of an IP address is the network ID, which identifies the network to which the host belongs.
Host ID and Network ID
For Example, In the above Image,  the IP address of host C is 198.162.30.4 that means it belongs to class C, so its default subnet mask will be 255.255.255.0; Now applying AND on both, it will give the host ID 0.0.0.4 and network ID 198.162.30.0.
Picked
Computer Networks
Computer Subject
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Introduction and IPv4 Datagram Header
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Algorithms
Software Engineering | Coupling and Cohesion
Difference between NP hard and NP complete problem
Software Engineering | Prototyping Model
How to find the number of arguments in a Python function? - GeeksforGeeks

16 Aug, 2021
In this article, we are going to see how to count the number of arguments of a function in Python. We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of arguments of the function in python.Example 1: 
Python3
def no_of_argu(*args):         # using len() method in args to count    return(len(args))  a = 1b = 3 # arguments passedn = no_of_argu(1, 2, 4, a) # result printedprint(" The number of arguments are: ", n)
Output :  
The number of arguments passed are: 4
Example 2:
Python3
def no_of_argu(*args):       # using len() method in args to count    return(len(args)) print(no_of_argu(2, 5, 4))print(no_of_argu(4, 5, 6, 5, 4, 4))print(no_of_argu(3, 2, 32, 4, 4, 52, 1))print(no_of_argu(1))
Output : 
3
6
7
1
kalrap615
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python - API.followers_ids() in Tweepy - GeeksforGeeks

08 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The followers_ids() method of the API class in Tweepy module is used to get the IDs of all the followers of a user.
Syntax : API.followers_ids(id / user_id / screen_name)
Parameters : Only use one of the 3 options:
id : specifies the ID or the screen name of the user.
user_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen name.
screen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID.
Returns : a list of Integers
Example 1 : Using followers_ids() method with the screen name.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # screen name of the userscreen_name = "CoursesGfG"  # getting the followers listfollowers = api.followers_ids(screen_name)  print(screen_name + " has " + str(len(followers)) + " followers.")
Output :
CoursesGfG has 198 followers.

Example 2 : Using followers_ids() method with the user ID.
# user ID of the useruser_id = 1037141442  # getting the followers listfollowers = api.followers_ids(user_id)  print(api.get_user(user_id).screen_name + " has " + str(len(followers)) + " followers.")
Output :
GeeksQuiz has 3449 followers.

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Numpy ndarray.tolist() - GeeksforGeeks

27 Mar, 2019
With the help of numpy.ndarray.tolist() method, we can have the list of data elements which is converted from an ndarray using ndarray.tolist() method.
Syntax: ndarray.tolist()
Parameters: none
Returns: The possibly nested list of array elements.
Example #1 :In this example, we can see that by using ndarray.tolist() method, we can have the list of data items in ndarray.
# import the important module in pythonimport numpy as np        # make an array with numpygfg = np.array([1, 2, 3, 4, 5])        # applying ndarray.tolist() methodprint(gfg.tolist())
[1, 2, 3, 4, 5]

Example #2 :
# import the important module in pythonimport numpy as np        # make an array with numpygfg = np.array([[1, 2, 3, 4, 5],                [6, 5, 4, 3, 2]])        # applying ndarray.tolist() methodprint(gfg.tolist())
[[1, 2, 3, 4, 5], [6, 5, 4, 3, 2]]

Python numpy-ndarray
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to get the path of current script using Node.js ? - GeeksforGeeks

31 Jan, 2020
We can get the path of the present script in node.js by using __dirname and __filename module scope variables.
__dirname: It returns the directory name of the current module in which the current script is located.
__filename: It returns the file name of the current module. This is the current module file’s absolute path with symlinks (symbolic links) resolved.
Let’s Consider the below file structure of the project:
Below examples illustrate the use of __dirname and __filename module scope variable in node.js:
Example 1: Determine the path of the present script while executing app.js file.
app.js file:
// Node.js program to demonstrates how to// get the current path of script  // To get the filenameconsole.log(`Filename is ${__filename}`);  // To get the directory nameconsole.log(`Directory name is ${__dirname}`);
Output:
Filename is D:\DemoProject\app.js
Directory name is D:\DemoProject

Example 2: Determine the path of the present script while executing routes\user.js file.
user.js file:
// Node.js program to demonstrates how to// get the current path of script  // To get the filenameconsole.log(`Filename is ${__filename}`);  // To get the directory nameconsole.log(`Directory name is ${__dirname}`);
Output:
Filename is D:\DemoProject\routes\app.js
Directory name is D:\DemoProject\routes

Node.js-Misc
Picked
Technical Scripter 2019
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
How do I redraw an image using Python's Matplotlib?

To redraw an image using python's Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Get the current axis using gca() method.
Show the current figure.
Iterate in the range of 20 and redraw the plot.
Use plot() method to plot random data points.
Redraw on the figure and pause for a while.
Close a figure window.
import numpy as np
from matplotlib import pyplot as plt

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

fig = plt.figure()
ax = fig.gca()
fig.show()

for i in range(20):
   ax.plot(np.random.randint(1, 5), np.random.randint(1, 5), '*', ms=10)
   fig.canvas.draw()
   plt.pause(0.1)

plt.close(fig)
Find the second last node of a linked list in single traversal in C++

Now we will see how to get the second last element in the linked list. Suppose there are few elements like [10, 52, 41, 32, 69, 58, 41], second last element is 58.
To solve this problem, we will use two pointers one will point to current node, and another will point to previous node of the current position, then we will move until the next of current is null, then simply return the previous node.
 Live Demo
#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *next;
};
void prepend(Node** start, int new_data) {
   Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = NULL;
   if ((*start) != NULL){
      new_node->next = (*start);
      *start = new_node;
   }
   (*start) = new_node;
}
int secondLastElement(Node *start) {
   Node *curr = start, *prev = NULL;
   while(curr->next != NULL){
      prev = curr;
      curr = curr->next;
   }
   return prev->data;
}
int main() {
   Node* start = NULL;
   prepend(&start, 15);
   prepend(&start, 20);
   prepend(&start, 10);
   prepend(&start, 9);
   prepend(&start, 7);
   prepend(&start, 17);
   cout << "Second last element is: " << secondLastElement(start);
}
Second last element is: 20
Draw a border around an undecorated JFrame in Java

At first, set an undecorated frame −
setUndecorated(true);
Now draw a border −
getRootPane().setBorder (.createMatteBorder(3, 3, 3, 3, Color.ORANGE));
The following is an example to draw a border around an undecorated JFrame −
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingDemo extends JFrame {
   JLabel label = new JLabel("Welcome!", JLabel.CENTER);
   public SwingDemo() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(new Dimension(500, 300));
      add(label, BorderLayout.CENTER);
      setUndecorated(true);
      getRootPane().setBorder(
         BorderFactory.createMatteBorder(3, 3, 3, 3, Color.ORANGE));
      setVisible(true);
   }
   public static void main(String[] args) {
      new SwingDemo();
   }
}
C++ Program to Emulate N Dice Roller

Here is the code to emulate N dice roller. This can be done by generating random number between 1-6.
Begin
   Declare n
   Read n
   For i = 0 to n-1 do
      Generate sequence with rand() mod 6 + 1
      Print the sequence
   Done
End
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
   cout << "Enter the number of dice: ";
   int n;
   cin >> n;
   cout << "The values on dice are: ";
   for (int i = 0; i < n; i++)
      cout << (rand() % 6) + 1<<" ";
}
Enter the number of dice: The values on dice are: 2 5 4 2 6 2 5
Meteor - First Application

In this chapter, we will learn how to create your first Meteor application.
To create the app, we will run the meteor create command from the command prompt window. The apps name will be meteorApp.
C:\Users\username\Desktop\Meteor>meteor create meteorApp

We can run the app by typing the meteor command.
C:\Users\username\Desktop\meteorApp>meteor

This command will start several processes, which can be seen in the following image.
Now, we can open the http://localhost:3000/ address to see how our first Meteor App looks like.

    73 Lectures 
     4 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to parse a string into a nullable int in C#?

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable where T is a type.
Nullable types can only be used with value types.
Nullable types can only be used with value types.
The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
The HasValue property returns true if the variable contains a value, or false if it is null.
The HasValue property returns true if the variable contains a value, or false if it is null.
You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give a compile time error.
Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give a compile time error.
static class Program{
   static void Main(string[] args){
      string s = "123";
      System.Console.WriteLine(s.ToNullableInt());
      Console.ReadLine();
   }
   static int? ToNullableInt(this string s){
      int i;
      if (int.TryParse(s, out i)) return i;
      return null;
   }
}
123
When Null is passed to the extenstion method it doesn't print any value
static class Program{
   static void Main(string[] args){
      string s = null;
      System.Console.WriteLine(s.ToNullableInt());
      Console.ReadLine();
   }
   static int? ToNullableInt(this string s){
      int i;
      if (int.TryParse(s, out i)) return i;
      return null;
   }
}
DOMException Failed to load because no supported source was found

It can be a Cross-Origin Resource Sharing (CORS) issue.
video.crossOrigin = 'anonymous';
To enable cross-origin resource sharing, use the following. It allows the images to pass the HTTP header with an image response.
Access-Control-Allow-Origin: *
You can also use the HTML() method −
$('#audio').html('<audio autoplay><source src="demo.mp3"></audio>');