code-rag-bench/online-tutorials huggingface dataset:
How to sum all elements in a nested array? JavaScript

Let’s say, we are supposed to write a function that takes in a nested array of Numbers and returns the sum of all the numbers. We are required to do this without using the Array.prototype.flat() method.
Let’s write the code for this function −
const arr = [
   5,
   7,
   [ 4, [2], 8, [1,3], 2 ],
   [ 9, [] ],
   1,
   8
];
const findNestedSum = (arr) => {
   let sum = 0;
   for(let len = 0; len < arr.length; len++){
      sum += Array.isArray(arr[len]) ? findNestedSum(arr[len]) :
      arr[len];
   };
   return sum;
};
console.log(findNestedSum(arr));
The output in the console will be −
50
PyQt5 - Set background color to view part of ComboBox - GeeksforGeeks

04 May, 2020
In this article we will see how we can set background color to the view part of the combo box. View part is basically drop down item list, which shows all the available items, we have get the view object with the help of view method, by default combo box uses QListView object. Below is the representation of normal view box and view box with color.
In order to do this we have to change the style sheet associated with the combo box, below is the style sheet code to do this
QListView
{
background-color : lightgreen;
}

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # making combo box editable        self.combo_box.setEditable(True)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # adding background color to the view part of combo box        self.combo_box.setStyleSheet("QListView"                                     "{"                                     "background-color: lightgreen;"                                     "}")      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
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
Iterate over a list in Python
How to Install PIP on Windows ?
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
Objective-C Blocks

An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.
Blocks are a language-level feature added to C, Objective-C and C++ which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages
returntype (^blockName)(argumentType);

Simple block implementation
returntype (^blockName)(argumentType)= ^{
};
Here is a simple example
void (^simpleBlock)(void) = ^{
   NSLog(@"This is a block");
};
We can invoke the block using
simpleBlock();

Blocks can also take arguments and return values just like methods and functions.
Here is a simple example to implement and invoke a block with arguments and return values.
double (^multiplyTwoValues)(double, double) = 
   ^(double firstValue, double secondValue) {
      return firstValue * secondValue;
   };

double result = multiplyTwoValues(2,4); 
NSLog(@"The result is %f", result);
Here is a simple example using typedef in block. Please note this sample doesn't work on the online compiler for now. Use XCode to run the same.
#import <Foundation/Foundation.h>

typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock {

   NSLog(@"Action Performed");
   completionBlock();
}

@end

int main() {
   
   /* my first program in Objective-C */
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass performActionWithCompletion:^{
      NSLog(@"Completion is called to intimate action is performed.");
   }];

   return 0;
}
Let us compile and execute it, it will produce the following result −
2013-09-10 08:13:57.155 demo[284:303] Action Performed
2013-09-10 08:13:57.157 demo[284:303] Completion is called to intimate action is performed.

Blocks are used more in iOS applications and Mac OS X. So its more important to understand the usage of blocks.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Prototype and AJAX Tutorial

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
For a complete understanding on AJAX, please go through our simple AJAX Tutorial.
Prototype framework enables you to deal with Ajax calls in a very easy and fun way that is also safe (cross-browser). Prototype also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.
Ajax functionality is contained in the global Ajax object. This object provides all the necessary methods to handle AJAX requests and responses in an easy way.
Actual requests are made by creating instances of the Ajax.Request() object.
new Ajax.Request('/some_url', { method:'get' });

