code-rag-bench/online-tutorials huggingface dataset:
Pygame - surface.blit() function - GeeksforGeeks

23 May, 2021
surface.blit() function draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not affect the blit.
Syntax : blit(source, dest, area=None, special_flags=0) -> Rect
Parameters:
Source – Draws a source Surface onto this Surface
dest – The draw can be positioned with the dest argument.
area -A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit
Python3
# import pygame moduleimport  pygame  pygame.init()  # widthwidth = 680  # heightheight = 480  #store he screen sizez = [width,height]  # store the colorwhite = (255, 255, 255)screen_display = pygame.display  # Set caption of screenscreen_display.set_caption('GEEKSFORGEEKS')  # setting the size of the windowsurface = screen_display.set_mode(z)  # set the image which to be displayed on screenpython = pygame.image.load('bg.jpg')  # set window truewindow = Truewhile window:    for event in pygame.event.get():        if event.type == pygame.QUIT:            window = False                          # display white on screen other than image    surface.fill(white)      # draw on image onto another    surface.blit(python,(50, 50))    screen_display.update()  pygame.quit()
Output:
Picked
Python-PyGame
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Node.js Automatic restart Node.js server with nodemon - GeeksforGeeks

14 Oct, 2021
We generally type following command for starting NodeJs server:
node server.js
In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again.
node server.js
It is a very hectic task for the development process.
Nodemon is a package for handling this restart process automatically when changes occur in the project file.
Installing nodemon: nodemon should be installed globally in our system:
Windows system: npm i nodemon -g
Linux system: sudo npm i nodemon -g 

Now, let’s check that nodemon has been installed properly to the system by typing the following command in terminal or command prompt:
nodemon -v
It will show the version of nodemon as shown in the below screenshot.
Starting node server with nodemon:
nodemon [Your node application]
Now, when we make changes to our nodejs application, the server automatically restarts by nodemon as shown in the below screenshot.
In this way with nodemon server automatically restarts.
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
pthread_self() in C with Example - GeeksforGeeks

28 Oct, 2019
Prerequisite : Multithreading in C
Syntax :- pthread_t pthread_self(void);The pthread_self() function returns the ID of the thread in which it is invoked.
// C program to demonstrate working of pthread_self()#include <stdio.h>#include <stdlib.h>#include <pthread.h>void* calls(void* ptr){    // using pthread_self() get current thread id    printf("In function \nthread id = %d\n", pthread_self());    pthread_exit(NULL);    return NULL;}  int main(){    pthread_t thread; // declare thread    pthread_create(&thread, NULL, calls, NULL);    printf("In main \nthread id = %d\n", thread);     pthread_join(thread, NULL);     return 0;}
Output:
In function
thread id = 1
In main
thread id = 1

This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shubham_singh
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Structures in C
Exception Handling in C++
Memory Layout of C Programs
StringBuffer reverse() Method in Java with Examples - GeeksforGeeks

13 Dec, 2021
The Java.lang.StringBuffer.reverse() is an inbuilt method which is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. Syntax : 
public StringBuffer reverse()
Parameters : The method does not take any parameter .Return Value : The method returns the StringBuffer after reversing the characters. Examples :  
Input: StringBuffer = GeeksforGeeks
Output = !skeegrofskeeG

Input: StringBuffer = Hello World
Output = !dlroW olleH
Below programs illustrate the java.lang.StringBuffer.reverse() method: Program 1:  
java
// Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test {     public static void main(String args[])    {        StringBuffer sbf = new StringBuffer("Geeksforgeeks!");        System.out.println("String buffer = " + sbf);                 // Here it reverses the string buffer        sbf.reverse();        System.out.println("String buffer after reversing = " + sbf);    }}
String buffer = Geeksforgeeks!
String buffer after reversing = !skeegrofskeeG
 
Program 2: 
java
// Java program to illustrate the// java.lang.StringBuffer.reverse()import java.lang.*; public class Test {     public static void main(String args[])    {        StringBuffer sbf = new StringBuffer("1 2 3 4 5 6 7 8 9 10");        System.out.println("String buffer  = " + sbf);         // Here it reverses the string buffer        sbf.reverse();        System.out.println("String buffer after reversing = " + sbf);    }}
String buffer  = 1 2 3 4 5 6 7 8 9 10
String buffer after reversing = 01 9 8 7 6 5 4 3 2 1
 
