code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.pyplot.margins() function in Python - GeeksforGeeks

03 Jan, 2021
Prerequisites: Matplotlib
Matplotlib.pyplot.margins() is a function used to set the margins of the x and y axes. All input parameters must be a float that too within the range [0, 1]. We cannot pass both positional and keyword arguments at once as that will raise a TypeError. The padding added to each limit of the axes is the margin times the data interval for that axis. If no arguments are provided, the existing margins remain in place. Specifying margins changes auto-scaling. 
If only one float value if provided, that is taken as margins for both x and y axes.
If two float values are provided, they will be taken to specify x-margin and y-margin axes respectively.
Syntax:
margins(x, y, tight)
Parameters
– x, y : Used to specify margin values for x and y axes. These can only be used individually.
– tight : Boolean 
If this parameter is specified as True, then it is considered the specified margins require no additional padding to match tick marks.
If this parameter is set to None, it will preserve original setting.
Various implementation for using this function is given below:
Example: General application
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x]  plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins()plt.show()
Output:
Example : Passing arguments to the margins() function 
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x]  plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(0.5)plt.show()
Output:
Example: Passing different values for x and y that are less than 1, the graph produced will be zoomed in
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x]  plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=0.1, y=0.5)plt.show()
Output:
Example: Passing different values for x and y that are greater than , the graph produced will be zoomed out
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x]  plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=2, y=2)plt.show()
Output:
Matplotlib Pyplot-class
Picked
Python-matplotlib
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()
Lodash _.forIn() Method - GeeksforGeeks

14 Sep, 2020
The Lodash _.forIn() Method Iterates over keys and values of the given object and invokes iteratee function for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.
Syntax:
_.forIn( object, iteratee_function)

Parameters: This method accepts two parameters as mentioned above and described below:
object: This is the object to find in.
iteratee_function: the function that is invoked per iteration.
Return Value: This method returns an object.
Example 1:
// Defining Lodash variable const _ = require('lodash');   var users = {  'a':  1,  'b':  2,  'c':  3};   _.forIn(users, function(value, key) {  console.log(key);});
Output:
a
b
c

Example 2:
// Defining Lodash variable const _ = require('lodash');   var users = {  'a':  1,  'b':  2,  'c':  3};   _.forIn(users, function(value, key) {    if(value > 1) {        console.log(key, value);    }});
Output:
b 2
c 3

Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:
npm install lodash
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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
Python program to find the sum of dictionary keys - GeeksforGeeks

01 Oct, 2020
Given a dictionary with integer keys. The task is to find the sum of all the keys.
Examples:
Input : test_dict = {3 : 4, 9 : 10, 15 : 10, 5 : 7} 
Output : 32 
Explanation : 3 + 9 + 15 + 5 = 32, sum of keys.

Input : test_dict = {3 : 4, 9 : 10, 15 : 10} 
Output : 27 
Explanation : 3 + 9 + 15 = 27, sum of keys. 
Method #1: Using loop
This is one of the ways in which this task can be performed. In this, we iterate all the keys in the dictionary and compute summation using a counter.
Python3
# Python3 code to demonstrate working of# Dictionary Keys Summation# Using loop  # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  res = 0for key in test_dict:      # adding keys    res += key  # printing resultprint("The dictionary keys summation : " + str(res))
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38

Method #2 : Using keys() + sum()
This is shorthand with the help of which this task can be performed. In this, we extract all keys in list using keys(), and the summation is performed using sum().
Python3
# Python3 code to demonstrate working of# Dictionary Keys Summation# Using keys() + sum()  # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # sum() performs summationres = sum(list(test_dict.keys()))  # printing resultprint("The dictionary keys summation : " + str(res))
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38

 
Python dictionary-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
PyQt5 - QDial - GeeksforGeeks

07 Jul, 2020
QDial is a class in PyQt5 which provide user to select the value within a program-definable range, and the range either wraps around (for example, with angles measured from 0 to 359 degrees). Also, it can be used to show the current value in a similar way of speedometer. Below is how the QDial looks like
Example :A window having a QDial and user can change the value it and when user change the value the current value will get displayed in the label
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating QDial object        dial = QDial(self)          # setting geometry to the dial        dial.setGeometry(100, 100, 100, 100)          # adding action to the dial        dial.valueChanged.connect(lambda: dial_method())          # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(220, 125, 200, 60)          # making label multiline        label.setWordWrap(True)          # method called by the dial        def dial_method():              # getting dial value            value = dial.value()              # setting text to the label            label.setText("Current Value : " + str(value))    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDial
Python-gui
Python-PyQt
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Connect MySQL database using MySQL-Connector Python - GeeksforGeeks

