code-rag-bench/online-tutorials huggingface dataset:
Solidity - Libraries

Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions which other contracts can call. Solidity have certain restrictions on use of a Library. Following are the key characteristics of a Solidity Library.
Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library.
Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library.
Library can not be destroyed as it is assumed to be stateless.
Library can not be destroyed as it is assumed to be stateless.
A Library cannot have state variables.
A Library cannot have state variables.
A Library cannot inherit any element.
A Library cannot inherit any element.
A Library cannot be inherited.
A Library cannot be inherited.
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;

library Search {
   function indexOf(uint[] storage self, uint value) public view returns (uint) {
      for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;
      return uint(-1);
   }
}
contract Test {
   uint[] data;
   constructor() public {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function isValuePresent() external view returns(uint){
      uint value = 4;
      
      //search if value is present in the array using Library function
      uint index = Search.indexOf(data, value);
      return index;
   }
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3

The directive using A for B; can be used to attach library functions of library A to a given type B. These functions will used the caller type as their first parameter (identified using self).
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;

library Search {
   function indexOf(uint[] storage self, uint value) public view returns (uint) {
      for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
      return uint(-1);
   }
}
contract Test {
   using Search for uint[];
   uint[] data;
   constructor() public {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function isValuePresent() external view returns(uint){
      uint value = 4;      
      
      //Now data is representing the Library
      uint index = data.indexOf(value);
      return index;
   }
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Python – Reverse Row sort in Lists of List

16 Jun, 2022
Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop + sort() + reverse This problem can be solved using a loop to loop over each row. The sort and reverse can be used to perform the reverse sort of rows. 
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using loop # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using loopfor ele in test_list:    ele.sort(reverse=True) # printing resultprint("The reverse sorted Matrix is : " + str(test_list))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]

Method #2: Using list comprehension + sorted() This is yet another way in which this task can be performed. In this, we perform in a similar way, just pack the logic in one line using list comprehension to provide a compact alternative. 
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using list comprehension + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using list comprehension + sorted()res = [sorted(sub, reverse=True) for sub in test_list] # printing resultprint("The reverse sorted Matrix is : " + str(res))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]

Method#3: Using map() + sorted This is one way to solve this problem. In this, we update the existing list with the help of map function which sorts the internal list in reverse order using the sorted function.
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using map + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using map + sorted()res = list(map(lambda x: sorted(x, reverse=True), test_list)) # printing resultprint("The reverse sorted Matrix is : " + str(res))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]

satyam00so
Python list-programs
Python-list-of-lists
Python-Matrix
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create an unique id in ReactJS ?

11 Nov, 2021
In this article, we will see the simple steps to create a unique reference ID in react JS. This has many uses such as giving a user uploaded image a unique name for saving in a database.
Approach: We will be using Uuid V4 in this tutorial. Uuid v4 is a React library or package that creates a universally unique identifier (UUID). It is a 128-bit unique identifier generator. The bits that comprise a UUID v4 are generated randomly and with no inherent logic. Because of this, there is no way to identify information about the source by looking at the UUID, so it is very unique.
Below is the step by step implementation:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2:  After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: After creating, your project directory should look like this.
Project Directory
Step 3: Delete all files from the src folder except for index.js and app.js(not necessary but recommended). Next, install UUID v4 using the following command:
npm install uuidv4
Step 4: Import the package into your component, page or code etc. You can now assign the Unique ID to any variable using the below code. unique_id is an example here, it can be any variable name. We are storing the unique id in it. You can then console.log() it to see the output and also use it wherever needed. Here I am displaying it in a <p> tag.
If the unique id is too long, you can slice it or extract a small part of it to use. We can use the JavaScript slice() function here. It takes 2 parameters, the number of characters and the last character.The variable small_id will store this sliced id. We will output both the ids on the browser to see the difference.
App.js
//import uuid v4import { v4 as uuid } from 'uuid';  export default function App() {  const unique_id = uuid();  const small_id = unique_id.slice(0,8)  return (    <div className="App">      <h1>Unique ID</h1>      <p>{unique_id}</p>      <h1>Sliced Unique ID</h1>      <p>{small_id}</p>    </div>  );}
Step to run the application: To run the app, use the following command:
npm start
Output: Now if you run the app, the unique id will be shown below the heading. Each time you refresh, a new and unique id will be shown with no repetition.
Output
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
Python | sympy.divisor_sigma() method

17 Sep, 2019
With the help of sympy.divisor_sigma() method, we can find the divisor function  for positive integer n. divisor_sigma(n, k) is equal to the sum of all the divisors of n raised to the power of k or sum([x**k for x in divisors(n)]).
Syntax: divisor_sigma(n, k)
Parameter:n – It denotes an integer.k – It denotes an integer(optional). Default for k is 1.
Returns: Returns the sum of all the divisors of n raised to the power of k.
Example #1:
# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma  n = 8  # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n)       print("divisor_sigma({}) =  {} ".format(n, divisor_sigma_n)) # 1 ^ 1 + 2 ^ 1 + 4 ^ 1 + 8 ^ 1 = 15
Output:
divisor_sigma(8) =  15 

Example #2:
# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma  n = 15k = 2  # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n, k)       print("divisor_sigma({}, {}) =  {} ".format(n, k, divisor_sigma_n)) # 1 ^ 2 + 3 ^ 2 + 5 ^ 2 + 15 ^ 2 = 260
Output:
divisor_sigma(15, 2) =  260 

SymPy
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
How to convert array to string in PHP ?

31 Jul, 2021
We have given an array and the task is to convert the array elements into string. In this article, we are using two methods to convert array to string.
Method 1: Using implode() function: The implode() method is an inbuilt function in PHP and is used to join the elements of an array. The implode() method is an alias for PHP | join() function and works exactly same as that of join() function.
Syntax:
string implode($separator, $array)
Example:
PHP
<?php    // Declare an array $arr = array("Welcome","to", "GeeksforGeeks",     "A", "Computer","Science","Portal");      // Converting array elements into// strings using implode functionecho implode(" ",$arr);   ?>
Output:
Welcome to GeeksforGeeks A Computer Science Portal
Method 2: Using json_encode() Function: The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.Syntax:
string json_encode( $value, $option, $depth )
Example:
PHP
<?php   // Declare multi-dimensional array $value = array(     "name"=>"GFG",     array(         "email"=>"abc@gfg.com",         "mobile"=>"XXXXXXXXXX"    ) );   // Use json_encode() function $json = json_encode($value);   // Display the output echo($json);   ?> 
Output:
{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-Misc
Picked
Technical Scripter 2020
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to Find the Area of a Rectangle Using Classes

When it is required to find the area of a rectangle using classes, object oriented method is used. Here, a class is defined, attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area of rectangle.
Below is a demonstration for the same −
 Live Demo
class shape_rectangle():
def __init__(self,my_length, my_breadth):
   self.length = my_length
   self.breadth = my_breadth
def calculate_area(self):
   return self.length*self.breadth
len_val = 6
bread_val = 45
print("The length of the rectangle is : ")
print(len_val)
print("The breadth of the rectangle is : ")
print(bread_val)
my_instance = shape_rectangle(len_val,bread_val)
print("The area of the rectangle : ")
print(my_instance.calculate_area())
print()
The length of the rectangle is :
6
The breadth of the rectangle is :
45
The area of the rectangle :
270
A class named ‘shape_rectangle’ is defined.
It has the ‘init’ method that initializes values.
It also has a method that calculates the area of the rectangle given the specific parameters.
An instance of this class is created.
The function to calculate area is called by passing required parameters.
It is displayed as output on the console.
Find the smallest and second smallest elements in an array in C++

Suppose we have an array of n elements. We have to find the first, second smallest elements in the array. First smallest is the minimum of the array, second smallest is minimum but larger than the first smallest number.
Scan through each element, then check the element, and relate the condition for first, and second smallest elements conditions to solve this problem.
#include<iostream>
using namespace std;
int getTwoSmallest(int arr[], int n) {
   int first = INT_MAX, sec = INT_MAX;
   for (int i = 0; i < n; i++) {
      if (arr[i] < first) {
         sec = first;
         first = arr[i];
      }else if (arr[i] < sec) {
         sec = arr[i];
      }
   }
   cout << "First smallest = " << first << endl;
   cout << "Second smallest = " << sec << endl;
}
int main() {
   int array[] = {4, 9, 18, 32, 12};
   int n = sizeof(array) / sizeof(array[0]);
   getTwoSmallest(array, n);
}
First smallest = 4
Second smallest = 9
How to Print Multiple Arguments in Python?

29 Dec, 2020
An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition.
Example: Simple argument
Python3
def GFG(name, num):    print("Hello from ", name + ', ' + num)    GFG("geeks for geeks", "25")
Output:
Hello from  geeks for geeks, 25
Calling the above code with no arguments or just one argument generates an error.
As shown above, functions had a fixed number of arguments. In Python, there are other ways to define a function that can take the variable number of arguments.Different forms are discussed below:
Python Default Arguments: Function arguments can have default values in Python. We provide a default value to an argument by using the assignment operator (=).
Example:
Python3
def GFG(name, num="25"):    print("Hello from", name + ', ' + num)    GFG("gfg")GFG("gfg", "26")
Output:
Hello from gfg, 25
Hello from gfg, 26
Pass it as a tuple 
Python3
def GFG(name, num):    print("hello from %s , %s" % (name, num))    GFG("gfg", "25")
Output:
hello from gfg , 25
Pass it as a dictionary 
Python3
def GFG(name, num):    print("hello from %(n)s , %(s)s" % {'n': name, 's': num})    GFG("gfg", "25")
Output:
hello from gfg , 25
Using new-style string formatting with number 
Python3
def GFG(name, num):    print("hello from {0} , {1}".format(name, num))    GFG("gfg", "25")
Output:
hello from gfg , 25
Using new-style string formatting with explicit names 
Python3
def GFG(name, num):    print("hello from {n} , {r}".format(n=name, r=num))    GFG("gfg", "25")
Output:
hello from gfg , 25
Concatenate strings 
Python3
def GFG(name, num):    print("hello from " + str(name) + " , " + str(num))    GFG("gfg", "25")
Output:
hello from gfg , 25
 Using the new f-string formatting in Python 3.6 
Python3
def GFG(name, num):    print(f'hello from {name} , {num}')    GFG("gfg", "25")
Output:
hello from gfg , 25
Using *args 
Python3
def GFG(*args):    for info in args:        print(info)    GFG(["Hello from", "geeks", 25], ["Hello", "gfg", 26])
Output:
[‘Hello from’, ‘geeks’, 25]
[‘Hello’, ‘gfg’, 26]
Using **kwargs 
Python3
def GFG(**kwargs):    for key, value in kwargs.items():        print(key, value)    GFG(name="geeks", n="- 25")GFG(name="best", n="- 26")
Output:
name geeks
n – 25
name best
n – 26
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
DateTimeOffset.AddMonths() Method in C# - GeeksforGeeks

21 Feb, 2019
This method is used to return a new DateTimeOffset object that adds a specified number of months to the value of the current instance.
Syntax: public DateTimeOffset AddMonths (int months);Here, it takes a number of whole months. The number can be negative or positive.
Return Value: This method returns an object whose value is the sum of the date and time represented by the current DateTimeOffset object and the number of months represented by months.
Exception: This method will give ArgumentOutOfRangeException if the resulting DateTimeOffset value is less than MinValue or the resulting DateTimeOffset value is greater than MaxValue.
Below programs illustrate the use of DateTimeOffset.AddMonths(Int32) Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTimeOffset            DateTimeOffset offset = new DateTimeOffset(2007,                    6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));              // adding a specified number of whole and            // fractional months to the value of this            // instance using AddMonths() method            DateTimeOffset value = offset.AddMonths(10);              // Display the time            Console.WriteLine("DateTimeOffset is {0}", value);        }          catch (ArgumentOutOfRangeException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
DateTimeOffset is 04/01/2008 07:55:00 -05:00

Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTimeOffset            DateTimeOffset offset = DateTimeOffset.MaxValue;              // adding a specified number of whole and            // fractional months to the value of this            // instance using AddMonths() method            DateTimeOffset value = offset.AddMonths(10);              // Display the time            Console.WriteLine("DateTimeOffset is {0}", value);        }          catch (ArgumentOutOfRangeException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.ArgumentOutOfRangeException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.addmonths?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C#
Firebase - Deploying

In this chapter, we will show you how to host your app on the Firebase server.
Before we begin, let us just add some text to index.html body tag. In this example, we will add the following text.
<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>
We need to install firebase tools globally in the command prompt window.
npm install -g firebase-tools

First we need to login to Firebase in the command prompt.
firebase login

Open the root folder of your app in the command prompt and run the following command.
firebase init

This command will initialize your app.
NOTE − If you have used a default configuration, the public folder will be created and the index.html inside this folder will be the starting point of your app. You can copy your app file inside the public folder as a workaround.
This is the last step in this chapter. Run the following command from the command prompt to deploy your app.
firebase deploy

After this step, the console will log your apps Firebase URL. In our case, it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in the browser to see our app.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Algorithms | Analysis of Algorithms | Question 3 - GeeksforGeeks

06 Feb, 2013
The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs is. (GATE CS 2012)(A) T(n) = 2T(n – 2) + 2(B) T(n) = 2T(n – 1) + n
(C) T(n) = 2T(n/2) + 1(D) T(n) = 2T(n – 1) + 1Answer: (D)Explanation: Following are the steps to follow to solve Tower of Hanoi problem recursively.
Let the three pegs be A, B and C. The goal is to move n pegs from A to C.
To move n discs from peg A to peg C:
    move n-1 discs from A to B. This leaves disc n alone on peg A
    move disc n from A to C
    move n?1 discs from B to C so they sit on disc n
The recurrence function T(n) for time complexity of the above recursive solution can be written as following.
T(n) = 2T(n-1) + 1
Algorithms-Analysis of Algorithms
Analysis of Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Sorting | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
GATE | GATE MOCK 2017 | Question 23
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Sorting | Question 5
Algorithms | Bit Algorithms | Question 3
Algorithms | Sorting | Question 6
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks

12 Sep, 2019
Given the following expression grammar:
E -> E * F | F + E | F
F -> F - F | id 
which of the following is true?(A) * has higher precedence than +(B) – has higher precedence than *(C) + and — have same precedence(D) + has higher precedence than *Answer: (B)Explanation: Let say i/p is 3*4-5 when we draw parse tree according to grammar
      E
   /  |  \
  E   *   F
  |     / | \
  F    F  -  F
  |    |     |
id(3) id(4) id(5)
As we can see first ‘- ‘ will be evaluated then ‘ * ‘ is evaluated so ‘ – ‘ has higher precedence then *.
So correct choice is B
See question 1 of https://www.geeksforgeeks.org/compilers-set-2/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
How to write an empty function in Java

Let us see how to write an empty function in Java −
 Live Demo
import java.util.Vector;
public class Demo{
   public static void my_empty_fun(){
   }
   public static void main(String[] args){
      System.out.println("In the main function");
      my_empty_fun();
   }  
}
In the main function
An empty function is basically creating a function without defining any operations inside it. A class named Demo contains an empty function named ‘my_empty_fun’ which is just completed by placing two flower brackets, without adding any functionality into it. In the main function, a print statement is written after which the empty function is called. Since there is no functionality defined for it, it does nothing.
Initialization of variable sized arrays in C

Variable sized arrays are data structures whose length is determined at runtime rather than compile time. These arrays are useful in simplifying numerical algorithm programming. The C99 is a C programming standard that allows variable sized arrays.
A program that demonstrates variable sized arrays in C is given as follows −
 Live Demo
#include

int main(){
   int n;

   printf("Enter the size of the array: \n");
   scanf("%d", &n);

   int arr[n];

   for(int i=0; i<n; i++)
   arr[i] = i+1;

   printf("The array elements are: ");

   for(int i=0; i<n; i++)
   printf("%d ", arr[i]);

   return 0;
}
The output of the above program is as follows −
Enter the size of the array: 10
The array elements are: 1 2 3 4 5 6 7 8 9 10
Now let us understand the above program.
The array arr[ ] is a variable sized array in the above program as its length is determined at run time by the value provided by the user. The code snippet that shows this is as follows:
int n;

printf("Enter the size of the array: \n");
scanf("%d", &n);

int arr[n];
The array elements are initialized using a for loop and then these elements are displayed. The code snippet that shows this is as follows −
for(int i=0; i<n; i++)
arr[i] = i+1;

printf("The array elements are: ");

for(int i=0; i<n; i++)
printf("%d ", arr[i]);
Bool Array in C#

In a bool array, you can store true and false values. To set a bool array, use the new operator −
bool[] arr = new bool[5];
To add elements in the array −
arr[0] = true;
arr[1] = true;
arr[2] = false;
arr[3] = true;
arr[4] = true;
Let us see the complete code −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      bool[] arr = new bool[5];
      arr[0] = true;
      arr[1] = true;
      arr[2] = false;
      arr[3] = true;
      arr[4] = true;
      Console.WriteLine("Displaying values...");

      foreach (bool res in arr) {
         Console.WriteLine(res);
      }
   }
}
Displaying values...
True
True
False
True
True
Convert dataframe to list of vectors in R - GeeksforGeeks

25 Aug, 2021
In this article, we will learn how to convert a dataframe into a list of vectors, such that we can use columns of the dataframes as vectors in the R Programming language.
as.list() function in R Language is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames.
Syntax:  as.list( object )
Parameter: Dataframe object in our case
Simply pass our sample dataframe object as an argument in as.list(), which will return a list of vectors. 
Example 1:
R
df<-data.frame(c1=c(1:5),               c2=c(6:10),               c3=c(11:15),               c4=c(16:20)) print("Sample Dataframe")print (df) list=as.list(df) print("After Conversion of Dataframe into list of Vectors")print(list)
Output:
[1] "Sample Dataframe"
  c1 c2 c3 c4
1  1  6 11 16
2  2  7 12 17
3  3  8 13 18
4  4  9 14 19
5  5 10 15 20
[1] "After Conversion of Dataframe into list of Vectors"
$c1
[1] 1 2 3 4 5
$c2
[1]  6  7  8  9 10
$c3
[1] 11 12 13 14 15
$c4
[1] 16 17 18 19 20
Example 2:
R
df <- data.frame(name = c("Geeks", "for", "Geeks"),                roll_no = c(10, 20, 30),                age=c(20,21,22)                ) print("Sample Dataframe")print (df) print("Our list after being converted from a dataframe: ") list=as.list(df)list
Output:
[1] "Sample Dataframe"
  name roll_no age
1 Geeks      10  20
2   for      20  21
3 Geeks      30  22
[1] "Our list after being converted from a dataframe: "
$name
[1] Geeks for   Geeks
Levels: for Geeks
$roll_no
[1] 10 20 30
$age
[1] 20 21 22
 split() function in R Language is used to divide a data vector into groups as defined by the factor provided.
Syntax: split(x, f)
Parameters:
x: represents data vector or data frame
f: represents factor to divide the data
Example:
R
df<-data.frame(c1=c(1:5),               c2=c(6:10),               c3=c(11:15),               c4=c(16:20)) print("Sample Dataframe")print (df) print("Result after conversion") split(df, 1:nrow(df))
Output:
[1] "Sample Dataframe"
  c1 c2 c3 c4
1  1  6 11 16
2  2  7 12 17
3  3  8 13 18
4  4  9 14 19
5  5 10 15 20
[1] "Result after conversion"
$`1`
  c1 c2 c3 c4
1  1  6 11 16
$`2`
  c1 c2 c3 c4
2  2  7 12 17
$`3`
  c1 c2 c3 c4
3  3  8 13 18
$`4`
  c1 c2 c3 c4
4  4  9 14 19
$`5`
  c1 c2 c3 c4
5  5 10 15 20
sagartomar9927
Picked
R DataFrame-Programs
R List-Programs
R-DataFrame
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Python | Decimal is_zero() method - GeeksforGeeks

05 Sep, 2019
Decimal#is_zero() : is_zero() is a Decimal class method which checks whether the Decimal value is zero value.
Syntax: 
Decimal.is_zero()

Parameter: 
Decimal values

Return: 
true - if the Decimal value is zero value; otherwise false


Code #1 : Example for is_zero() method
# Python Program explaining # is_zero() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal(0)  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.is_zero() methodprint ("\n\nDecimal a with is_zero() method : ", a.is_zero())  print ("Decimal b with is_zero() method : ", b.is_zero())
Output :
Decimal value a :  -1
Decimal value b :  0


Decimal a with is_zero() method :  False
Decimal b with is_zero() method :  True


Code #2 : Example for is_zero() method
# Python Program explaining # is_zero() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-0)  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.is_zero() methodprint ("\n\nDecimal a with is_zero() method : ", a.is_zero())  print ("Decimal b with is_zero() method : ", b.is_zero())
Output :
Decimal value a :  0
Decimal value b :  3.21E+7


Decimal a with is_zero() method :  True
Decimal b with is_zero() method :  False

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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Tryit Editor v3.7

HTML Form elements
Tryit: HTML output element
Create and write on excel file using xlsxwriter module in Python

Python’s wide availability of libraries enables it to interact with Microsoft excel which is a very widely used data processing tool. In this article we will see how we can use the module named xlsxwriter to create and write into a excel file. It cannot write into existing excel file.
We can write to each cell of an excel sheet by writing to the name of the cell. In the below example we create a workbook and then ass a worksheet to it. Finally write to the cells of the worksheet using the write() method.
import xlsxwriter

# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Schedule.xlsx')

# Add new worksheet
sheet_schedule = xlsx_File.add_worksheet()

# write into the worksheet
sheet_schedule.write('A1', 'Day')
sheet_schedule.write('A2', 'Mon')
sheet_schedule.write('A3', 'Tue')

sheet_schedule.write('B1', 'Schedule')
sheet_schedule.write('B2', 'Final Exam')
sheet_schedule.write('B3', 'party')

# Close the Excel file
xlsx_File.close()
Running the above code gives us the following result −
In this approach we can initialize the row and column number from where we want to start writing. Then use a for loop to add required values to the rows and cells by dynamically increasing their values. In the below example we only add more rows. But by designing a loop within a loop we can also create both columns and rows dynamically.
import xlsxwriter

# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Days.xlsx')

# Add new worksheet
sheet_days = xlsx_File.add_worksheet()

row = 1
column = 1

days = ['Mon','Tue','wed','Thu','Fri','Sat']

# Iterating through days list
for day in days:
sheet_days.write(row, column, day)
row += 1

# Close the Excel file
xlsx_File.close()
Running the above code gives us the following result −
Chrono library in C++

In this section we will see what is the Chrono library in C++. This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library.
In this library, it provides precision-neutral concept, by separating the durations and point of time.
The duration objects are used to express time span by means of a count like minute, two hours or ten minutes. For example, 30 seconds is represented by a duration consisting of 30 ticks of unit of 1 seconds.
#include <iostream>
#include <chrono>
using namespace std;
int main () {
   using namespace std::chrono;
   // chrono::milliseconds is an instantiation of std::chrono::duration milliseconds mili(1000);
   mili = mili*60;
   cout << "Duration : ";
   cout << mili.count() << " milliseconds.\n";
   cout << "Duration : ";
   cout << (mili.count() * milliseconds::period::num / milliseconds::period::den);
   cout << " seconds.\n";
}
Duration : 60000 milliseconds.
Duration : 60 seconds.
jQuery | change() with Examples - GeeksforGeeks

03 Aug, 2021
The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements.
Syntax :
$(selector).change(function)

Parameter: It accepts an optional parameter “function”.Return Value: It returns the element with the modification.jQuery code to show the working of change() method:Code #1:In the below code, no function is passed to the change method.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/               jquery/3.3.1/jquery.min.js"></script>    <!--Demo of change method without passing function-->    <script>        $(document).ready(function() {            $("button").click(function() {                $("input").change();            });        });    </script></head>  <body>    <p>Click the button to see the changed value !!!</p>    <!--click on this button and see the change -->    <button>Click Me!</button>    <p>Enter value:        <input value="Donald" onchange="alert(this.value)"        type="text"></p></body>  </html>
Output:Before clicking the “Click Me” button-
After clicking the “Click Me” button-
Code #2:In the below code, function is passed to the change method.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/                   jquery/3.3.1/jquery.min.js"></script>    <!--Here function is passed to the change method-->    <script>        $(document).ready(function() {            $(".field").change(function() {                $(this).css("background-color", "#7FFF00");            });        });    </script>    <style>        .field {            padding: 5px;        }    </style></head>  <body>    <!--write something and click outside -->    Enter Value:    <input class="field" type="text">    <p>Write something in the input field, and then        press enter or click outside the field.</p></body>  </html>
Output:Before entering any values to the “Enter Value:” box-
After entering a values of “GeeksforGeeks” to the “Enter Value:” box and clicking outside of the box-
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
destinierkunal34
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change the background color after clicking the button in JavaScript ?
C# program to return an array from methods

Call a method under Join method to join words −
string.Join(" ", display())
Now set a string array −
string[] str = new string[5];
Add individual elements −
str[0] = "My";
str[1] = "name";
str[2] = "is";
str[3] = "Brad";
str[4] = "Pitt";
And return the same string array from method −
return str;
The following is the complete code −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      Console.WriteLine(string.Join(" ", display()));
   }
   static string[] display() {
      string[] str = new string[5];

      // string array elements
      str[0] = "My";
      str[1] = "name";
      str[2] = "is";
      str[3] = "Brad";
      str[4] = "Pitt";
      return str;
   }
}
My name is Brad Pitt
HTML Window innerWidth Property