akshaysingh98088
Java-Functions
Java-lang package
java-StringBuffer
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Node.js os.totalmem() Method - GeeksforGeeks

13 Oct, 2021
The os.totalmem() method is an inbuilt application programming interface of the os module which is used to get amount of total system memory in bytes.
Syntax:
os.totalmem()
Parameters: This method does not accept any parameters.
Return Value: This method returns an integer value that specifies the amount of total system memory in bytes.
Below examples illustrate the use of os.totalmem() method in Node.js:
Example 1:
// Node.js program to demonstrate the    // os.totalmem() method      // Import the os moduleconst os = require('os');  // Printing os.totalmem() method valueconsole.log(os.totalmem());
Output:
8502722560
Example 2:
// Node.js program to demonstrate the    // os.totalmem() method      // Import the os moduleconst os = require('os');  // Convert total memory to kb, mb and gbvar total_memory = os.totalmem();var total_mem_in_kb = total_memory/1024;var total_mem_in_mb = total_mem_in_kb/1024;var total_mem_in_gb = total_mem_in_mb/1024;   total_mem_in_kb = Math.floor(total_mem_in_kb);total_mem_in_mb = Math.floor(total_mem_in_mb);total_mem_in_gb = Math.floor(total_mem_in_gb);   total_mem_in_mb = total_mem_in_mb%1024;total_mem_in_kb = total_mem_in_kb%1024;total_memory = total_memory%1024;  // Display memory sizeconsole.log("Total memory: " + total_mem_in_gb + "GB "          + total_mem_in_mb + "MB " + total_mem_in_kb          + "KB and " + total_memory + "Bytes");
Output:
Total memory: 7GB 940MB 848KB and 0Bytes

Example 3:
// Node.js program to demonstrate the    // os.totalmem() method      // Import the os moduleconst os = require('os');  // Printing free memory out of total memoryconsole.log("Free Memory " + String(os.freemem())    + " Bytes out of " + String(os.totalmem()) + " Bytes");
Output:
Free Memory 4161896448 Bytes out of 8502722560 Bytes

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_totalmem
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
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?
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
numpy.power() in Python - GeeksforGeeks

29 Nov, 2018
numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :Array element from first array is raised to the power of element from second element(all happens element-wise). Both arr1 and arr2 must have same shape and each element in arr1 must be raised to corresponding +ve value from arr2; otherwise it will raise a ValueError.Parameters :
arr1     : [array_like]Input array or object which works as base.
arr2     : [array_like]Input array or object which works as exponent. 
out      : [ndarray, optional]Output array with same dimensions as Input array, 
           placed with result.
**kwargs : Allows you to pass keyword variable length of argument to a function. 
           It is used when we want to handle named argument in a function.
where    : [array_like, optional]True value means to calculate the universal 
           functions(ufunc) at that position, False value means to leave the 
           value in the output alone.

Return :
An array with elements of arr1 raised to exponents in arr2

 Code 1 : arr1 raised to arr2
# Python program explaining# power() functionimport numpy as np  # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, 3, 4, 5, 6]print ("arr1         : ", arr1)print ("arr1         : ", arr2)  # output_arrayout = np.power(arr1, arr2)print ("\nOutput array : ", out)
Output :
arr1         :  [2, 2, 2, 2, 2]
arr2         :  [2, 3, 4, 5, 6]

Output array :  [ 4  8 16 32 64]

 Code 2 : elements of arr1 raised to exponent 2
# Python program explaining# power() functionimport numpy as np  # input_arrayarr1 = np.arange(8)exponent = 2print ("arr1         : ", arr1)  # output_arrayout = np.power(arr1, exponent)print ("\nOutput array : ", out)
Output :
arr1         :  [0 1 2 3 4 5 6 7]

Output array :  [ 0  1  4  9 16 25 36 49]
 Code 3 : Error if arr2 has -ve elements