13 Sep, 2021
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies. 
In the following example we will be connecting to MySQL database using connect()Example: 
Python3
# Python program to connect# to mysql database  import mysql.connector  # Connecting from the serverconn = mysql.connector.connect(user = 'username',                               host = 'localhost',                              database = 'database_name') print(conn) # Disconnecting from the serverconn.close()
Output: 
Also for the same, we can use connection.MySQLConnection() class instead of connect():Example: 
Python3
# Python program to connect# to mysql database  from mysql.connector import connection # Connecting to the serverconn = connection.MySQLConnection(user = 'username',                              host = 'localhost',                              database = 'database_name') print(conn) # Disconnecting from the serverconn.close()
Output: 
Another way is to pass the dictionary in the connect() function using ‘**’ operator:Example: 
Python3
# Python program to connect# to mysql database  from mysql.connector import connection  dict = {  'user': 'root',  'host': 'localhost',  'database': 'College'} # Connecting to the serverconn = connection.MySQLConnection(**dict) print(conn) # Disconnecting from the serverconn.close()
Output: 
 
saurabh1990aror
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
numpy.diag() in Python

09 Mar, 2022
numpy.diag(a, k=0) : Extracts and construct a diagonal array Parameters : 
a : array_like 
k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
Returns : 
ndarray
Python
# Python Programming illustrating# numpy.diag method  import numpy as geek  # matrix creation by array inputa = geek.matrix([[1, 21, 30],                  [63 ,434, 3],                  [54, 54, 56]])  print("Main Diagonal elements : \n", geek.diag(a), "\n")  print("Diagonal above main diagonal : \n", geek.diag(a, 1), "\n")  print("Diagonal below main diagonal : \n", geek.diag(a, -1))
Output :  
Main Diagonal elements : 
 [  1 434  56] 

Diagonal above main diagonal : 
 [21  3] 

Diagonal below main diagonal : 
 [63 54]
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.diagflat.html#numpy.diagflat Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them . This article is contributed by Mohit Gupta_OMG . 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. 
gabaa406
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can we find the employees from MySQL table whose age is greater than say 30 years, providing the only date of birth on the table?

To understand this concept, we are using the data from table ‘emp_tbl’ as follows −
mysql> Select * from emp_tbl;
+--------+------------+
| Name   | DOB        |
+--------+------------+
| Gaurav | 1984-01-17 |
| Gaurav | 1990-01-17 |
| Rahul  | 1980-05-22 |
| Gurdas | 1981-05-25 |
| Naveen | 1991-04-25 |
| Sohan  | 1987-12-26 |
+--------+------------+
6 rows in set (0.00 sec)

mysql> SELECT Name,SYSDATE(),DOB,DATEDIFF(SYSDATE(),DOB)/365 AS AGE from emp_tbl WHERE(DATEDIFF(SYSDATE(), DOB)/365)>30;
+--------+---------------------+------------+---------+
| Name   | SYSDATE()           | DOB        | AGE     |
+--------+---------------------+------------+---------+
| Gaurav | 2017-12-26 22:33:24 | 1984-01-17 | 33.9644 |
| Rahul  | 2017-12-26 22:33:24 | 1980-05-22 | 37.6219 |
| Gurdas | 2017-12-26 22:33:24 | 1981-05-25 | 36.6137 |
| Sohan  | 2017-12-26 22:33:24 | 1987-12-26 | 30.0219 |
+--------+---------------------+------------+---------+
4 rows in set (0.10 sec)
How to use :: Namespace Alias Qualifier in C#

06 Mar, 2019
Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global. Thus it doesn’t invoke a lookup in the aliased namespace but in the global namespace.
Syntax:
alias_name::class-name;
Example:
// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing System;  // creating aliased nameusing first = firstnamespace;using sec = secondnamespace;  namespace Geeks {  class GFG {      // Main Method    static void Main()    {          // use of Namespace alias qualifier(::)        first::GFG1 obj1 = new first::GFG1();         obj1.display();    }}}  // Both namespaces have a // class named GFG1namespace firstnamespace {  class GFG1 {      public void display()    {        Console.WriteLine("It is the first namespace.");    }}}  namespace secondnamespace {  class GFG1 {      public void display()    {        Console.WriteLine("It is the second namespace.");    }}}
It is the first namespace.