The first parameter is the URL of the request; the second is the options hash. The method option refers to the HTTP method to be used; default method is POST.
Ajax requests are by default asynchronous, which means you must have callbacks that will handle the data from a response. Callback methods are passed in the options hash when making a request −
new Ajax.Request('/some_url', {
   method:'get',
   onSuccess: function(transport) {
      var response = transport.responseText || "no response text";
      alert("Success! \n\n" + response);
   },
   onFailure: function() { alert('Something went wrong...') }
});
Here, two callbacks are passed in the hash −
onSuccess
onFailure
Any of the above two call is called accordingly based on the status of the response. The first parameter passed to both is the native xmlHttpRequest object from which you can use its responseText and responseXML properties, respectively.
You can specify both callbacks, one or none - it's up to you. Other available callbacks are −
onUninitialized
onLoading
onLoaded
onInteractive
onComplete
onException
They all match a certain state of the xmlHttpRequest transport, except for onException, which fires when there was an exception while dispatching other callbacks.
NOTE − The onUninitialized, onLoading, onLoaded, and onInteractive callbacks are not implemented consistently by all browsers. In general, it's best to avoid using these.
Ajax object provides all the necessary methods to handle AJAX requests and responses in an easy way. Here is a complete list of all the methods related to AJAX.
NOTE − Make sure you at least have the version 1.6 of prototype.js.
This is not a method but details all core options shared by all AJAX requesters and callbacks.
Periodically performs an AJAX request and updates a container's contents based on the response text.
Initiates and processes an AJAX request.
A repository of global listeners notified about every step of Prototype-based AJAX requests.
The object passed as the first argument of all Ajax requests callbacks.
Performs an AJAX request and updates a container's contents based on the response text.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
How to count the total number of frames in Selenium with python?

We can count the total number of frames in a page in Selenium with the help of find_elements method. While working on frames, we will always find the tagname in the html code and its value should be frame/iframe.
This characteristic is only applicable to frames on that particular page and to no other types of UI elements like edit box, link and so on.
To retrieve all the elements with the tagname as frame or iframe we will use find_elements_by_tag_name() method. This method returns a list of web elements with the type of tagname specified in the method argument. In case there are no matching elements, an empty list will be returned.
After the list of frames are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure.
Finally this length is printed on the console.
driver.find_elements_by_tag_name("frame")
Code Implementation to count frames.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
#to get the list of frames present on the web page
l = driver.find_elements_by_tag_name('frame')
#print the count with the len method on console
print(len(l))
#to close the browser
driver.quit()
Change color of button in Python - Tkinter - GeeksforGeeks

23 Dec, 2020
Prerequisite: Creating a button in tkinter, Python GUI – tkinter
In this article, we are going to write a Python script to change the color of the button in Tkinter. It can be done with two methods:
Using bg properties.
Using activebackground properties.
Example 1: using bg properties.
We can change the button background color with bg properties, The default color of the button is grey but here we are going to change.
Python3
# import tkinter module from tkinter import *     # create a tkinter windowmaster = Tk()    # Open window having dimension 200x100master.geometry('200x100')      # Create a Buttonbutton = Button(master,                 text = 'Submit',                 bg='blue').pack()    master.mainloop()
Output:
Example 2: Using activebackground properties.
These properties will change the button background color while clicking the button.
Python3
# import tkinter module from tkinter import *     # create a tkinter windowmaster = Tk()    # Open window having dimension 200x100master.geometry('200x100')      # Create a Buttonbutton = Button(master,                 text = 'Submit',                 bg='white',                 activebackground='blue').pack()      master.mainloop()
Output:
Python-tkinter
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()
Algorithms | Analysis of Algorithms | Question 19 - GeeksforGeeks

28 Jun, 2021
Consider the following two functions. What are time complexities of the functions?
int fun1(int n){    if (n <= 1) return n;    return 2*fun1(n-1);}
int fun2(int n){    if (n <= 1) return n;    return fun2(n-1) + fun2(n-1);}
(A) O(2^n) for both fun1() and fun2()(B) O(n) for fun1() and O(2^n) for fun2()(C) O(2^n) for fun1() and O(n) for fun2()(D) O(n) for both fun1() and fun2()Answer: (B)Explanation: Time complexity of fun1() can be written asT(n) = T(n-1) + C which is O(n)
Time complexity of fun2() can be written asT(n) = 2T(n-1) + C which is O(2^n)
Quiz of this Question
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 3
Algorithms | Sorting | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
GATE | GATE MOCK 2017 | Question 23
Algorithms | Graph Traversals | Question 1
Algorithms | Graph Traversals | Question 12
Algorithms | Bit Algorithms | Question 3
Algorithms | Sorting | Question 6
Data Structures and Algorithms | Set 38
Algorithms | Bit Algorithms | Question 2
Python Number choice() Method

