code-rag-bench/online-tutorials huggingface dataset:
How to compare two dictionaries in C#?

To compare two dictionaries, firstly set the two dictionaries −
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);

// Dictionary One elements
Console.WriteLine("Dictionary One elements: "+d.Count);
IDictionary<int, int> d2 = new Dictionary<int, int>();
d2.Add(1,97);
d2.Add(2,89);
d2.Add(3,77);
d2.Add(4,88);

// Dictionary Two elements
Console.WriteLine("Dictionary Two elements: "+d2.Count);
Now let us compare them −
bool equal = false;
if (d.Count == d2.Count) { // Require equal count.
   equal = true;
   foreach (var pair in d) {
      int value;
      if (d2.TryGetValue(pair.Key, out value)) {
         if (value != pair.Value) {
            equal = false;
            break;
         }
      } else {
         equal = false;
         break;
      }
   }
}
The above compares two dictionaries. Now print console and the result would be True. That would mean both the dictionaries have the same values.
JavaScript Insert space after every two letters in string?

For this, use replace() along with regular expressions.
Following is the code −
var values = "JavaScriptTutorial";
var result = values.replace(/.{1,2}(?=(.{2})+$)/g, '$& ');
console.log("The actual result is=");
console.log(values);
console.log("After inserting space at nth position=")
console.log(result);
To run the above program, you need to use the below command −
node fileName.js.
Here, my file name is demo326.js
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo326.js
The actual result is=
JavaScriptTutorial
After inserting space at nth position=
Ja va Sc ri pt Tu to ri al
Perfect Squares in C++

Suppose we have a positive integer n, find the least number of perfect square numbers whose sum is n. So if the number is 13, then the output is 2, as the numbers are 13 = 9 + 4
To solve this, we will follow these steps −
create one table for dynamic programming, of length n + 1, and fill it with infinity
dp[0] := 0
for i := 1, when i*i <= nx = i * ifor j := x to ndp[j] := minimum of dp[j] and 1 + dp[j – x]
x = i * i
for j := x to ndp[j] := minimum of dp[j] and 1 + dp[j – x]
dp[j] := minimum of dp[j] and 1 + dp[j – x]
return dp[n]
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define INF 1e9
class Solution {
   public:
   int numSquares(int n) {
      vector < int > dp(n+1,INF);
      dp[0] = 0;
      for(int i =1;i*i<=n;i++){
         int x = i*i;
         for(int j = x;j<=n;j++){
            dp[j] = min(dp[j],1+dp[j-x]);
         }
      }
      return dp[n];
   }
};
main(){
   Solution ob;
   cout << (ob.numSquares(147));
}
147
3
Minimum Cost Tree From Leaf Values in Python

Suppose we have an array arr of positive integers, consider all binary trees such that −
Each node has either 0 or 2 children;
The values of arr array correspond to the values of each leaf in an inorder traversal of the tree.
The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.
Among all possible binary trees considered, we have to find the smallest possible sum of the values of each non-leaf node. So if the input arr is [6,2,4], then the output will be 32, as there can be possibly two trees −
To solve this, we will follow these steps −
make a map called memo
Define a method dp(), this will take i and j as parameters. This will work as follows −
if j <= i, then return 0
if (i, j) in the memo, then return memo[(i, j)]
res := infinity
for k in range i to j – 1res := min of res, dp(i, k) + dp(k + 1, j) + (max of subarray of arr from index i to k + 1) * max of subarray of arr from k + 1 to j + 1
res := min of res, dp(i, k) + dp(k + 1, j) + (max of subarray of arr from index i to k + 1) * max of subarray of arr from k + 1 to j + 1
memo[(i, j)] := res
return memo[(i, j)]
The main method will call this dp() method as − call dp(0, length of arr - 1)
Let us see the following implementation to get better understanding −
class Solution(object):
   def mctFromLeafValues(self, arr):
      """
      :type arr: List[int]
      :rtype: int
      """
      self. memo = {}
      def dp(i,j):
         if j<=i:
            return 0
         if (i,j) in self.memo:
            return self.memo[(i,j)]
         res = float('inf')
         for k in range(i,j):
            res = min(res,dp(i,k) + dp(k+1,j) + (max(arr[i:k+1])*max(arr[k+1:j+1])))
         self.memo[(i,j)]=res
         return self.memo[(i,j)]
      return dp(0,len(arr)-1)