Note: The namespace alias qualifier :: is only used for the namespaces or aliases and cannot be used for subclasses.
Example:
System.Collections::lists obj= new System.Collections.lists() // illegal
aliasname = System.Collections;
aliasname::lists obj = new aliasname::lists(); // Legal

// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing aliasname = System.Collections;  namespace Geeks {  class GFG {      // Main Method    static void Main()    {        // using :: Namespace Alias Qualifier        aliasname::Hashtable obj = new aliasname::Hashtable();          // Add items to the table.        obj.Add("ASCII value of A is:", "65");        obj.Add("ASCII value of B is:", "66");          // displaying the result        foreach(string i in obj.Keys)        {            System.Console.WriteLine(i + " " + obj[i]);        }    }}}
ASCII value of A is: 65
ASCII value of B is: 66

Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to combine two vectors in R ?

05 Apr, 2021
In this article, we will learn how to combine two vectors in R Programming Language. We can combine two or more vectors using function c() itself. While using function c() All arguments are coerced to a common type which is the type of the returned value.
Syntax: c(...)
Parameters:
...: arguments to be combined
Returns: A vector
Steps –
Create vectors to be combined
Combine them using c()
Display combined result
Example 1: Vectors of the same data type will give the vector of input data type as result. 
R
a <- c(1, 2, 8) b <- c(5, 8, 9, 10) c <- c(a,b)c  cat("typeof a", typeof(a), " typeof b", typeof(b),    "typeof c",typeof(c) , "\n")  a <- c("geek","for","geek")b <- c("hello","coder")c <- c(a,b)c  cat("typeof a", typeof(a), " typeof b", typeof(b),    "typeof c",typeof(c) , "\n")  a <- c(TRUE, FALSE, NA)b <- c(TRUE, FALSE)c <- c(a,b)c  cat("typeof a", typeof(a), " typeof b", typeof(b),    "typeof c",typeof(c) , "\n")
Output:
[1]  1  2  8  5  8  9 10
typeof a double  typeof b double typeof c double 
[1] “geek”  “for”   “geek”  “hello” “coder”
typeof a character  typeof b character typeof c character 
[1]  TRUE FALSE    NA  TRUE FALSE
typeof a logical  typeof b logical typeof c logical 
While combining vectors of type double and character, character and logical, double and logical c() function return vector of a type character, character, double respectively.
Example 2: 
R
a <- c(1, 2, 8) b <- c("hello","coder")c <- c(a,b)  # a vector of type double and b vector of type # character result c vector of type characterc  cat("typeof a", typeof(a), " typeof b", typeof(b),     "typeof c",typeof(c) , "\n")  a <- c("geek","for","geek")b <- c(TRUE, FALSE)  # a vector of type character and b vector of type logical# result c vector of type characterc <- c(a,b)c  cat("typeof a", typeof(a), " typeof b", typeof(b),     "typeof c",typeof(c) , "\n")  a <- c(1, 2, 8) b <- c(TRUE, FALSE)c <- c(a,b)  # a vector of type double and b vector of type # logical result c vector of type doublec  cat("typeof a", typeof(a), " typeof b", typeof(b),    "typeof c",typeof(c) , "\n")
Output:
[1] “1”     “2”     “8”     “hello” “coder”
typeof a double  typeof b character typeof c character 
[1] “geek”  “for”   “geek”  “TRUE”  “FALSE”
typeof a character  typeof b logical typeof c character 
[1] 1 2 8 1 0
typeof a double  typeof b logical typeof c double 
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to dynamically insert id into table element using JavaScript ?