Python number  method choice() returns a random item from a list, tuple, or string.
Following is the syntax for choice() method −
choice( seq )

Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.
seq − This could be a list, tuple, or string.
seq − This could be a list, tuple, or string.
This method returns a random item.
The following example shows the usage of choice() method.
#!/usr/bin/python
import random

print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9])
print "choice('A String') : ", random.choice('A String')
When we run above program, it produces following result −
choice([1, 2, 3, 5, 9]) :  2
choice('A String') :  n


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Print all subsets of given size of a set in C++

In this problem, we are given an array and we have to print all the subset of a given size r that can be formed using the element of the array.
Let’s take an example to understand the topic better −
Input:
array = {3, 5, 6}
r = 2
Output:
3 5
3 6
5 6
In this problem, we will have to find all the combinations of the numbers of the array. And exclude those r bit combinations which are already in the set.
 Live Demo
#include <iostream>
using namespace std;
void printSubset(int arr[], int n, int r, int index, int data[], int i);
int main(){
   int arr[] = {3 , 5, 6};
   int r = 2;
   cout<<"The sets are : ";
   int n = sizeof(arr) / sizeof(arr[0]);
   int data[r];
   printSubset(arr, n, r, 0, data, 0);
   return 0;
}
void printSubset(int arr[], int n, int r, int index, int data[], int i){
   if (index == r) {
      for (int j = 0; j < r; j++)
         cout<<data[j]<<" ";
      cout<<endl;
      return;
   }
   if (i >= n)
      return;
   data[index] = arr[i];
   printSubset(arr, n, r, index + 1, data, i + 1);
   printSubset(arr, n, r, index, data, i + 1);
}
The sets are −
3 5
3 6
5 6
How to visualize 95% confidence interval in Matplotlib?

To visualize 95% confidence interval in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data sets.
Create x and y data sets.
Get the confidence interval dataset.
Get the confidence interval dataset.
Plot the x and y data points using plot() method.
Plot the x and y data points using plot() method.
Fill the area within the confidence interval range.
Fill the area within the confidence interval range.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np

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

x = np.arange(0, 10, 0.05)
y = np.sin(x)

# Define the confidence interval
ci = 0.1 * np.std(y) / np.mean(y)

plt.plot(x, y, color='black', lw=7)

plt.fill_between(x, (y-ci), (y+ci), color='blue', alpha=0.5)

plt.show()
How to find a number using Pythagoras Theorem using C#?

Firstly, set the first two numbers −
double val1, val2;
val1 = 10;
val2 = 5;
Now use the Math.Sqrt function to use Pythagoras Theorem.
res = Math.Sqrt(val1 * val1 + val2 * val2);
 Live Demo
using System;
public class Program {
   public static void Main(string[] args) {
      double val1, val2, res;
      val1 = 10;
      val2 = 5;
      res = Math.Sqrt(val1 * val1 + val2 * val2);

      Console.WriteLine("Result = {0}", res);
      Console.ReadLine();
   }
}
Result = 11.1803398874989
ASP.NET - Calendars