# Python program explaining# power() functionimport numpy as np  # input_arrayarr1 = [2, 2, 2, 2, 2]arr2 = [2, -3, 4, -5, 6]print ("arr1         : ", arr1)print ("arr2         : ", arr2)  # output_arrayout = np.power(arr1, arr2)print ("\nOutput array : ", out)
Output :
arr1         :  [2, 2, 2, 2, 2]
arr2         :  [2, -3, 4, -5, 6]
ValueError: Integers to negative integer powers are not allowed.
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.power.html#numpy.power.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to check whether the elements of a given NumPy array is non-zero? - GeeksforGeeks

29 Aug, 2020
In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero.
Syntax: numpy.any()
Parameter :An array.
Return :It return boolean value(True/False).
Example 1:
Python
import numpy as np    # Original arrayarray = np.array([4,6,0,0,0,4,89])print(x)  # Test whether any of the elements# of a given array is non-zeroprint(np.any(array))
Output:
True

Example 2:
Python
import numpy as np  # Original arrayarray = np.array([0,0,0,0,0,0])print(x)  # Test whether any of the elements# of a given array is non-zeroprint(np.any(array))
Output:
False

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | Scipy stats.halfgennorm.isf() method - GeeksforGeeks

06 Feb, 2020
With the help of stats.halfgennorm.isf() method, we can get the value of inverse survival function which is inverse(1 – cdf) by using stats.halfgennorm.isf() method.
Syntax : stats.halfgennorm.isf(x, beta)Return : Return the value of inverse survival function.
Example #1 :In this example we can see that by using stats.halfgennorm.isf() method, we are able to get the value of inverse survival function by using this method.
# import halfgennormfrom scipy.stats import halfgennormbeta = 1  # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.3, beta)  print(gfg)
Output :
1.2039728043259357
Example #2 :
# import halfgennormfrom scipy.stats import halfgennormbeta = 4  # Using stats.halfgennorm.isf() methodgfg = halfgennorm.isf(0.9, beta)  print(gfg)
Output :
0.09064147135377666
Python scipy-stats-functions
Python-scipy
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Set Difference in list of dictionaries - GeeksforGeeks

26 Feb, 2019
The difference of two lists have been discussed many a times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehensionThe naive method to iterate both the list and extract the difference can be shortened to the method in which we shorten the code and increase the readability using list comprehension.
# Python3 code to demonstrate # set difference in dictionary list # using list comprehension  # initializing list test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}]  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " +  str(test_list2))  # using list comprehension# set difference in dictionary list res = [i for i in test_list1 if i not in test_list2] \      + [j for j in test_list2 if j not in test_list1]  # printing result print ("The set difference of list is : " +  str(res))
Output :
The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}]
 Method #2 : Using itertools.filterfalse()This is a different way in which this particular task can be performed using the in built python function. The filterfalse method filters the not present element of one list with respect to other.
# Python3 code to demonstrate # set difference in dictionary list # using itertools.filterfalse()import itertools  # initializing list test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}]  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " +  str(test_list2))  # using itertools.filterfalse()# set difference in dictionary list res = list(itertools.filterfalse(lambda i: i in test_list1, test_list2)) \    + list(itertools.filterfalse(lambda j: j in test_list2, test_list1))  # printing result print ("The set difference of list is : " +  str(res))
Output :
The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]The set difference of list is : [{‘Shambhavi’: 2019}]
Python dictionary-programs
Python list-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?
Python | Pandas dataframe.sem() - GeeksforGeeks