29 May, 2021
This article explains how to dynamically insert “id” into the table element. This can be done by simply looping over the tables and add “id”s dynamically.
Syntax:
The setAttribute() method adds the specified attribute to an element and gives the specified value.table.setAttribute("id", "Dynamically Generated ID")
table.setAttribute("id", "Dynamically Generated ID")
It can also be done by accessing the “id” of the selected element (table).table.id = "Dynamically Generated ID";
table.id = "Dynamically Generated ID";
Example:
HTML
<!DOCTYPE html><html> <head>    <style>        table,        th,        td {            border: 1px solid black;            border-collapse: collapse;            margin: auto;            width: 50%;            text-align: center;        }    </style></head> <body>    <h1 style="color:green;text-align: center;">        GeeksForGeeks    </h1>         <table>        <tr>            <th>Firstname</th>            <th>Lastname</th>        </tr>        <tr>            <td>Jill</td>            <td>Smith</td>        </tr>        <tr>            <td>Eve</td>            <td>Jackson</td>        </tr>    </table>    <br>     <table>        <tr>            <th>Firstname</th>            <th>Lastname</th>        </tr>        <tr>            <td>John</td>            <td>Doe</td>        </tr>        <tr>            <td>Emma</td>            <td>Allen</td>        </tr>    </table>     <script>        // Getting the table element        var tables = document            .getElementsByTagName("table");         // Looping over tables        for (var i = 0; i < tables.length; i++) {             // Get the ith table            var table = tables[i];             // Set the id dynamically            table.setAttribute("id", i + 1);             // The line below will also give id            // dynamically to the tables            //table.id = i+1;        }    </script></body> </html>
Output: The two tables will be created with “id”s 1 and 2 respectively.
sweetyty
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Single and Double Quotes | Python

14 Jul, 2019
Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement. Sometimes we have to use quotes (single or double quotes) together in the same string, in such cases, we use single and double quotes alternatively so that they can be distinguished.
Example #1:Check below example and analyze the error –
#Gives Error
print('It's python')


Explanation –It gives an invalid syntax error. Because single quote after “it” is considered as the end of the string and rest part is not the part of a string.
It can be corrected as:
print("It's Python !")
Output:
It's Python!

Example #2:If you want to print ‘WithQuotes’ in python, this can’t be done with only single (or double) quotes alone, it requires simultaneous use of both.
# this code prints the output within quotes.# print WithQuotes within single quotesprint("'WithQuotes'")print("Hello 'Python'")  # print WithQuotes within single quotesprint('"WithQuotes"')print('Hello "Python"')
Output –
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"

Conclusion –The choice between both the types (single quotes and double quotes) depends on the programmer’s choice. Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it’s sometimes our need to use one type over the other.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Different ways to create Pandas Dataframe
Queue in Python
Read a file line by line in Python
Defaultdict in Python
How to iterate through Excel rows in Python?
What is the syntax for input parameters (variables) in a MySQL query?

To set a variable in MySQL, you need to use the SET command. Following is the syntax:
set @yourVariableName:=yourValue;
select *from yourTableName where yourColumnName=@yourVariableName;
Let us first create a table:
mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20),
   LastName varchar(20)
);
Query OK, 0 rows affected (0.83 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable values(10,'Carol','Taylor');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(20,'John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(30,'John','Smith');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(40,'David','Miller');
Query OK, 1 row affected (0.18 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
| 10   | Carol     | Taylor   |
| 20   | John      | Doe      |
| 30   | John      | Smith    |
| 40   | David     | Miller   |
+------+-----------+----------+
4 rows in set (0.00 sec)
Let us now see how to set user defined variables in MySQL:
mysql> set @myId:=30;
Query OK, 0 rows affected (0.00 sec)
mysql> select *from DemoTable where Id=@myId;
This will produce the following output
+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
| 30   | John      | Smith    |
+------+-----------+----------+
1 row in set (0.00 sec)
What is getContext in HTML5 Canvas?

The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.
Following is the code to get required context along with a check if your browser supports <canvas> element:
var canvas = document.getElementById("mycanvas");
if (canvas.getContext){
   var ctx = canvas.getContext('2d');

   // drawing code here
   } else {

   // canvas-unsupported code here
}
C++ Program to Perform Fermat Primality Test

Fermat Primality test performs to check a given number is prime or not. Here is a C++ code of this algorithm.
Begin
   modulo(base, e, mod)
   a = 1
   b = base
   while (e > 0)
      if (e mod 2 == 1)
         a = (a * b) % mod
         b = (b * b) % mod
         e = e / 2
      return a % mod
End

Begin
   Fermat(ll m, int iterations)
   if (m == 1)
      return false
   done
   for (int i = 0; i < iterations; i++)
      ll x = rand() mod (m - 1) + 1
      if (modulo(x, m - 1, m) != 1)
         return false
      done
   return true
End
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
ll modulo(ll base, ll e, ll mod) {
   ll a = 1;
   ll b = base;
   while (e > 0) {
      if (e % 2 == 1)
         a = (a * b) % mod;
         b = (b * b) % mod;
         e = e / 2;
   }
   return a % mod;
}
bool Fermat(ll m, int iterations) {
   if (m == 1) {
      return false;
   }
   for (int i = 0; i < iterations; i++) {
      ll x = rand() % (m - 1) + 1;
      if (modulo(x, m - 1, m) != 1) {
         return false;
      }
   }
   return true;
}
int main() {
   int iteration = 70;
   ll num;
   cout<<"Enter integer to test primality: ";
   cin>>num;
   if (Fermat(num, iteration))
      cout<<num<<" is prime"<<endl;
   else
      cout<<num<<" is not prime"<<endl;
   return 0;
}
Enter integer to test primality: 13 is prime
C++ Program to Implement a Heuristic to Find the Vertex Cover of a Graph

Vertex Cover of a Graph is to find a set of vertices V, such that for every edge connecting M to N in graph, either M or N (or both) are present in V. In this program, we Implement a Heuristic to Find the Vertex Cover of a Graph.
Begin
   1) Initialize a set S as empty.
   2) Take an edge E of the connecting graph Say M and N.
   3) Add both vertex to the set S.
   4) Discard all edges in the graph with endpoints at M or N.
   5) If some edge is still left in the graph Go to step 2,
   6) Print the final set S is a vertex cover of the graph.