The calendar control is a functionally rich web control, which provides the following capabilities:
Displaying one month at a time
Selecting a day, a week or a month
Selecting a range of days
Moving from month to month
Controlling the display of the days programmatically
The basic syntax of a calendar control is:
<asp:Calender ID = "Calendar1" runat = "server">
</asp:Calender>
The calendar control has many properties and events, using which you can customize the actions and display of the control. The following table provides some important properties of the Calendar control:
The Calendar control has the following three most important events that allow the developers to program the calendar control. They are:
Putting a bare-bone calendar control without any code behind file provides a workable calendar to a site, which shows the months and days of the year. It also allows navigation to next and previous months.
Calendar controls allow the users to select a single day, a week, or an entire month. This is done by using the SelectionMode property. This property has the following values:
The syntax for selecting days:
<asp:Calender ID = "Calendar1" runat = "server" SelectionMode="DayWeekMonth">
</asp:Calender>
When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears for selecting the week, and a >> symbol appears to the left of the days name for selecting the month.
The following example demonstrates selecting a date and displays the date in a label:
The content file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="calendardemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>
   
   <body>
      <form id="form1" runat="server">
      
         <div>
            <h3> Your Birthday:</h3>
            <asp:Calendar ID="Calendar1" runat="server  SelectionMode="DayWeekMonth" onselectionchanged="Calendar1_SelectionChanged">
            </asp:Calendar>
         </div>
         
         <p>Todays date is: 
            <asp:Label ID="lblday" runat="server"></asp:Label>
         </p>
         
         <p>Your Birday is: 
            <asp:Label ID="lblbday" runat="server"></asp:Label>
         </p>
         
      </form>
   </body>
</html>
The event handler for the event SelectionChanged:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
   lblday.Text = Calendar1.TodaysDate.ToShortDateString();
   lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}
When the file is run, it should produce the following output:

    51 Lectures 
     5.5 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    42 Lectures 
     18 hours 

 SHIVPRASAD KOIRALA

    57 Lectures 
     3.5 hours 

 University Code

    40 Lectures 
     2.5 hours 

 University Code

    138 Lectures 
     9 hours 

 Bhrugen Patel
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Form elements
Tryit: HTML fieldset element
Difference Between Constructor and Destructor

In this post, we will understand the difference between constructor and destructor.
It helps allocate memory to an object.
It helps allocate memory to an object.
It can take arguments.
It can take arguments.
It is called automatically when an object is created.
It is called automatically when an object is created.
It allows an object to initialize a value before it is used.
It allows an object to initialize a value before it is used.
They are called in the successive order of their creation.
They are called in the successive order of their creation.
There can be multiple constructors in a single class.
There can be multiple constructors in a single class.
The copy constructor allows the constructor to declare and initialize an object from another object.
The copy constructor allows the constructor to declare and initialize an object from another object.
It can be overloaded.
It can be overloaded.
class_name( arguments if any )
{
};
It deallocates the memory of an object.
It deallocates the memory of an object.
It doesn’t take any argument.
It doesn’t take any argument.
It is called automatically when the block is exited or when the program terminates.
It is called automatically when the block is exited or when the program terminates.
They allow objects to execute code when it is being destroyed.
They allow objects to execute code when it is being destroyed.
They are called in the reverse order of their creation.
They are called in the reverse order of their creation.
There is a single destructor in a class.
There is a single destructor in a class.
Destructor can’t be overloaded.
Destructor can’t be overloaded.
~ class_name( no arguments )
{
};
Can we override a start() method in Java?

Yes, we can override the
start() method of a Thread class in Java. We must call the super.start() method to create a new thread and need to call run() method in that newly created thread. If we call the run() method directly from within our start() method, it can be executed in the actual thread as a normal method, not in a new thread.
public class ThreadTest {
   public static void main(String[] args) {
      MyThread t = new MyThread();
      t.start();
   }
}
class MyThread extends Thread {
   @Override
   public void start() { // overriding the start() method
      System.out.println("Overriding a start() method");
      super.start();
   }
   @Override
   public void run() {
      System.out.println("run() method ");
   }
}
Overriding a start() method
run() method
Python | Check if tuple exists as dictionary key - GeeksforGeeks