The HTML Window innerWidth property returns the width of the content area of a window in an HTML document.
Following is the syntax −
window.innerWidth
Let us see an example of HTML Window innerWidth Property −
 Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #8BC6EC;
      background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show {
      font-size: 1.2rem;
   }
</style>
<body>
<h1>HTML Window innerWidth Property</h1>
<button onclick="display()" class="btn">Show window inner width</button>
<div class="show"></div>
<script>
   function display() {
      document.querySelector('.show').innerHTML = 'Window inner width is: ' + window.innerWidth + "px";
   }
</script>
</body>
</html>
Click on “Show window inner width” button to display the inner width of the content area:
How to set border width, border style, and border color in one declaration with JavaScript?

To set the border width, style, and color in a single declaration, use the border property in JavaScript.
You can try to run the following code to learn how to set border in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="display()">Set border</button>
      <div id="box">
         <p>Demo Text</p>
         <p>Demo Text</p>
      </div>
      <script>
         function display() {
            document.getElementById("box").style.border = "thick dashed #000000";
         }
      </script>
   </body>
</html>
Difference between Runnable and Callable interface in java

Runnable and Callable both functional interface. Classes which are implementing these interfaces are designed to be executed by another thread.
Thread can be started with Ruunable and they are two ways to start a new thread: one is by subclassing Thread class and another is implementing Runnable interface.
Thread class does not have constructor for callable so we should use ExecutorService  class for executing thread.
public class RunnableExample implements Runnable {
   public void run() {
      System.out.println("Hello from a Runnable!");
   }
   public static void main(String args[]) {
      (new Thread(new RunnableExample())).start();
   }
}
public class Main {
   public static void main(String args[]) throws InterruptedException, ExecutionException {
      ExecutorService services = Executors.newSingleThreadExecutor();
      Future<?> future = services.submit(new Task());
      System.out.println("In Future Object" + future.get());
   }
}
import java.util.concurrent.Callable;