[6,2,4]
32
Output of C Programs | Set 13 - GeeksforGeeks

05 Jul, 2018
Difficulty Level: Rookie
Question 1Predict the output of below program.
int main(){  char arr[] = "geeksforgeeks";  printf("%d", sizeof(arr));  getchar();  return 0;}
Output: 14The string “geeksforgeeks” has 13 characters, but the size is 14 because compiler includes a single ‘\0’ (string terminator) when char array size is not explicitly mentioned.
Question 2In below program, what would you put in place of “?” to print “geeks”. Obviously, something other than “geeks”.
int main(){  char arr[] = "geeksforgeeks";  printf("%s", ?);  getchar();  return 0;}
Answer: (arr+8)The printf statement prints everything starting from arr+8 until it finds ‘\0’
Question 3Predict the output of below program.
int main(){  int x, y = 5, z = 5;  x = y==z;  printf("%d", x);      getchar();  return 0;}
The crux of the question lies in the statement x = y==z. The operator == is executed before = because precedence of comparison operators (<=, >= and ==) is higher than assignment operator =.The result of a comparison operator is either 0 or 1 based on the comparison result. Since y is equal to z, value of the expression y == z becomes 1 and the value is assigned to x via the assignment operator.
Question 4Predict the output of below program.
int main(){  printf(" \"GEEKS %% FOR %% GEEKS\"");  getchar();  return 0;}
Output: “GEEKS % FOR % GEEKS”
Backslash (\) works as escape character for double quote (“). For explanation of %%, please see this.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of Java Program | Set 3
Different ways to copy a string in C/C++
Output of C++ programs | Set 34 (File Handling)
Output of Java program | Set 28
Runtime Errors
Output of Java program | Set 5
Output of Java Programs | Set 12
numpy.ma.mask_cols() function | Python - GeeksforGeeks

22 Apr, 2020
In thisnumpy.ma.mask_cols() function, mask columns of a 2D array that contain masked values. This function is a shortcut to mask_rowcols with axis equal to 1.
Syntax : numpy.ma.mask_cols(arr, axis = None)
Parameters :arr : [array_like, MaskedArray] The array to mask.axis : [int, optional] Axis along which to perform the operation. Default is None.
Return : [MaskedArray] A modified version of the input array.
Code #1 :
# Python program explaining# numpy.ma.mask_cols() function  # importing numpy as geek  # and numpy.ma module as ma import numpy as geek import numpy.ma as ma   arr = geek.zeros((3, 3), dtype = int)arr[1, 1] = 1   arr = ma.masked_equal(arr, 1)  gfg = ma.mask_cols(arr)  print (gfg)
Output :
[[0 -- 0]
 [0 -- 0]
 [0 -- 0]]

 Code #2 :
# Python program explaining# numpy.ma.mask_cols() function  # importing numpy as geek  # and numpy.ma module as ma import numpy as geek import numpy.ma as ma   arr = geek.zeros((4, 4), dtype = int)arr[2, 2] = 1   arr = ma.masked_equal(arr, 1)  gfg = ma.mask_cols(arr)  print (gfg)
Output :
[[0 0 -- 0]
 [0 0 -- 0]
 [0 0 -- 0]
 [0 0 -- 0]]

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