29 Oct, 2019
Sometimes, while working with dictionaries, there is a possibility that it’s keys be in form of tuples. This can be a sub problem to some of web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using in operatorThis is the most recommened and Pythonic way to perform this particular task. It checks for particular tuple and returns True in case of it occurs or False if doesn’t.
# Python3 code to demonstrate working of# Check if tuple exists as dictionary key# using in operator  # initialize dictionarytest_dict = { (3, 4) : 'gfg', 6 : 'is', (9, 1) : 'best'}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # initialize target tuple tar_tup = (3, 4)  # Check if tuple exists as dictionary key# using in operatorres = tar_tup in test_dict  # printing resultprint("Does tuple exists as dictionary key ? : " + str(res))
The original dictionary : {(3, 4): 'gfg', (9, 1): 'best', 6: 'is'}
Does tuple exists as dictionary key ? : True

 
Method #2 : Using get()We can use dictionary’s get(), which searches for key in dictionary and if it doesn’t get it, it returns a None. This can be extended in case of tuple keys as well.
# Python3 code to demonstrate working of# Check if tuple exists as dictionary key# using get()  # initialize dictionarytest_dict = { (3, 4) : 'gfg', 6 : 'is', (9, 1) : 'best'}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # initialize target tuple tar_tup = (3, 5)  # Check if tuple exists as dictionary key# using get()res = Falseres = test_dict.get(tar_tup) != None   # printing resultprint("Does tuple exists as dictionary key ? : " + str(res))
The original dictionary : {(3, 4): 'gfg', (9, 1): 'best', 6: 'is'}
Does tuple exists as dictionary key ? : False

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

28 Jun, 2021
An operating system uses the Banker’s algorithm for deadlock avoidance when managing the allocation of three resource types X, Y, and Z to three processes P0, P1, and P2. The table given below presents the current system state. Here, the Allocation matrix shows the current number of resources of each type allocated to each process and the Max matrix shows the maximum number of resources of each type required by each process during its execution.
There are 3 units of type X, 2 units of type Y and 2 units of type Z still available. The system iscurrently in a safe state. Consider the following independent requests for additional resources in thecurrent state:
REQ1: P0 requests 0 units of X,  
      0 units of Y and 2 units of Z
REQ2: P1 requests 2 units of X, 
      0 units of Y and 0 units of Z
Which one of the following is TRUE?(A) Only REQ1 can be permitted.(B) Only REQ2 can be permitted.(C) Both REQ1 and REQ2 can be permitted.(D) Neither REQ1 nor REQ2 can be permittedAnswer: (B)Explanation: This is the current safe state.
 
Now, if the request REQ1 is permitted, the state would become :
 
Now, with the current availability, we can service the need of P1. The state would become :
 
With the resulting availability, it would not be possible to service the need of either P0 or P2, owing to lack of Z resource.
Therefore, the system would be in a deadlock.
⇒ We cannot permit REQ1.
 
Now, at the given safe state, if we accept REQ2 :
 
With this availability, we service P1 (P2 can also be serviced). So, the state is :
 
With the current availability, we service P2. The state becomes :
 
Finally, we service P0. The state now becomes :
The state so obtained is a safe state. ⇒ REQ2 can be permitted.
So, only REQ2 can be permitted.
Hence, B is the correct choice.
 
Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Arithmetic Operators in LISP - GeeksforGeeks

21 Sep, 2021
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
There are 7 arithmetic operators in LISP that are listed in the below table:
Example 1: LISP Program that demonstrates arithmetic operators
Lisp
;set value 1 to 300; set value 2 to 600(setq val1 300)(setq val2 600)  ;addition operation(print (+ val1 val2))  ;subtraction operation(print (- val1 val2))  ;multiplication operation(print (* val1 val2))  ;division operation(print (/ val1 val2))  ;modulus operation(print (MOD val1 val2))  ;increment a by 10(print (incf val1 val2))  ;decrement b by 20(print (decf val1 val2))
Output:
900  
-300  
180000  
1/2  
300  
900  
300 
Example 2:
Lisp
;set value 1 to 30; set value 2 to 15(setq val1 30)(setq val2 15)  ;addition operation(print (+ val1 val2))  ;subtraction operation(print (- val1 val2))  ;multiplication operation(print (* val1 val2))  ;division operation(print (/ val1 val2))  ;modulus operation(print (MOD val1 val2))  ;increment a by 10(print (incf val1 val2))  ;decrement b by 20(print (decf val1 val2))
Output:
45  
15  
450  
2  
0  
45  
30 
LISP-Basics
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cond Construct in LISP
Data Types in LISP
LISP - Comparison Operators on Characters & Strings
Packages in LISP
Mapping Functions in LISP
Symbols in LISP
Case Construct in LISP
Do Construct in LISP
Property Lists in LISP
Naming Conventions in LISP
Python | Find minimum of each index in list of lists - GeeksforGeeks