public class Task implements Callable {

   @Override
   public String call() throws Exception {
      System.out.println("In call");
      String name = "test";
      return name;
   }
}
Jackson - JsonParser Class

JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.
Following is the declaration for com.fasterxml.jackson.core.JsonParser class:
public abstract class JsonParser
   extends Object
      implements Closeable, Versioned
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
 Print
 Add Notes
 Bookmark this page
Difference between Transfer Time and Disk Access Time in Disk Scheduling - GeeksforGeeks

28 Apr, 2020
1. Transfer Time :Time required to transfer the required amount of data. It can be calculated by the given formula
Transfer time,
= Data to be transfer / transfer rate 
Data to be transfer is given in the question and transfer rate is sometimes given and sometimes it may not be given.
It can be calculated by the given formula.
Transfer Rate,
= {(Number of heads or number of surfaces in the disk)
     *(capacity of one track or number of sectors in each track)
       *(Number of rotations in each track to reach the required sector)}
2. Data Access Time:It is the total time required to access the data.It means total time required to read/write the data from the disk.Following is the formula to calculated the data access time:
Data access time,
= {(Seek time) + (Rotational Latency) + (Data Transfer Time)} 
Note:
Seek time – The time required by R/W head to move to the desired track from the current position.
Rotational Latency – Time required by sector to come under R/W head.
Difference between Transfer Time and Disk Access Time in Disk Scheduling :
Picked
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Automate the Conversion from Python2 to Python3 - GeeksforGeeks