23 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.sem() function return unbiased standard error of the mean over requested axis. The standard error (SE) of a statistic (usually an estimate of a parameter) is the standard deviation of its sampling distribution[1] or an estimate of that standard deviation. If the parameter or the statistic is the mean, it is called the standard error of the mean (SEM).
Syntax : DataFrame.sem(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesddof : Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N represents the number of elements.numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series
Return : sem : Series or DataFrame (if level specified)
For link to the CSV file used in the code, click here
Example #1: Use sem() function to find the standard error of the mean of the given dataframe over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
Let’s use the dataframe.sem() function to find the standard error of the mean over the index axis.
# find standard error of the mean of all the columnsdf.sem(axis = 0)
Output :Notice, all the non-numeric columns and values are automatically not included in the calculation of the dataframe. We did not have to specifically input the numeric columns for the calculation of the standard error of the mean. Example #2: Use sem() function to find the standard error of the mean over the column axis. Also do not skip the NaN values in the calculation of the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Calculate the standard error of # the mean of all the rows in dataframedf.sem(axis = 1, skipna = False)
Output :When we include the NaN values then it will cause that particular row or column to be NaN
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How can I test if a string starts with a capital letter using Python?

To be precise, above string four words starting with uppercase character. This, Delhi, City and India.
Two string functions should be used for this purpose. Assuming that words in the string are separated by single space character, split() function gives list of words.
Secondly to check if first character of each word is uppercase, use isupper() function.
Following code lists words starting with capital letters.
s1="This is not true that Delhi is the hottest or coldest City in India"
for word in s1.split():
    if word[0].isupper():
        print (word)
The output is:
This
Delhi
City
India
Argument Index in Java

Argument indices allow programmers to reorder the output. Let us see an example.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      System.out.printf("Before reordering = %s %s %s %s %s %s\n", "one", "two", "three", "four", "five", "six" );
      System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s\n","one", "two", "three", "four", "five", "six" );
      System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300);
      System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);
   }
}
Before reordering = one two three four five six
After reordering = six five four three two one
Before reordering = 100 200 300
After reordering = 200 300 100
Above, we have reordered the output completely. Before ordering, we displayed normally.
System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300);
But, we changed the order and displayed it as −
System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);
How to find an element using the “CSS Selector” in Selenium?

We can find an element using the css locator with Selenium webdriver. To identify the element with css, the expression should be tagname[attribute='value'].
We can also specifically use the id attribute to create a css expression.
With id, the format of a css expression should be tagname#<id>. For example,input#txt [here input is the tagname and the txt is the value of the id attribute].
With class, the format of css expression should be tagname.<class> . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute].
If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n).
In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child.
For attributes whose values are dynamically changing, we can use ^= to locate an element whose value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa].
For attributes whose values are dynamically changing, we can use =tolocateanelementwhosevalueendswithaparticulartext.Forexample,input[class='txt'] [here input is the tagname and the value of the class attribute ends with txt].
For attributes whose values are dynamically changing, we can use *= to locate an element whose value contains a specific sub-text. For example, input[name*='nam'] [here input is the tagname and the value of the name attribute contains the sub-text nam].
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorCss{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      //identify element with css
      WebElement n = driver.
      findElement(By.cssSelector("input[id='session_key']"));
      n.sendKeys("Java");
      String str = n.getAttribute("value");
      System.out.println("Attribute value: " + str);
      driver.quit();
   }
}
How to plot CSV data using Matplotlib and Pandas in Python?

To plot CSV data using Matplotlib and Pandas in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a list of headers of the .CSV file.
Read the CSV file with headers.
Set the index and plot the dataframe.
To display the figure, use show() method.
import pandas as pd
import matplotlib.pyplot as plt

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

headers = ['Name', 'Age', 'Marks']

df = pd.read_csv('student.csv', names=headers)

df.set_index('Name').plot()

plt.show()
C++ Program to Find Inverse of a Graph Matrix

This is a C++ program to Find Inverse of a Graph Matrix. Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Inverse of a matrix can find out in many ways. Here we find out inverse of a graph matrix using adjoint matrix and its determinant. Steps involved in the Example
Begin
   function INV() to get the inverse of the matrix:
   Call function DET().
   Call function ADJ().
   Find the inverse of the matrix using the formula;
   Inverse(matrix) = ADJ(matrix) / DET(matrix)