06 May, 2019
Sometimes, we are encountered with such problem in which we need to find the minimum of each column in a matrix i.e minimum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved.
Examples:
Input : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
Output : [1, 3, 2] 
 
Input : [[3, 2, 8], [5, 3, 5], [9, 3, 1]] 
Output : [3, 2, 1]

Method #1 : Using min() + list comprehension + zip()
The combination of above methods are required to solve this particular problem. The min function is used to get the required minimum value and zip function provides the combination of like indices and then list is created using list comprehension.
# Python3 code to demonstrate# Minimum index value# using min() + list comprehension + zip()  # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]  # printing original listprint("The original list : " + str(test_list))  # using min() + list comprehension + zip()# Minimum index valueres = [min(idx) for idx in zip(*test_list)]  # print resultprint("The Minimum of each index list is : " + str(res))
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Minimum of each index list is : [1, 3, 2]

 
Method #2 : Using map() + min() + zip()
This works in almost similar way as the above method, but the difference is just that we use map function to build the min element list rather than using list comprehension.
# Python3 code to demonstrate# Minimum index value# using min() + map() + zip()  # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]  # printing original listprint("The original list : " + str(test_list))  # using min() + map() + zip()# Minimum index valueres = list(map(min, zip(*test_list)))  # print resultprint("The Minimum of each index list is : " + str(res))
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Minimum of each index list is : [1, 3, 2]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Auto select option from Dropdown in ReactJS - GeeksforGeeks

18 Jan, 2021
Auto Select option from Dropdown means without forcing the user to click on any options, the option value is auto-populated. Material UI for React has this component available for us and it is very easy to integrate. We can auto-select the options from Dropdown using the following approach.
Creating React Application And Installing Module:
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
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';  const App = () => {    // Sample options for dropdown  const myOptions = ['One', 'Two', 'Three', 'Four', 'Five'];    return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        style={{width:500}}        autoSelect        options={myOptions}        renderInput={(params) => (          <TextField {...params}            variant="outlined"            label="AutoSelect Dropdown"           />        )}      />    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Now over any option and click outside the dropdown, the option value will be auto-populated. This is how auto select works in ReactJS for dropdown.
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Spinning Ball Animation with Glow Effect using CSS - GeeksforGeeks

23 Feb, 2021
Spinning ball animation can be easily created using the transform property to rotate the ball. The animation iteration count is applied as infinite to get the never-ending spinning animation. To get the glowing effect,  box-shadow is used.
STEPS:
Create an HTML file with the name index.html.
Create a div element in the index.html file and give a class name ball.
Add style to this class name.
Create an animation named spinball using @keyframes rule. Use transform property to rotate the ball.
Apply 2 color inset combination in the box-shadow property to get the glowing spinning effect.
Spinning speed can be adjusted by changing the animation duration.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible"             content="IE=edge">      <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <title>Spinning Ball Animation</title>      <style>        * {            background-color: black;        }                  .ball {            height: 40px;            width: 40px;            border-radius: 100px;            position: fixed;            top: 50vh;            left: 50vw;            animation: spinBall 0.13s linear infinite;            box-shadow: inset 0 0 18px #fff,                 inset 6px 0 18px violet,                 inset -6px 0 18px #0ff,                 inset 6px 0 30px violet,                 inset -6px 0 30px #0ff,                 0 0 18px #fff, -4px                 0 18px violet, 4px 0 18px #0ff;        }                  @keyframes spinBall {            100% {                transform: rotate(360deg);            }        }    </style></head>  <body>    <div class="ball"></div></body>  </html>
Output:
Spinning Ball Animation
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Questions
HTML-Questions
Technical Scripter 2020
CSS
HTML
Technical Scripter
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 ?
Simple Tic-Tac-Toe Game using JavaScript
CSS Introduction
HTML Course | Structure of an HTML Document
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
HTML | <img> align Attribute
pmap command in Linux with Examples - GeeksforGeeks