26 Jul, 2021
In order to print all the heading tags using BeautifulSoup, we use the find_all() method. The find_all method is one of the most common methods in BeautifulSoup. It looks through a tag and retrieves all the occurrences of that tag.
Syntax: find_all(name, attrs, recursive, string, limit, **kwargs)
An HTML document consists of the following tags – h1, h2, h3, h4, h5, and h6. The most commonly used HTML tags in webpages are h1, h2 and h3, and to find these we pass a list of tags as an argument to the find_all() method.
Steps:
import the libraries requests and BeautifulSouppass a URL into a variableuse the request library to fetch the URLcreate a BeautifulSoup objectcreate a list of heading tags ()iterate over all the heading tags using find_all() method
import the libraries requests and BeautifulSoup
pass a URL into a variable
use the request library to fetch the URL
create a BeautifulSoup object
create a list of heading tags ()
iterate over all the heading tags using find_all() method
Example:
Python3
# Python program to print all heading tagsimport requestsfrom bs4 import BeautifulSoup # scraping a wikipedia articleurl_link = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'request = requests.get(url_link) Soup = BeautifulSoup(request.text, 'lxml') # creating a list of all common heading tagsheading_tags = ["h1", "h2", "h3"]for tags in Soup.find_all(heading_tags):    print(tags.name + ' -> ' + tags.text.strip())
Output: 
h2 -> Related Articles
h2 -> Python3
h2 -> Python3
h2 -> Python3
h2 -> Python3
h2 -> Python3
h2 -> Python3
surindertarika1234
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
find_elements_by_class_name() driver method - Selenium Python - GeeksforGeeks

23 Nov, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_class_name() is discussed in this article. This method returns a list with the type of elements specified. To grab a single first element, checkout – find_element_by_class_name() driver method – Selenium PythonSyntax –  
driver.find_elements_by_class_name("class-name")
Example – For instance, consider this page source:  
HTML
Now after you have created a driver, you can grab an element using –  
login_form = driver.find_elements_by_class_name('form-control')
Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its class “GSC-input” Create a file called run.py to demonstrate find_elements_by_class_name method –  
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementselements = driver.find_elements_by_class_name("gsc-input") # print complete elements listprint(element)
Now run using –  
Python run.py
First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output –  
Terminal Output –  
 
kumaripunam984122
Python-selenium
selenium
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Lodash _.some() Method - GeeksforGeeks

27 Sep, 2021
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers, etc. 
The _.some() method is used to check if predicate return true for any element of collection. Iteration is stopped once predicate return true. 
Syntax: 
_.some(collection, predicate)
Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
predicate: This parameter holds the function invoked per iteration and is invoked with three arguments (value, index|key, collection).
Return Value: This method is used to return true if any element passes the predicate check, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. 
Javascript
// Requiring the lodash libraryconst _ = require("lodash");      // Original array and use of _.some() methodvar gfg = _.some([null, 0, 'yes', false], Boolean); // Printing the outputconsole.log(gfg);
 Output:  
true
Example 2: 
Javascript
// Requiring the lodash libraryconst _ = require("lodash");      // Original arrayvar object = [  { 'obj': 'moto', 'active': true },  { 'obj': 'lenovo',   'active': false } ];  // Use of _.some() method// The `_.matches` iteratee shorthand let gfg = _.some(object, { 'obj': 'moto', 'active': false }); // Printing the outputconsole.log(gfg);
 Output:  
false
Example 3: 
Javascript
// Requiring the lodash libraryconst _ = require("lodash");      // Original array var object = [  { 'obj': 'moto', 'active': true },  { 'obj': 'lenovo',   'active': false } ];  // Use of _.some() method// The `_.matchesProperty` iteratee shorthand let gfg = _.some(object, ['active', false]); // Printing the outputconsole.log(gfg);
 Output:  
true
Example 4: 
Javascript
// Requiring the lodash libraryconst _ = require("lodash");      // Original arrayvar object = [  { 'obj': 'moto', 'active': true },  { 'obj': 'lenovo',   'active': false } ];  // Use of _.some() method// The `_.property` iteratee shorthand let gfg = _.some(object, 'active'); // Printing the outputconsole.log(gfg);
 Output:  
true
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
 
simmytarika5
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to set position relative to top of a canvas circle using Fabric.js ? - GeeksforGeeks