End.
#include<bits/stdc++.h>
using namespace std;
#define N 5
void getCfactor(int M[N][N], int t[N][N], int p, int q, int n) {
   int i = 0, j = 0;
   for (int r= 0; r< n; r++) {
      for (int c = 0; c< n; c++) //Copy only those elements which are not in given row r and column c: {
         if (r != p && c != q) { t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index
            if (j == n - 1) {
               j = 0; i++;
            }
         }
      }
   }
}
int DET(int M[N][N], int n) //to find determinant {
   int D = 0;
   if (n == 1)
      return M[0][0];
   int t[N][N]; //store cofactors
   int s = 1; //store sign multiplier //
   To Iterate each element of first row
   for (int f = 0; f < n; f++) {
      //For Getting Cofactor of M[0][f] do getCfactor(M, t, 0, f, n); D += s * M[0][f] * DET(t, n - 1);
      s = -s;
   }
   return D;
}
void ADJ(int M[N][N],int adj[N][N])
//to find adjoint matrix {
   if (N == 1) {
      adj[0][0] = 1; return;
   }
   int s = 1,
   t[N][N];
   for (int i=0; i<N; i++) {
      for (int j=0; j<N; j++) {
         //To get cofactor of M[i][j]
         getCfactor(M, t, i, j, N);
         s = ((i+j)%2==0)? 1: -1; //sign of adj[j][i] positive if sum of row and column indexes is even.
         adj[j][i] = (s)*(DET(t, N-1)); //Interchange rows and columns to get the transpose of the cofactor matrix
      }
   }
}
bool INV(int M[N][N], float inv[N][N]) {
   int det = DET(M, N);
   if (det == 0) {
      cout << "can't find its inverse";
      return false;
   }
   int adj[N][N]; ADJ(M, adj);
   for (int i=0; i<N; i++) for (int j=0; j<N; j++) inv[i][j] = adj[i][j]/float(det);
   return true;
}
template<class T> void print(T A[N][N]) //print the matrix. {
   for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << " "; cout << endl; }
}
int main() {
   int M[N][N] = {
      {1, 2, 3, 4,-2}, {-5, 6, 7, 8, 4}, {9, 10, -11, 12, 1}, {13, -14, -15, 0, 9}, {20 , -26 , 16 , -17 , 25}
   };
   float inv[N][N];
   cout << "Input matrix is :\n"; print(M);
   cout << "\nThe Inverse is :\n"; if (INV(M, inv)) print(inv);
   return 0;
}
Input matrix is :
1 2 3 4 -2
-5 6 7 8 4 
9 10 -11 12 1 
13 -14 -15 0 9 
20 -26 16 -17 25
The Inverse is : 
0.0811847 -0.0643008 0.0493814 -0.0247026 0.0237006 
-0.126819 -0.0161738 0.0745377 -0.0713976 0.0151639 
0.0933664 0.0028245 -0.0111876 -0.0220437 0.0154006 
0.143624 0.0582573 -0.0282371 0.0579023 -0.0175466 
-0.15893 0.0724272 0.0259728 -0.00100988 0.0150219
zlib.crc32() in python

23 Mar, 2020
With the help of zlib.crc32() method, we can compute the checksum for crc32 (Cyclic Redundancy Check) to a particular data. It will give 32-bit integer value as a result by using zlib.crc32() method.
Syntax : zlib.crc32(s)Return : Return the unsigned 32-bit checksum integer.
Example #1 :In this example we can see that by using zlib.crc32() method, we are able to compute the unsigned 32-bit checksum for given data by using this method.
# import zlib and crc32import zlib  s = b'I love python, Hello world'# using zlib.crc32() methodt = zlib.crc32(s)  print(t)
Output :
2185029202
Example #2 :
# import zlib and crc32import zlib  s = b'Hello GeeksForGeeks'# using zlib.crc32() methodt = zlib.crc32(s)  print(t)
Output :
3165518624
python-zlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Batch Script - CMD

This batch command invokes another instance of command prompt.
cmd

@echo off 
cmd
Another instance of command prompt will be invoked.
Solving multiplexer circuit