23 Apr, 2019
The pmap command in Linux is used to display the memory map of a process. A memory map indicates how memory is spread out.
Syntax:
pmap [options] pid [...]
Example:
Options:
-x : This option is used to display the memory map in an extended format.Example:pmap -x 9466
Example:
pmap -x 9466
-p : This option is used to display the full path to the files.Example:pmap -p 9466
Example:
pmap -p 9466
-d : This option is used to display the device format.Example:pmap -d 9466
Example:
pmap -d 9466
-q : This option is used to ignore the column names while displaying the report of the memory map.Example:pmap -q -d 9466
Example:
pmap -q -d 9466
-A : This option is used to display results to the given range. Notice that the low and high arguments are single string separated with a comma.Example:pmap -A 000055a5908f8000, 00007fd264ed2000 11747
Example:
pmap -A 000055a5908f8000, 00007fd264ed2000 11747
-XX : This option is used to display everything the kernel provides.Example:pmap -xx [PID]
Example:
pmap -xx [PID]
-n : This option is used to create a new configuration.Example:pmap -n
Example:
pmap -n
-c : This option is used to read the default configuration.Example:pmap -c [PID]
Example:
pmap -c [PID]
-h : This option is used to display help text.pmap -h
pmap -h
-v : This option is used to display the version information and exit.pmap -v
pmap -v
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Create Boxplot of Multiple Column Values using ggplot2 in R - GeeksforGeeks

28 Nov, 2021
In this article, we will discuss how to create a boxplot of multiple column values using ggplot2 in R Programming Language.
A dataframe can be created by containing values organized in the form of rows and columns. The values may belong to different data types. The reshape2 package is used to aggregate data by using the functions, melt and cast. The library can be installed and loaded into the working space using the following command : 
install.packages("reshape2")
The melt method in R is used to melt an R object, say a dataframe into a form suitable for easy casting.
Syntax:
melt(data, id.vars, measure.vars)
Parameters:
data – The data set to melt
id.vars –  Id variables.
measure.vars – Measured variables.
The ggplot method in this package is used to declare and define a ggplot object. It takes as input a dataframe and defines a set of aesthetic mappings to be intended for the plot. 
ggplot(data = NULL, mapping = aes())
Parameters: 
data – The dataframe to be used as input in the ggplot method
mapping – Default list of aesthetic mappings to use for plot.
Additional components can be added to the ggplot object. The geom_boxplot() method is used to draw a boxplot() in R.
Syntax:
geom_boxplot( mapping = aes(x , y , color  ))
Example:
R
# importing required librarieslibrary(reshape2)library(ggplot2)  # creating a dataframedata_frame < - data.frame(col1=rep(1: 5, each=2),                          col2=1: 10,                          col3=11: 20,                          col4=21: 30)  # creating the modified dataframedata_mod < - melt(data_frame, id.vars='col1',                   measure.vars=c('col2', 'col3', 'col4'))# creating a plotp < - ggplot(data_mod) +geom_boxplot(aes(x=col1, y=value, color=variable))  # printing the plotprint(p)
Output
Example 2:
The following code snippet illustrates the plotting the values belonging to col2 and col3 on the x axis and its corresponding data items on the y axes : 
R
library(reshape2)library(ggplot2)  # creating a dataframedata_frame < - data.frame(col1=rep(1: 5, each=2),                          col2=1: 10,                          col3=11: 20,                          col4=21: 30)    # creating the modified dataframedata_mod < - melt(data_frame, id.vars='col1',                   measure.vars=c('col2', 'col3'))  # creating a plotp < - ggplot(data_mod) +geom_boxplot(aes(x=col1, y=value, color=variable))  # printing the plotprint(p)
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
Plot mean and standard deviation using ggplot2 in R
ROWS and COLUMNS Functions in Excel With Examples