End
#include<bits/stdc++.h>
using namespace std;
vector<vector<int> > g;
bool v[11110];
int i,j;
vector<int> sol_vertex(int n,int e) {
   vector<int> S;
   for(i=0;i<n;i++) {
      if(!v[i]) {
         for(j=0;j<(int)g[i].size();j++) {
            if(!v[g[i][j]]) {
               v[i]=true;
               v[g[i][j]]=true;
               break;
            }
         }
      }
   }
   for(i=0;i<n;i++)
      if(v[i])
   S.push_back(i);
   return S;
}
int main() {
   int n,e,a,b;
   cout<<"Enter number of vertices:";
   cin>>n;
   cout<<"Enter number of Edges:";
   cin>>e;
   g.resize(n);
   memset(v,0,sizeof(v));
   for(i=0;i<e;i++) {
      cout<<"Enter the end-points of edge "<<i+1<<" : ";
      cin>>a>>b;
      a--; b--;
      g[a].push_back(b);
      g[b].push_back(a);
   }
   vector<int> S = sol_vertex(n,e);
   cout<<"The required vertex cover is as follows:\n";
   for(i=0;i<(int)S.size();i++)
      cout<<S[i]+1<<" ";
   return 0;
}
Enter number of vertices:4
Enter number of Edges:5
Enter the end-points of edge 1 : 2 1
Enter the end-points of edge 2 : 3 2
Enter the end-points of edge 3 : 4 3
Enter the end-points of edge 4 : 1 4
Enter the end-points of edge 5 : 1 3
The required vertex cover is as follows:
1 2 3 4
Bootstrap Dropdowns

A dropdown menu is a toggleable menu that allows the user to choose one value 
from a predefined list:
HTML
CSS
JavaScript
About Us
The .dropdown class indicates a dropdown menu.
To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and 
the 
data-toggle="dropdown" attribute.
The .caret class creates a caret arrow icon (), which indicates that the 
button is a dropdown.
Add the .dropdown-menu class to a <ul> element to actually build the dropdown menu.
The .divider class is used to separate links inside the dropdown menu with a thin horizontal border:
Dropdown header 1
HTML
CSS
JavaScript
Dropdown header 2
About Us
The .dropdown-header class is used to add headers inside the dropdown menu:
Normal
Disabled
Active
Highlight a specific dropdown item with the .active class (adds a blue background color).
To disable an item in the dropdown menu, use the .disabled class (gets a light-grey text color and a "no-parking-sign" icon on hover):
HTML
CSS
JavaScript
About Us
To right-align the dropdown, add the .dropdown-menu-right class to the element 
with .dropdown-menu:
HTML
CSS
JavaScript
About Us
If you want the dropdown menu to expand upwards instead of downwards, change 
the <div> element with class="dropdown" to "dropup":
To help improve accessibility for people using screen readers, you should 
include the following role and aria-* attributes, when creating a dropdown menu:
Add the required classes and attributes to create a dropdown list.
<div class="">
  <button 
  class="btn btn-primary ">
  Dropdown Example
  <span class="caret"></span></button>
  <ul class="">
    <li><a href="#">HTML</a></li>
    <li><a href="#">CSS</a></li>
    <li><a href="#">JavaScript</a></li>
  </ul>