14 May, 2020
The procedure for solving and finding the output function of the given multiplexer is quite simple. Firstly we will discuss the procedure and then illustrate it with examples.
Procedure:
Firstly truth table is constructed for the given multiplexer.
Select lines in multiplexer are considered as input for the truth table.
Output in truth table can be four forms i.e. ( 0, 1, Q, Q’).
Now with the help of truth table we find the extended expression.
Then the expression is minimized using boolean algebraic rules.
Final function can be either in expression form or in SOP or POS form.
Example-1:Given MUX is following,
Explanation :
Step-1: First draw the truth table. For the truth table, select lines A and B are the input.According to the circuit,I0 = C' (hence first row of truth table will be C')
I1 = C'
I2 = C
I3 = C I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively.
I0 = C' (hence first row of truth table will be C')
I1 = C'
I2 = C
I3 = C 
I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively.
Step-2: Now we will find the expression of Y:Y = A'B'C' + A'BC' + AB'C + ABC
  = A'C'(B' + B) + AC(B' + B)
  = A'C' + AC

Y = A'B'C' + A'BC' + AB'C + ABC
  = A'C'(B' + B) + AC(B' + B)
  = A'C' + AC

Example-2:Given MUX,
Explanation :
Step-1: Truth table is following. For the truth table select lines B and C are input.According to the circuit,I0 = A (hence first row of truth table will be A)
I1 = A'
I2 = 1
I3 = 0 I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively.
I0 = A (hence first row of truth table will be A)
I1 = A'
I2 = 1
I3 = 0 
I0, I1, I2, I3 are considered as output of 1st, 2nd, 3rd and 4th row of truth table respectively.
Step-2: Now we will find the output:f(A, B, C) = AB'C' + A'B'C + BC'.1
         = AB'C' + A'B'C + BC'(A + A')
         = AB'C' + A'B'C + ABC' + A'BC'
         =  100     001    110     010
         = m(1, 2, 4, 6)
f(A, B, C) = AB'C' + A'B'C + BC'.1
         = AB'C' + A'B'C + BC'(A + A')
         = AB'C' + A'B'C + ABC' + A'BC'
         =  100     001    110     010
         = m(1, 2, 4, 6)
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to memory and memory units
Analog to Digital Conversion
Latches in Digital Logic
Digital to Analog Conversion
Half Subtractor in Digital Logic
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Python | Pandas Series.nlargest()

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.nlargest() function return the n largest element from the underlying data in the given series object.
Syntax: Series.nlargest(n=5, keep=’first’)
Parameter :n : Return this many descending sorted values.keep : {‘first’, ‘last’, ‘all’}, default ‘first’
Returns : Series
Example #1: Use Series.nlargest() function to return the first n largest element from the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.nlargest() function to find the first 2 largest value in the given series object.
# return the first 2 of the largest# elementresult = sr.nlargest(n = 2)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.nlargest() function has successfully returned the first 2 largest value in the given series object. Example #2: Use Series.nlargest() function to return the first n largest element from the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])  # Print the seriesprint(sr)
Output :
Now we will use Series.nlargest() function to find the first 5 largest value in the given series object.
# return the first 5 of the largest# elementresult = sr.nlargest(n = 5)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.nlargest() function has successfully returned the first 5 largest value in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Send multiple data with ajax in PHP

Data can be sent through JSON or via normal POST. Following is an example showing data sent through JSON −
var value_1 = 1;
var value_2 = 2;
var value_3 = 3;
$.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   url: "your_url_goes_here",
   data: { data_1: value_1, data_2: value_2, data_3: value_3 },
   success: function (result) {
      // perform operations here
   }
});
With normal post, the below code can be used −
$.ajax({
   type: "POST",
   url: $('form').attr("action"),
   data: $('#form0').serialize(),
   success: function (result) {
      // perform operations here
   }
});
An alternate to the above code has been demonstrated below −
data:'id='+ID & 'user_id=' + USERID,
with:
data: {id:ID, user_id:USERID}
so your code will look like this :
$(document).ready(function(){
   $(document).on('click','.show_more',function(){
      var ID = 10;
      var USERID =1;
      $('.show_more').hide();
      $('.loding').show();
      $.ajax({
         type:'POST',
         url:'/ajaxload.php',
         data: {id:ID, user_id:USERID},
         success:function(html){
            $('#show_more_main'+ID).remove();
            $('.post_list').append(html);
         }
      });
   });
});
What does enumerable property mean in JavaScript?