12 May, 2020
In this article, we are going to see how to position relative to the top of a canvas circle using FabricJS. The canvas means the circle is movable and can be stretched according to requirement. Further, the circle can be customized when it comes to initial stroke color, fill color, stroke width or radius.
Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our circle. After this, we will initialize instances of Canvas and Circle provided by FabricJS and position relative to the top of the circle using top property and render the Circle on the Canvas as given in the example below.
Syntax:
fabric.Circle({
    radius: number,
    top: number
}); 
Parameters: This function accepts two parameters as mentioned above and described below:
radius: It specifies the radius.
top: It specifies the relative distance from the top edge.
Example: This example uses FabricJS to position relative to top of a canvas circle.
<!DOCTYPE html><html>  <head>    <title>        How to position relative to top of        a canvas circle using FabricJS?    </title>      <!-- FabricJS CDN -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head>  <body>    <canvas id="canvas" width="600" height="200"         style="border:1px solid #000000">    </canvas>      <script>          // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");          // Initiate a Circle instance        var circle = new fabric.Circle({            radius: 50,            top: 30        });          // Render the circle in canvas        canvas.add(circle);    </script></body>  </html>
Output:
Fabric.js
JavaScript-Misc
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
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 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to detect copy paste commands Ctrl+V, Ctrl+C using JavaScript ? - GeeksforGeeks

23 Sep, 2020
To detect the combination of keys with “Ctrl”, we use the ctrl property of the keydown event. It returns a “boolean” value to tell if “ctrl” is pressed or not when the key event got triggered.
Syntax:
event.ctrlKey
Return Value:
true: When “ctrl” was pressed.
false: When “ctrl” was not pressed.
HTML code: Below is the code for the file “index.html” to detect the combination of “Ctrl+C” and “Ctrl+V”.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie-edge">    <link rel="stylesheet" href="style.css"></head>  <body>    <div class="container">        <textarea cols="30" row="5"             placeholder="Enter Text">        </textarea>          <textarea cols="30" row="5"             placeholder="Paste Text">        </textarea>    </div>          <script src="script.js"></script></body>  </html>
CSS code: The following code demonstrates the file “style.css” which is used in the above HTML file.
.container{
   display: flex;
   flex-direction: column;
   align-items: center;
}