</div>

Start the Exercise
For a complete reference of all dropdown options, methods and events, go to our
Bootstrap JS Dropdown Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Minimum Number of Jumps Problem

In this problem, a list of positive integers is given. Each integer is denoting that how many maximum steps that can be made from the current element. Starting from the first element, we have to find the minimum number of jumps to reach the end item of the list.
For the dynamic programming approach, a jumps array is defined to store the minimum number of jumps required. Like for a value of jumps[i], it indicates that how many minimum jumps are needed to reach the ith index of the array from the 0th index.
Input:
A list of integers. {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}
Output:
The minimum number of jumps to reach the end location. It is 3.
Start from value 1, go to 3. then jumps 3 values and reach 8. then jump 8 values and reach the last element.
minPossibleJump(list, n)
Input: Number array, number of elements in the array.
Output: Minimum number of jumps required to reach at the end.
Begin
   define an array named jump of size n
   if n = 0 or list[0] = 0, then
      return ∞
   jump[0] := 0

   for i := 1 to n, do
      jumps[i] := ∞
      for j := 0 to i, do
         if i <= j + list[j] and jump[j] ≠ ∞, then
            jump[i] := minimum of jump[i] and (jump[j] + 1)
            break the loop
      done
   done

   return jump[n-1]
End
#include<iostream>
using namespace std;

int min(int x, int y) {
   return (x < y)? x: y;
}

int minPossibleJump(int list[], int n) {
   int *jumps = new int[n];     // dynamically create jumps array to store steps
   if (n == 0 || list[0] == 0)
       return INT_MAX;
   jumps[0] = 0;

   for (int i = 1; i < n; i++) {
      jumps[i] = INT_MAX;    //initially set jumps as infinity
      for (int j = 0; j < i; j++) {
         if (i <= j + list[j] && jumps[j] != INT_MAX) {
            jumps[i] = min(jumps[i], jumps[j] + 1);
            break;
         }
      }
   }
   return jumps[n-1];
}

int main() {
   int list[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
   int size = 11;
   cout << "Minimum number of jumps to reach end is: "<< minPossibleJump(list,size);
   return 0;
}
Minimum number of jumps to reach end is: 3
C# program to check if all the values in a list that are greater than a given value

Let’s say you need to find the elements in the following list to be greater than 80.
int[] arr = new int[] {55, 100, 87, 45};
For that, loop until the array length. Here, res = 80 i.e. the given element.
for (int i = 0; i < arr.Length; i++) {
   if(arr[i]<res) {
      Console.WriteLine(arr[i]);
   }
}
The following is the complete code −
using System;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = new int[] {
            55,
            100,
            87,
            45
         };
         // given integer
         int res = 80;
         Console.WriteLine("Given Integer {0}: ", res);
         Console.WriteLine("Numbers larger than {0} = ", res);
         for (int i = 0; i < arr.Length; i++) {
            if (arr[i] > res) {
               Console.WriteLine(arr[i]);
            }
         }
      }
   }
}
Powershell - Regular Expression - Match Quantifiers

Following is the example of supported quantifiers in Windows PowerShell
#Format:  *
#Logic    Specifies zero or more matches; for example, \wor (abc). Equivalent
#         to {0,}.
 "abc" -match "\w*"

#Format:  +
#Logic:   Matches repeating instances of the preceding characters.
 "xyxyxy" -match "xy+"

#Format:  ?
#Logic:   Specifies zero or one matches; for example, \w? or (abc)?.
#         Equivalent to {0,1}.
 "abc" -match "\w?"

#Format:  {n}
#Logic:   Specifies exactly n matches; for example, (pizza){2}.
 "abc" -match "\w{2}"

#Format:  {n,}
#Logic:   Specifies at least n matches; for example, (abc){2,}.
 "abc" -match "\w{2,}"

#Format:  {n,m}
#Logic:   Specifies at least n, but no more than m, matches.
 "abc" -match "\w{2,3}"
Output of all the above commands is True.

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Calculate interest amount by using formula in C language

Write a C program to calculate the deposited amount incremented after some years with interest
The formula for calculating interest is −
M=((r/100) * t);
A=P*exp(M);
Where r= rate of interest
            t=no. of years
            P=amount to be deposited
            M=temporary variable
            A= Final amount after interest