04 Jun, 2020
An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for...in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default.
Example 1:
<script>// Creating a student objectconst student = {    registration: '12342',    name: 'Sandeep',    age: 27,    marks: 98};  // prints all the keys in student objectfor (const key in student) {    console.log(key);}</script>
Output:
registration
name
age
marks

Example 2: Since all the properties are initialized by property initializer, they all have enumerable set to true by default. To explicitly change the internal enumerable attribute of a property, the Object.defineProperty() method is used. Also, to check whether a property is enumerable or not, we use the function propertyIsEnumerable(). It returns true if the property is enumerable or false otherwise.
<script>// Creating a student objectconst student = {    registration: '12342',    name: 'Sandeep',    age: 27,};  // This sets the enumerable attribute// of marks property to false   Object.defineProperty(student, 'marks', {    value: 98,    configurable: true,    writable: false,    enumerable: false,});  // To print whether enumerable or notconsole.log(student.propertyIsEnumerable('registration')); console.log(student.propertyIsEnumerable('name'));console.log(student.propertyIsEnumerable('age'));console.log(student.propertyIsEnumerable('marks'));</script>
Output:
true
true
true
false

Note: Properties that are created using the defineProperty() method have enumerable flag set to false. When the same above code is run using a for loop, the “marks” property is not visible.
// This will not print the property 
// Who's enumerable property is set to false

for (const key in student){
    console.log(key)
}

Output:
registration
name
age

javascript-basics
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Node.js | fs.writeFileSync() Method
Remove elements from a JavaScript Array
How do you run JavaScript script through the Terminal?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to rearrange columns of a 2D NumPy array using given index positions?

05 Sep, 2020
In this article, we will learn how to rearrange columns of a given numpy array using given index positions. Here the columns are rearranged with the given indexes. For this, we can simply store the columns values in lists and arrange these according to the given index list but this approach is very costly. So, using by using the concept of numpy array this can be easily done in minimum time.
Arr = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] and i = [2, 4, 0, 3, 1]then output is [[3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2]].
Here, i[0] = 2 i.e; 3rd column so output = [[3],[3],[3],][3],[3]].     i[1] = 4 i.e; 5th column so output = [[3,5],[3,5],[3,5],][3,5],[3,5]].     i[2] = 0 i.e; 1st column so output = [[3,5,1],[3,5,1],[3,5,1],][3,5,1],[3,5,1]].     i[3] = 3 i.e; 4th column so output = [[3,5,1,4],[3,5,1,4],[3,5,1,4],][3,5,1,4],[3,5,1,4]].     i[4] = 1 i.e; 2nd column so output = [[3,5,1,4,2],[3,5,1,4,2],[3,5,1,4,2],][3,5,1,4,2],[3,5,1,4,2]].
Below is the implementation with an example :
Python3
# importing packageimport numpy  # create a numpy arrayarr = numpy.array([[1,2,3,4,5],                   [1,2,3,4,5],                   [1,2,3,4,5],                   [1,2,3,4,5],                   [1,2,3,4,5]                   ])  # view arrayprint(arr)  # declare index listi = [2,4,0,3,1]  # create outputoutput = arr[:,i]  # view outputprint(output)
Output :
[[1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]]
[[3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]
 [3 5 1 4 2]]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Array and Pointers in C.

Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.r Benefit of using pointer for array is two folds, first, we store the address of dynamically allocated array to the pointer and second, to pass the array to a function. Following are the differences in using array and using pointer to array.
sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int.
sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int.
assignment array variable cannot be assigned address of another variable but pointer can take it.
assignment array variable cannot be assigned address of another variable but pointer can take it.
first value first indexed value is same as value of pointer. For example, array[0] == *p.
first value first indexed value is same as value of pointer. For example, array[0] == *p.
iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2)
iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2)
 Live Demo