textarea{
   margin-top: 20px;
}
Javascript code: The following demonstrates the code for the file “script.js” which is used in the above HTML file.
Javascript
document.body.addEventListener("keydown", function (ev) {      // function to check the detection    ev = ev || window.event;  // Event object 'ev'    var key = ev.which || ev.keyCode; // Detecting keyCode          // Detecting Ctrl    var ctrl = ev.ctrlKey ? ev.ctrlKey : ((key === 17)        ? true : false);      // If key pressed is V and if ctrl is true.    if (key == 86 && ctrl) {        // print in console.        console.log("Ctrl+V is pressed.");    }    else if (key == 67 && ctrl) {          // If key pressed is C and if ctrl is true.        // print in console.        console.log("Ctrl+C is pressed.");    }  }, false);
Output:
When Ctrl+C was pressed:
When Ctrl+V was pressed:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
GATE | GATE CS 2011 | Question 11 - GeeksforGeeks

28 Jun, 2021
A computer handles several interrupt sources of which the following are relevant for this question.

. Interrupt from CPU temperature sensor (raises interrupt if 
  CPU temperature is too high)
. Interrupt from Mouse(raises interrupt if the mouse is moved 
  or a button is pressed)
. Interrupt from Keyboard(raises interrupt when a key is 
  pressed or released)
. Interrupt from Hard Disk(raises interrupt when a disk 
  read is completed)
Which one of these will be handled at the HIGHEST priority?(A) Interrupt from Hard Disk(B) Interrupt from Mouse(C) Interrupt from Keyboard(D) Interrupt from CPU temperature sensorAnswer: (D)Explanation: Higher priority interrupt levels are assigned to requests which, if delayed or interrupted, could have serious consequences. Devices with high speed transfer such as magnetic disks are given high priority, and slow devices such as keyboard receive low priority (Source: Computer System Architecture by Morris Mano)
Interrupt from CPU temperature sensor would have serious consequences if ignored.Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47
Plot multiple columns of Pandas dataframe on the bar chart in Matplotlib

To plot multiple columns of a Pandas dataframe on the bar chart in matplotlib, we can take the following steps −
Make a dictionary of different keys, between 1 to 10 range.
Make a dictionary of different keys, between 1 to 10 range.
Make a dataframe using Pandas dataframe.
Make a dataframe using Pandas dataframe.
Create a bar plot, using the plot() method with kind=”bar”.
Create a bar plot, using the plot() method with kind=”bar”.
To display the figure, use the show() method.
To display the figure, use the show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {
   'y=1/x': [1 / i for i in range(1, 10)],
   'y=x': [i for i in range(1, 10)],
   'y=x^2': [i * i for i in range(1, 10)],
   'y=x^3': [i * i * i for i in range(1, 10)]
}
df = pd.DataFrame(d)
df.plot(kind='bar')
plt.show()
Comment in header file name? - GeeksforGeeks

08 May, 2017
What happens if there is a comment in header file name?Parsing of `#include’ is slightly special because comments are not recognized within the ”. Thus, in `#include ‘ the `/*’ does not start a comment and the directive specifies inclusion of a system header file named `x/*y’. Of course, a header file with such a name is unlikely to exist on Unix, where shell wildcard features would make it hard to manipulate.
Below are some examples.
#include <stdio.h>int main(){  printf("This will compile");  return 0;}
Output:
This will compile
#include <stdio.h/*comment*/>int main(){  printf("This will not compile");  return 0;}
Output:
Error: stdio.h/*comment*/: No such file or directory
#include <std/*comment*/io.h>int main(){  printf("This will not compile either");  return 0;}
Output:
Error: std/*comment*/io.h: No such file or directory
This article is contributed by Pankaj Boola. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C Basics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
UDP Server-Client implementation in C
How to dynamically allocate a 2D array in C?
Unordered Sets in C++ Standard Template Library
Powershell - Create Folder

New-Item cmdlet is used to create a directory by passing the path using -Path as path of the directory and -ItemType as Directory.
In this example, we'll create a folder in D:\Temp\ with name "Test Folder"
Type the following command in PowerShell ISE Console
New-Item -Path 'D:\temp\Test Folder' -ItemType Directory
You will see the following output.
Directory: D:\temp

Mode                LastWriteTime     Length Name                                               
----                -------------     ------ ----                                               
d----          4/3/2018   7:06 PM            Test Folder   

You can see the same in Windows Explorer where Test Folder is created in D:/temp folder.

    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
Add two numbers represented by two arrays in C Program

A number represented by the array is stored in such a form that each digit of the number is represented by an element of the array. For example,
Number 234 in array is {2,3,4}.
To add to such numbers we will first add number at the least significant digit and if the sum is greater than 10 propagate the carry. After this, we will go for the next consecutive digits of the array doing the same procedure and finding the sum.
Let’s take an example to add two numbers −
a = {2,9, 6}
b = {6, 3, 8}
Output: 934
Explanation − We will add the least significant digit of the number i.e. 6+8 = 14 that will propagate a carry and then for the same 9+3+1 = 13 that will again propagate the carry to next. The next will sum will be 2+6+1 = 9. This will make the sum = 934.
In order to find the sum of numbers stored as array. We will first check if any number has more number of digits. If yes then we will find the sum till the digits of smaller number and then go for add digits of larger number.In addition, we will check a carry number that will keep track of the carry that may arise in the sum and needs to be forwarded, initially it will be zero and also made zero before every sum iteration. We will one by one find the sum of numbers and store it into array and then print it.
 Live Demo
#include <iostream>
using namespace std;
int Sum(int a[], int b[], int n, int m){
   int sum[n];
   int i = n - 1, j = m - 1, k = n - 1;
   int c = 0, s = 0;
   while (j >= 0) {
      s = a[i] + b[j] + c;
      sum[k] = (s % 10);
      c = s / 10;
      k--;
      i--;
      j--;
   }
   while (i >= 0) {
      s = a[i] + c;
      sum[k] = (s % 10);
      c = s / 10;
      i--;
      k--;
   }
   for (int i = 0; i <= n-1; i++) {
      cout<<sum[i];
   }
}
int main(){
   int a[] = { 5, 6, 9 };
   int b[] = { 3, 8 };
   int n = sizeof(a) / sizeof(a[0]);
   int m = sizeof(b) / sizeof(b[0]);
   cout<<"The sum is ";
   if (n >= m)
      Sum(a, b, n, m);
   else
      Sum(b, a, m, n);
   return 0;
}
The sum is 607
How to Create Text on Canvas using Fabric.js ? - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to create a text on canvas using FabricJS. The text on canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.
Approach: To make this possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and render the Canvas on the Text as given in the example below.
Syntax: 
 fabric.Text(text, options); 
Parameters: This function accepts two parameters as mentioned above and described below:  
text: It specifies the text to be written.
options: It specifies the additional options to be applied.
Example: This example uses FabricJS to create simple editable text on canvas. 
HTML
<!DOCTYPE html><html> <head>    <title>        How to Create Text on        Canvas using Fabric.js?    </title>         <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head> <body>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000;">    </canvas>         <script>                 // Create a new instance of Canvas        var canvas = new fabric.Canvas("canvas");         // Create a new Text instance        var text = new fabric.Text('GeeksforGeeks', {            fill: 'green'        });         // Render the Text on Canvas        canvas.add(text);    </script></body> </html>
Output: 
 
abhishek0719kadiyan
Fabric.js
JavaScript-Misc
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Python Pandas – Find the common rows between two Data Frames

To find the common rows between two DataFrames, use the merge() method. Let us first create DataFrame1 with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)
Create DataFrame2 with two columns −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 250, 150, 80, 130, 90]
   }
)
To find the common rows −
dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)

Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 250, 150, 80, 130, 90]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# check for equality
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)