START
Step 1: declare double variables
Step 2: read amount to be deposited
Step 3: read rate of interest
Step 4: read years you want to deposit
Step 5: Calculate final amount with interest
         I. M=((r/100) * t);
         II. A=P*exp(M);
Step 6: Print final amount
STOP
#include<stdio.h>
#include<math.h>
#include<ctype.h>
int main(){
   double P,r,t,A,M;
   printf("amount to be deposit in the bank: ");
   scanf("%lf",&P);
   printf("\n enter the rate of interest:");
   scanf("%lf",&r);
   printf("\n How many years you want to deposit:");
   scanf("%lf",&t);
   M=((r/100) * t);
   A=P*exp(M);
   printf("\n amount after %0.1lf years with interest is:%0.2lf",t,A);
   return 0;
}
amount to be deposit in the bank: 50000
enter the rate of interest:6.5
How many years you want to deposit:5
amount after 5.0 years with interest is:69201.53
How to list out the hidden files in a Directory using Java program?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The isHidden() method of the File class verifies weather the (abstract path of) file/directory represented by the current File object, is hidden.
The ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
Therefore, to list all the hidden files in a directory get all the file objects using the ListFiles() method, verify weather each file is hidden using the isHidden() method.
Following Java program prints the file name and path of all the hidden files and directories in the specified directory −
import java.io.File;
public class ListingHiddenDirectories {
   public static void main(String args[]) {
      String filePath = "D://ExampleDirectory//";
      //Creating the File object
      File directory = new File(filePath);
      //List of all files and directories
      File filesList[] = directory.listFiles();
      System.out.println("List of files and directories in the specified directory:");
      for(File file : filesList) {
         if(file.isHidden()) {
            System.out.println("File name: "+file.getName());
            System.out.println("File path: "+file.getAbsolutePath());
         }
      }
   }
}
List of files and directories in the specified directory:
File name: hidden_directory1
File path: D:\ExampleDirectory\hidden_directory1
File name: hidden_directory2
File path: D:\ExampleDirectory\hidden_directory2
File name: SampleHiddenfile1.txt
File path: D:\ExampleDirectory\SampleHiddenfile1.txt
File name: SampleHiddenfile2.txt
File path: D:\ExampleDirectory\SampleHiddenfile2.txt
File name: SampleHiddenfile3.txt
File path: D:\ExampleDirectory\SampleHiddenfile3.txt
Get the Current Working Directory in Java

The method java.lang.System.getProperty() is used to obtain the system property. This system property is specified by the key which is the parameter for the method. To obtain the current working directory, the key used is user.dir.
A program that demonstrates this is given as follows −
 Live Demo
public class Demo {
   public static void main(String[] argv) throws Exception {
      String currentDirectory = System.getProperty("user.dir");
      System.out.println("The current working directory is " + currentDirectory);
   }
}
The output of the above program is as follows −
The current working directory is c:\JavaProgram
Now let us understand the above program.
The current working directory is obtained by using the key user.dir with the method java.lang.System.getProperty(). Then the current working directory is printed. A code snippet that demonstrates this is given as follows −
String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory);
JavaScript Number - valueOf()

This method returns the primitive value of the specified number object.
Its syntax is as follows −
number.valueOf()

Returns the primitive value of the specified number object.
Try the following example.
<html>
   <head>
      <title>JavaScript valueOf() Method </title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var num = new Number(15.11234);
         document.write("num.valueOf() is " + num.valueOf());
      </script>      
   </body>
</html>
num.valueOf() is 15.11234 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C# program to check if string is panagram or not

A pangram has all the 26 letters of an alphabet.
Below, we have entered a string, and will check whether it is a pangram or not −
string str = "The quick brown fox jumps over the lazy dog";
Now, check using the ToLower(), isLetter() and Count() functions that the string has all the 26 letters of not since pangram has all the 26 letters of an alphabet.
You can try to run the following code to check whether a string is pangram or not.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
   public class Program {
      public static void Main(string []arg) {
         string str = "The quick brown fox jumps over the lazy dog";
         Console.WriteLine("{0}: \"{1}\" is pangram", checkPangram(str), str);
         Console.ReadKey();
      }
      static bool checkPangram(string str) {
         return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;
      }
   }
}
True: "The quick brown fox jumps over the lazy dog" is pangram
QlikView - Dimensions and Measures