01 Jun, 2021
In this article, we are going to see the details about Excel ROW, ROWS, COLUMN, COLUMNS functions, and their usages.
The ROW( ) function basically returns the row number for a reference. 
Syntax:
=ROW([reference])
Example :
=ROW(G100); Returns 100 as output 
as G100 is in the 100th row in the Excel sheet
If we write no argument inside the ROW( ) it will return the row number of the cell in which we have written the formula.
Here the following returns are achieved:
=ROW(A67) // Returns 67
=ROW(B4:H7) // Returns 4
It is the extended version of the ROW function. ROWS function is used to return the number of rows in a cell range. 
Syntax:
=ROWS([array])
Example :
=ROWS(A2:A11) // Returns 10 as there are ten rows
It is important to note that writing the column name is trivial here. We can also write :
=ROWS(2:13) // Returns 12
The column function usually returns the column number of a reference. There are 16,384 columns in Excel from the 2007 version. It returns the value 1 to 16,384.
Syntax:
=COLUMN([reference])
Example :
=COLUMN(E20) // Returns 5 as output
as E is the fifth column in the Excel sheet
Last Column of Excel
Similar to the ROW function, the argument is not mandatory. If we don’t write any argument, it will return the index of the column in which the formula is written.
It is the extended version of the COLUMN( ). It returns the number of columns for a given cell range.
Syntax:
=COLUMNS([array])
Example :
=COLUMNS(B12:E12) // Returns 4 as output as
there are 4 columns in the given range
It is important to note that writing the row number is trivial here. We can also write :
=COLUMNS(B:E) // Returns 4
We can use the ROWS( ) and COLUMNS( ) in array formulas using SMALL( ), LARGE( ), VLOOKUP( ) functions in Excel.
Example :
The smallest value is returned to the provided cell range.
The largest value is returned to the provided cell range.
Say, we need to find the number of days needed to complete Task number 5. 
The steps are :
Step 1: Choose any cell and write the name of the Task.
Step 2:  Beside that cell write the “Formula” as shown below to get the “Number of Days” need :
=VLOOKUP($F$3,$A$3:$B$13,COLUMNS($A$3:$B$13),0)
F3 : Reference of the Task T-5
A3:B13 : Cell range of the entire table for VLOOKUP to search
Step 3: Click Enter.
Now, it can be observed it returns 20 as output which is perfect as per the data set.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Create a Macro in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Python program to calculate square of a given number

12 Oct, 2021
Given a number, the task is to write a Python program to calculate square of the given number.
Examples:
Input: 4
Output: 16

Input: 3
Output: 9

Input: 10
Output: 100
We will provide the number, and we will get the square of that number as output. We have three ways to do so:
Multiplying the number to get the square (N * N)
Using Exponent Operator
Using math.pow() Method
Method 1: Multiplication
In this approach, we will multiply the number with one another to get the square of the number.
Example:
Python3
# Declaring the number.n = 4 # Finding square by multiplying them# with each othersquare = n * n # Printing squareprint(square)
Output:
16
Method 2: Using Exponent Operator
In this approach, we use the exponent operator to find the square of the number.
Exponent Operator: **
Return: a ** b will return a raised to power b as output.
Example:
Python3
# Declaring the number.n = 4 # Finding square by using exponent operator# This will yield n power 2 i.e. square of nsquare = n ** 2 # Printing squareprint(square)
Output:
16
Method 3: Using pow() Method
In this approach, we will use the pow() method to find the square of the number. This function computes x**y and returns a float value as output.
Syntax: float pow(x,y)
Parameters :
x : Number whose power has to be calculated.
y : Value raised to compute power. 
Return Value : Returns the value x**y in float.
Example:
Python3
# Declaring the number.n = 4 # Finding square by using pow method# This will yield n power 2 i.e. square of nsquare = pow(n, 2) # Printing squareprint(square)
Output:
16.0
snehashishghosh21
Picked
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Java Ternary Operator Examples

The ternary operator is also known as the conditional operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true: value if false
Following is an example −
Online Demo
public class Test {

   public static void main(String args[]) {
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}
This will produce the following result −
Value of b is : 30
Value of b is : 20