# finding common rows between two DataFrames
resData = dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)
print"\nCommon rows between two DataFrames...\n",resData
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3    Tesla     80
4  Bentley    110
5   Jaguar     90

DataFrame2 ...
       Car   Units
0      BMW    100
1    Lexus    250
2     Audi    150
3  Mustang     80
4  Bentley    130
5   Jaguar     90

Are both the DataFrames equal? False

Common rows between two DataFrames...
      Car   Units
0     BMW    100
1  Jaguar     90
Python | List of tuples to String - GeeksforGeeks

29 Oct, 2019
Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using str() + strip()The combination of above functions can be used to solve this problem. In this, we just convert a list into string and strip the opening, closing square brackets of list to present a string.
# Python3 code to demonstrate working of# List of tuples to String# using str() + strip()  # initialize listtest_list = [(1, 4), (5, 6), (8, 9), (3, 6)]  # printing original listprint("The original list is : " + str(test_list))  # List of tuples to String# using str() + strip()res = str(test_list).strip('[]')  # printing resultprint("Resultant string from list of tuple : " + res)
The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)

 
Method #2 : Using map() + join()This is yet another way in which this task can be performed. In this, we apply the string conversion function to each element and then join the tuples using join().
# Python3 code to demonstrate working of# List of tuples to String# using map() + join()  # initialize listtest_list = [(1, 4), (5, 6), (8, 9), (3, 6)]  # printing original listprint("The original list is : " + str(test_list))  # List of tuples to String# using map() + join()res = ", ".join(map(str, test_list))  # printing resultprint("Resultant string from list of tuple : " + res)
The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
numpy.broadcast

As seen earlier, NumPy has in-built support for broadcasting. This function mimics the broadcasting mechanism. It returns an object that encapsulates the result of broadcasting one array against the other.
The function takes two arrays as input parameters. Following example illustrates its use.
import numpy as np 
x = np.array([[1], [2], [3]]) 
y = np.array([4, 5, 6])  
   
# tobroadcast x against y 
b = np.broadcast(x,y)  
# it has an iterator property, a tuple of iterators along self's "components." 

print 'Broadcast x against y:' 
r,c = b.iters 
print r.next(), c.next() 
print r.next(), c.next() 
print '\n'  
# shape attribute returns the shape of broadcast object 

print 'The shape of the broadcast object:' 
print b.shape 
print '\n'  
# to add x and y manually using broadcast 
b = np.broadcast(x,y) 
c = np.empty(b.shape) 