#include <stdio.h>
void printElement(char* q, int index){
   printf("Element at index(%d) is: %c\n", index, *(q+index));
}
int main() {
   char arr[] = {'A', 'B', 'C'};
   char* p = arr;
   printf("Size of arr[]: %d\n", sizeof(arr));
   printf("Size of p: %d\n", sizeof(p));
   printf("First element using arr is: %c\n", arr[0]);
   printf("First element using p is: %c\n", *p);
   printf("Second element using arr is: %c\n", arr[1]);
   printf("Second element using p is: %c\n", *(p+1));
   printElement(p, 2);
   return 0;
}
Size of arr[]: 3
Size of p: 8
First element using arr is: A
First element using p is: A
Second element using arr is: B
Second element using p is: B
Element at index(2) is: C
Create and save animated GIF with Python – Pillow

24 Feb, 2021
Prerequisites: pillow
In this article, we are going to use a pillow library to create and save gifs.
GIFs: The Graphics Interchange Format(gif) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite on 15 June 1987.
A GIF file normally stores a single image, but the format allows multiple images to be stored in one file. The format also has parameters that can be used to sequence the images to display each image for a short time then replace it with the next one. In simple words, GIF is a moving image.
Pillow: Pillow is used for image processing in python. Pillow was developed on top of PIL(python image library). PIL was not supported in python 3, so we use a pillow. 
This module is not preloaded with Python. So to install it execute the following command in the command-line:
pip install pillow
Let’s create a gif in step wise:
Step 1: First we import our requirements for PIL module.
Python3
from PIL import Image, ImageDraw
Step 2: Create a list after we enter the values of the circle. (0,255,0) it is the color code of green and (255,0,0) is the color code of red.
Python3
images = []width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8
Step 3: For loop was used to create an animation image.2nd line of code used to set values of the square, that square contains red color and it’s edge size is 200.3rd line used to create square image .4th line used to draw a circle in that square image, that circle color is green.
Python3
for i in range(0, max_radius, step):    im = Image.new('RGB', (width, width), color_2)    draw = ImageDraw.Draw(im)    draw.ellipse((center - i, center - i,                  center + i, center + i),                  fill=color_1)    images.append(im)
Step 4: Save the gif image.
Python3
images[0].save('pillow_imagedraw.gif',               save_all = True, append_images = images[1:],               optimize = False, duration = 10)
Below is the full implementation:
Python3
from PIL import Image, ImageDraw  images = []  width = 200center = width // 2color_1 = (0,255, 0)color_2 = (255, 0, 0)max_radius = int(center * 1.5)step = 8  for i in range(0, max_radius, step):    im = Image.new('RGB', (width, width), color_2)    draw = ImageDraw.Draw(im)    draw.ellipse((center - i, center - i,                  center + i, center + i),                 fill = color_1)    images.append(im)  images[0].save('pillow_imagedraw.gif',               save_all = True, append_images = images[1:],                optimize = False, duration = 10)
  Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create multiple subplots in Matplotlib in Python?

16 Dec, 2020
To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.
By default, it returns a figure with a single plot. For each axes object i.e plot we can set title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
Let’s see how this works  
When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots.We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding
When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots.
We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding
Example 1: 1-D array of subplots
Python3
# importing libraryimport matplotlib.pyplot as plt # Some data to displayx = [1, 2, 3]y = [0, 1, 0]z = [1, 0, 1] # Creating 2 subplotsfig, ax = plt.subplots(2) # Accessing each axes object to plot the data through returned arrayax[0].plot(x, y)ax[1].plot(x, z)
Output : 
subplots_fig1
Example2: Stacking in two directions returns a 2D array of axes objects.
Python3
# importing libraryimport matplotlib.pyplot as pltimport numpy as np # Data for plottingx = np.arange(0.0, 2.0, 0.01)y = 1 + np.sin(2 * np.pi * x) # Creating 6 subplots and unpacking the output array immediatelyfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)ax1.plot(x, y, color="orange")ax2.plot(x, y, color="green")ax3.plot(x, y, color="blue")ax4.plot(x, y, color="magenta")ax5.plot(x, y, color="black")ax6.plot(x, y, color="red")
Output : 
Subplots_fig2
tejalkadam18m
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.