Dimensions and Measures are fundamental entities, which are always used in data analysis. For example, consider the result of the analysis, “what is the percentage change in volume of sales for each quarter?” In this case, each quarter represents the Dimensions, which is the name of the quarter. The percentage change in volume represents the Measures, which is a calculation with respect to each value in the dimension. Below are some widely accepted definition of these two terms.
Dimension − It is a descriptive field in the data set which represents few distinct values. Examples − Month, Year, Product ID etc.
Measures − It is a numeric field on which some calculations are performed for each distinct value of dimension.
Let us consider the following input data, which represents the sales volume and Revenue of different product lines and product categories in different regions. Save the data into a .csv file.
ProductID,ProductCategory,Region,SalesVolume, Revenue
1,Outdoor Recreation,Europe,457,25841
2,Clothing,Europe,125,54281
3,Costumes & Accessories,South Asia,781,54872
4,Athletics,South Asia,839,87361
5,Personal Care,Australia,473,15425
6,Arts & Entertainment,North AMerica,625,84151
7,Hardware,South America,772,45812

The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into the QlikView's memory
We can see the structure of the table by following the menu File → Table Viewer or pressing Control+T. The following screen comes up in which we have marked the dimensions inside a green box and the measures inside a red box.
Let us create a straight table chart showing the calculation using above dimensions and measures. Click on the Quick Chart Wizard as shown below.
Next, click on the Straight Table option. Click Next.
In this screen, we choose Region as the dimension as we want to select the total revenue for each region.
The Next screen prompts for applying the calculation on a measure field. We choose to apply Sum on the field Revenue.
On completing the above steps, we get the final chart which shows the total revenue(Measure) for each region(Dimension).

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Adding Glitches to Images using Python - GeeksforGeeks

08 Sep, 2021
One of the filters currently popular is to add random glitches to the images. These create a random effect that comes out to be a natural glitch. Usually, glitches are introduced by the corruption of frames of images or adding a layer over them. In this article, we will use the two different modules of Python to add glitches to the image.
This Python library adds random glitch effects to Images. It does this by distorting or Corrupting JPEG frames of some random bytes of Images, to not harm the File. Internally it uses Pillow library to perform tasks. 
To install this module type the below command in the terminal.
pip3 install glitchart
After installation, the glitchart library is imported and jpeg() or png() is invoked depending upon the extension of the image to be glitched. Just run the script and a new glitched file will be created with the name <filename>_glitch in the same path.
Function Used:
png(): Add glitches to png images.
Syntax:
png(photo, seed=random_val, min_amount=0, max_amount=10, inplace=False):
Parameters:
photo :  The required .png format photo to add glitch to.
seed : Random number, if we wish to add similar amount of glitch to next photo, can have same seed value.
min_amount : Minimum amount of glitch required, defaults to 0.
max_amount : Maximum amount of glitch required, defaults to 10.
inplace : boolean field, if True, changes original photo, not creating new one.
Example:
Input Image:
Python3
import glitchart glitchart.png('gfg.png')
 
 
Output:
 
 
Example 2: Controlling Glitch amount.
 
Python3
import glitchart glitchart.png('gfg.png', max_amount=3)
Output : 
Using glitch-this Module 
Using this, we can perform the task of glitching images using command line by supplying image path and levels and certain image and file management parameters.
To install this module type the below command in the terminal
pip install glitch-this
Command Line Parameters Explanation
glitch_this [-h] [–version] [-c] [-s] [-g] [-ig] [-f] [-o Outfile_path] Image_Path Glitch_Level
Parameters:Image_Path : The image path to perform glitch on.Glitch_Level : Level of Glitch to be applied, from 0.1 to 10.0 [inclusive].-h : Getting pull description-o Outfile_path :Explicitly supply full/relative path to output file.-g : Output image as gif.-ig :  Include if input is gif.-f : If output file has to be overwritten.-c : If color effect has to be added.-s. : If sideline effect has to be added.
Example: Controlling Glitch amount.
Example of Glitching using glitch-this
Output : 
Glitched Image Output
surinderdawra388
Image-Processing
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Flask â Static Files

A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application.
A special endpoint ‘static’ is used to generate URL for static files.
In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.
from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)
The HTML script of index.html is given below.
<html>
   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>
hello.js contains sayHello() function.
function sayHello() {
   alert("Hello World")
}

    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page