print 'Add x and y manually using broadcast:' 
print c.shape 
print '\n'  
c.flat = [u + v for (u,v) in b] 

print 'After applying the flat function:' 
print c 
print '\n'  
# same result obtained by NumPy's built-in broadcasting support 

print 'The summation of x and y:' 
print x + y
Its output is as follows −
Broadcast x against y:
1 4
1 5

The shape of the broadcast object:
(3, 3)

Add x and y manually using broadcast:
(3, 3)

After applying the flat function:
[[ 5. 6. 7.]
 [ 6. 7. 8.]
 [ 7. 8. 9.]]

The summation of x and y:
[[5 6 7]
 [6 7 8]
 [7 8 9]]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to Find the Factorial of a Number using Python?

Factorial of a number is the product of all integers between 1 and itself. To find factorial of a given number, let us form a for loop over a range from 1 to itself. Remember that range() function excludes the stop value. Hence stop value should be one more than the input number. 
Each number in range is cumulatively multiplied in a variable f which is initialised to 1
num=int(input('enter a number'))
f=1
for i in range(1,num+1):
  f=f*i
print ('factorial of', num, '=',f)
Sample run of above code −
enter a number5
factorial of 5 = 120
Python - Save List to CSV - GeeksforGeeks

10 Jul, 2020
A CSV (Comma Separated Values) is a simple file format, used to store data in a tabular format. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
There are various methods to save lists to CSV which we will see in this article.
Method 1 : Using CSV Module
import csv    # field names fields = ['Name', 'Branch', 'Year', 'CGPA']     # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'],          ['Sanchit', 'COE', '2', '9.1'],          ['Aditya', 'IT', '2', '9.3'],          ['Sagar', 'SE', '1', '9.5'],          ['Prateek', 'MCE', '3', '7.8'],          ['Sahil', 'EP', '2', '9.1']]   with open('GFG', 'w') as f:          # using csv.writer method from CSV package    write = csv.writer(f)          write.writerow(fields)    write.writerows(rows)
Output:
Method 2 : Using Pandas
# importing pandas as pd  import pandas as pd         # list of name, degree, score nme = ["aparna", "pankaj", "sudhir", "Geeku"] deg = ["MBA", "BCA", "M.Tech", "MBA"] scr = [90, 40, 80, 98]      # dictionary of lists  dict = {'name': nme, 'degree': deg, 'score': scr}         df = pd.DataFrame(dict)     # saving the dataframe df.to_csv('GFG.csv') 
Output:
Method 3 : Using Numpy
import numpy as np    # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'],          ['Sanchit', 'COE', '2', '9.1'],          ['Aditya', 'IT', '2', '9.3'],          ['Sagar', 'SE', '1', '9.5'],          ['Prateek', 'MCE', '3', '7.8'],          ['Sahil', 'EP', '2', '9.1']]   # using the savetxt # from the numpy modulenp.savetxt("GFG.csv",            rows,           delimiter =", ",            fmt ='% s')
Output:
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
CSS Styling Links