16 Jul, 2020
We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3.
This module does not come built-in with Python. To install this type the below command in the terminal.
pip install 2to3
Syntax:
2to3 [file or folder] -w
If we want to change all files in the currently open folder and all the files in the subfolder from Python2 to Python3 type the below command.
2to3.-w
If we want to change a particular file in the current folder from Python2 to Python3 then enter the following command.
2to3 gfg.py -w
Example: Consider a simple Python2 file.
To convert this file from Python2 to Python3 open the terminal in the directory containing the file and type the below command.
The Python file will now be converted to Python3. Let’s see the file.
Python-projects
python-utility
Python
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 drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to validate decimal numbers in JavaScript?

To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.
You can try to run the following code to validate decimal numbers −
<html>
   <body>
      <script>
         var str = "1.5";
         var re = /^[-+]?[0-9]+\.[0-9]+$/;
         var found = str.match( re );
         document.write("decimal" );
      </script>
   </body>
</html>
How to change the color of a plot frame in Matplotlib?

To change the color of a plot frame, we can set axes ticklines and spine value into a specific color.
Create a figure and add a set of subplots, using subplots method with value 4.
Create a figure and add a set of subplots, using subplots method with value 4.
Zip colors with axes and iterate them together.
Zip colors with axes and iterate them together.
In the iteration, set the color for spines values and ticklines (x, y).
In the iteration, set the color for spines values and ticklines (x, y).
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4)
for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'red', 'yellow', 'blue']):
   plt.setp(ax.spines.values(), color=color)
   ax.plot([8, 3], c=color)
   plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)
plt.show()