With CSS, links can be styled in many different ways.
Links can be styled with any CSS property (e.g. color, font-family, 
background, etc.).
In addition, links can be styled 
differently depending on what state they are in.
The four links states are: 
a:link - a normal, unvisited link
a:visited - a link the user has visited
a:hover - a link when the user mouses over it
a:active - a link the moment it is clicked
When setting the style for several link states, there are some order rules:
a:hover MUST come after a:link and a:visited
a:active MUST come after a:hover
The text-decoration property is mostly used to remove underlines from links:
The background-color property can be used to specify a background color for links:
This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:
This example demonstrates how to add other styles to hyperlinks:
Another example of how to create link boxes/buttons:
This example demonstrates the different types of cursors (can be useful for links):
Set the color of links to "red".
<style>
 {
  color: red;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <a href="http://w3schools.com">This is a link</a>
</body>

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

10 Aug, 2021
Prerequisites: Object-Oriented Programming in Python, Object-Oriented Programming in Python | Set 2 Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.Syntax of constructor declaration : 
def __init__(self):
    # body of the constructor
Types of constructors : 
default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
Example of default constructor :  
Python3
class GeekforGeeks:     # default constructor    def __init__(self):        self.geek = "GeekforGeeks"     # a method for printing data members    def print_Geek(self):        print(self.geek)  # creating object of the classobj = GeekforGeeks() # calling the instance method using the object objobj.print_Geek()
Output : 
GeekforGeeks
Example of the parameterized constructor : 
Python3
class Addition:    first = 0    second = 0    answer = 0         # parameterized constructor    def __init__(self, f, s):        self.first = f        self.second = s         def display(self):        print("First number = " + str(self.first))        print("Second number = " + str(self.second))        print("Addition of two numbers = " + str(self.answer))     def calculate(self):        self.answer = self.first + self.second # creating object of the class# this will invoke parameterized constructorobj = Addition(1000, 2000) # perform Additionobj.calculate() # display resultobj.display()
Output : 
First number = 1000
Second number = 2000
Addition of two numbers = 3000
 
dhineshbala
ddeevviissaavviittaa
Picked
Python-OOP
python-oop-concepts
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()
Iterators in C#

Iterator performs a custom iteration over a collection. It uses the yield return statement and returns each element one at a time. The iterator remembers the current location and in the next iteration the next element is returned.
The following is an example −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo {
   class Program {
      public static IEnumerable<string> display() {
         int[] arr = new int[] {99,45,76};

         foreach (var val in arr) {
            yield return val.ToString();
         }
      }

      public static void Main(string[] args) {
         IEnumerable<string> ele = display();
         foreach (var element in ele) {
            Console.WriteLine(element);
         }
      }
   }
}
99
45
76
Above, we have an iterator method display() that use the yield statement to return one element at a time −
public static IEnumerable<string> display() {
   int[] arr = new int[] {99,45,76};

   foreach (var val in arr) {
      yield return val.ToString();
   }
}
The result is stored and each element is iterated and printed −
IEnumerable<string> ele = display();
foreach (var element in ele) {
   Console.WriteLine(element);
}
Create PySpark dataframe from nested dictionary

17 Jun, 2021
In this article, we are going to discuss the creation of Pyspark dataframe from the nested dictionary. 
We will use the createDataFrame() method from pyspark for creating DataFrame. For this, we will use a list of nested dictionary and extract the pair as a key and value. Select the key, value pairs by mentioning the items() function from the nested dictionary
[Row(**{'': k, **v}) for k,v in data.items()]
Example 1:Python program to create college data with a dictionary with nested address in dictionary
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSessionfrom pyspark.sql import Row  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # creating nested dictionarydata = {    'student_1': {        'student id': 7058,        'country': 'India',        'state': 'AP',        'district': 'Guntur'    },    'student_2': {        'student id': 7059,        'country': 'Srilanka',        'state': 'X',        'district': 'Y'    }}  # taking row datarowdata = [Row(**{'': k, **v}) for k,           v in data.items()]  # creating the pyspark dataframefinal = spark.createDataFrame(rowdata).select(  'student id', 'country', 'state', 'district')  # display pyspark dataframefinal.show()
Output:
+----------+--------+-----+--------+
|student id| country|state|district|
+----------+--------+-----+--------+
|      7058|   India|   AP|  Guntur|
|      7059|Srilanka|    X|       Y|
+----------+--------+-----+--------+
Example 2: Python program to create nested dictionaries with 3 columns(3 keys)
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSessionfrom pyspark.sql import Row  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # creating nested dictionarydata = {    'student_1': {        'student id': 7058,        'country': 'India',        'state': 'AP'    },    'student_2': {        'student id': 7059,        'country': 'Srilanka',        'state': 'X'      }}  # taking row datarowdata = [Row(**{'': k, **v}) for k, v in data.items()]  # creating the pyspark dataframefinal = spark.createDataFrame(rowdata).select(  'student id', 'country', 'state')  # display pyspark dataframefinal.show()
Output:
+----------+--------+-----+
|student id| country|state|
+----------+--------+-----+
|      7058|   India|   AP|
|      7059|Srilanka|    X|
+----------+--------+-----+
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function