code-rag-bench/online-tutorials huggingface dataset:
Prototype - AJAX Request() Method

This AJAX method initiates and processes an AJAX request. This object is a general-purpose AJAX requester: it handles the life-cycle of the request, handles the boilerplate, and lets you plug in callback functions for your custom needs.
In the optional options hash, you can use any callback function like onComplete and/or onSuccess depending on your custom needs.
new Ajax.Request(url[, options]);

As soon as the object is created, it initiates the request, then goes on processing it throughout its life-cyle. The defined life-cycle is as follows −
Created
Initialized
Request sent
Response being received (can occur many times, as packets come in)
Response received, request complete
There is a set of callback functions, defined in Ajax Options,, which are triggered in the following order −
onCreate (this is actually a callback reserved to AJAX global responders))
onUninitialized (maps on Created)
onLoading (maps on Initialized)
onLoaded (maps on Request sent)
onInteractive (maps on Response being received)
onXYZ (numerical response status code), onSuccess or onFailure (see below)
onComplete
Depending on how your browser implements XMLHttpRequest, one or more callbacks may never be invoked.  In particular, onLoaded and onInteractive are not a 100% safe bet so far.  However, the global onCreate, onUninitialized and the two final steps are very much guaranteed.
new Ajax.Request
You can pull the brake on a running PeriodicalUpdater by simply calling its stop method. If you wish to re-enable it later, just call its start method. Both take no argument.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function SubmitRequest() {
            new Ajax.Request('/cgi-bin/ajax.cgi', {
               method: 'get',
               onSuccess: successFunc,
               onFailure:  failureFunc
            });
         }
         function successFunc(response) {
            if (200 == response.status) {
               alert("Call is success");
            }
            var container = $('notice');
            var content = response.responseText;
            container.update(content);
         }
         function failureFunc(response) {
            alert("Call is failed" );
         }
      </script>
   </head>

   <body>
      <p>Click submit button see how current notice changes.</p>
      <br />
 
      <div id = "notice">Current Notice</div>
      <br />
      <br />
      <input type = "button" value = "Submit" onclick = "SubmitRequest();"/>
   </body>
</html>
Here is the content of ajax.cgi.
#!/usr/bin/perl

print "Content-type: text/html\n\n";
print "This content is returned by AJAX cgi <br />";
print "Current Time " . localtime;

Click submit button see how current notice changes.
You can pass the parameters for the request as the parameters property in options −
new Ajax.Request('/some_url', {
   method: 'get',
   parameters: {company: 'example', limit: 12}
});

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
Why do we use import * and then ttk in TKinter?

In order to work with a tkinter application, we have to install and import the tkinter library in our environment. Generally, we import the tkinter library in the environment by using from tkinter import * command.
The significance of "import *" represents all the functions and built-in modules in the tkinter library. By importing all the functions and methods, we can use the inbuilt functions or methods in a particular application without importing them implicitly.
There are lots of widgets, functions, methods available in tkinter library which can be used to construct the component of a particular application. Tkinter provides the ttk package that is used to style the widget's property and its look and feel. In order to use the ttk package, we have to import it by typing the following code −;
from tkinter import ttk
In this particular example, we will create a functional application that will contain a button and a label widget.
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Define the function to close the window
def change_text():
   label.configure(text="Welcome")
#Create a label
label=Label(win, text= "Click the below button to Change this Text", font=('Aerial 20 bold'))
label.pack(pady=30)
#Create a button widget
button= ttk.Button(win, text="Commit",command=lambda:change_text())
button.pack()
win.mainloop()
Executing the above code will display a window that contains a button and a text label showing some text. When we click the button, it will change the message on the screen.
Now, click the "Commit" button to change the Label text.
Generate Random Integer Numbers in Java

In order to generate Random Integer Numbers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence.
Declaration − The java.util.Random.nextInt() method is declared as follows −
public int nextInt()
Let us see a program to generate random integer numbers in Java −
 Live Demo
import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random(); // creating Random object
      System.out.println(rd.nextInt());
   }
}
27100093
Note - The output might vary on Online Compilers.
How to select a subset of a DataFrame? - GeeksforGeeks

02 Jun, 2021
In this article, we are going to discuss how to select a subset of columns and rows from a DataFrame. We are going to use the nba.csv dataset to perform all operations.
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # display dataframedata.head()
 Output:
Below are various operations by using which we can select a subset for a given dataframe: 
Select a specific column from a dataframe
To select a single column, we can use a square bracket [ ]:
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # get a single columnsages = data["Age"] # display the columnages.head()
 Output:
Select multiple columns from a dataframe
We can pass a list of column names inside the square bracket [] to get multiple columns: 
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # get a single columnsname_sex = data[["Name","Age"]] # display the columnname_sex.head()
 Output:
Select a subset of rows from a dataframe
To select rows of people older than 25 years in the given dataset, we can put conditions within the brackets to select specific rows depending on the condition. 
Python3
# importing pandas libraryimport pandas as pd # reading csv filedata = pd.read_csv("nba.csv") # subset of dataframeabove_25 = data[data["Age"] > 35] # display subsetprint(above_25.head())
Output:
Select a subset of rows and columns combined
In this case, a subset of all rows and columns is made in one go, and select [] is not sufficient now. The loc or iloc operators are needed. The section before the comma is the rows you choose, and the part after the comma is the columns you want to pick by using loc or iloc. Here we select only names of people older than 25.
Python3
# importing pandas libraryimport pandas as pd # reading csv filedata = pd.read_csv("nba.csv") # subset of dataframeadults = data.loc[data["Age"] > 25, "Name"] # display susbsetprint(adults.head())
Output:
saurabh1990aror
Picked
Python pandas-dataFrame
Python-pandas
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
How semaphore is used to implement mutual exclusion?

A semaphore is a shared variable which is used to implement mutual exclusion between
system processes. It is mainly helpful to solve critical section problems and is a
technique to achieve process synchronization.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
P(s)
P(s)
CS
CS
V(s)
V(s)
Each of these operations is defined below −
Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue.
P(Semaphore s)
{
   s = s - 1;
   if (s < 0) {
      block(p);
   }
}
Signal(V) − When a process exists CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation.
V(Semaphore s)
{
   s = s + 1;
   if (s >= 0) {
      wakeup(p);
   }
}
Let us see how the lock variable is used to introduce the mutual exclusion −
It uses a similar mechanism as semaphore but at a time only one process can enter into a critical section and uses lock variable to implement synchronization as below −
while(lock != 0);
Lock = 1;
//critical section
Lock = 0;
It checks if the lock is equal to 0 then sets the lock to 1 indicating that lock is occupied and then
enters into CS. If the lock is not 0, then wait until it is available. When exiting CS set
lock back to 0 indicating lock is available and another process can enter into CS.
The difference between locks and semaphores is that locks can be implemented in user mode
whereas semaphores are implemented in kernel mode. Also, locks allow only one
process to enter into CS but semaphore can allow multiple processes to enter into CS. In
short, semaphore is the generalization of locks.
Concrete class in Java - GeeksforGeeks

16 Jan, 2019
A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or implement an interface as long as it implements all their methods. It is a complete class and can be instantiated.
In other words, we can say that any class which is not abstract is a concrete class.
Necessary condition for a concrete class: There must be an implementation for each and every method.
Example: The image below shows three classes Shape, Rectangle and Circle. Shape is abstract whereas Rectangle and Circle are concrete and inherit Shape. This is because Rectangle and Circle implement area() method.
Example 1: The below code shows a simple concrete class:
// Java program to illustrate concrete class  // Concrete Classclass Main {      // this method calculates    // product of two numbers    static int product(int a, int b)    {        return a * b;    }      // this method calculates    // sum of two numbers    static int sum(int a, int b)    {        return a + b;    }      // main method    public static void main(String args[])    {        int p = product(5, 10);        int s = sum(5, 10);          // print product        System.out.println("Product: " + p);          // print sum        System.out.println("Sum: " + s);    }}
Product: 50
Sum: 15

Example 2: The code below illustrates a concrete class which extends an abstract class. The method product() in interface X is implemented by class Product but it does not implement method sum(), therefore it has to be abstract. Whereas class Main implements the unimplemented method sum(), therefore there are no unimplemented methods. Hence, it is a concrete class.
// Java program to illustrate concrete class  // This is an interfaceinterface X {    int product(int a, int b);    int sum(int a, int b);}  // This is an abstract classabstract class Product implements X {      // this method calculates    // product of two numbers    public int product(int a, int b)    {        return a * b;    }}  // This is a concrete class that implementsclass Main extends Product {      // this method calculates    // sum of two numbers    public int sum(int a, int b)    {        return a + b;    }      // main method    public static void main(String args[])    {        Main ob = new Main();        int p = ob.product(5, 10);        int s = ob.sum(5, 10);          // print product        System.out.println("Product: " + p);          // print sum        System.out.println("Sum: " + s);    }}
Product: 50
Sum: 15

java-basics
Java-Classes
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
Set in Java
Getting details when a table is modified in SAP HANA DB

You can query SYS.M_TABLE_STATISTICS providing name of table and LAST MODIFY DATE. Here is the sample SQL query.
SELECT "ABC", "LAST_MODIFY_TIME"  
FROMSYS.M_TABLE_STATISTICS
ORDER BY “LAST_MODIFY_TIME" DESC
In above command, you need to replace “ABC” by your table name.
How can I simulate a print statement in MySQL?

To simulate a print statement in MySQL, you can use select statement. The syntax is as follows −
SELECT ‘anyStringValue’ as ’ ‘;
You can check the above syntax at the MySQL command line client.
To print a string.
mysql> select 'HELLO MYSQL' as ' ';
+-------------+
|             |
+-------------+
| HELLO MYSQL |
+-------------+
1 row in set (0.00 sec)
a) To print integer, use the following query −
mysql> select 23 as ' ';
+----+
|    |
+----+
| 23 |
+----+
1 row in set (0.00 sec)
b) To print float or double type, use the following query −
mysql> select 23.45 as ' ';
+-------+
|       |
+-------+
| 23.45 |
+-------+
1 row in set (0.00 sec)
How do I create an automatically updating GUI using Tkinter in Python?

GUI window has many controls such as labels, buttons, text boxes, etc. We may sometimes want the content of our controls such as labels to update automatically while we are viewing the window.
We can use after() to run a function after a certain time. For example, 1000 milliseconds mean 1 second. The function which we call continuously after a certain amount of time will update the text or any updation you want to happen.
We have a label on our window. We want the text of the label to update automatically after 1 second. To keep the example easy, suppose we want the label to show some number between 0 and 1000. We want this number to change after each 1 second.
We can do this by defining a function that will change the text of the label to some random number between 0 and 1000. We can call this function continuously after an interval of 1 second using the after().
from Tkinter import *
from random import randint
root = Tk()
lab = Label(root)
lab.pack()

def update():
   lab['text'] = randint(0,1000)
   root.after(1000, update) # run itself again after 1000 ms

# run first time
update()

root.mainloop()
This will automatically change the text of the label to some new number after 1000 milliseconds. You can change the time interval according to need. The update function can be modified to perform the required updation.
This line of the code performs the main function of recalling the function update().
The first parameter in root.after() specifies the time interval in milliseconds after which you want the function to be recalled.
The second parameter specifies the name of the function to be recalled.
CSS3 - Multi Columns

CSS3 supported multi columns to arrange the text as news paper structure.
Some of most common used multi columns properties as shown below −
column-count
Used to count the number of columns that element should be divided.
column-fill
Used to decide, how to fill the columns.
column-gap
Used to decide the gap between the columns.
column-rule
Used to specifies the number of rules.
rule-color
Used to specifies the column rule color.
rule-style
Used to specifies the style rule for column.
rule-width
Used to specifies the width.
column-span
Used to specifies the span between columns.
Below example shows the arrangement of text as new paper structure.
<html>
   <head>
      <style>
         .multi {
            /* Column count property */
            -webkit-column-count: 4;
            -moz-column-count: 4;
            column-count: 4;
            
            /* Column gap property */
            -webkit-column-gap: 40px; 
            -moz-column-gap: 40px; 
            column-gap: 40px;
            
            /* Column style property */
            -webkit-column-rule-style: solid; 
            -moz-column-rule-style: solid; 
            column-rule-style: solid;
         }
      </style>
   </head>

   <body>
   
      <div class = "multi">
         Tutorials Point originated from the idea that there exists a class 
         of readers who respond better to online content and prefer to learn 
         new skills at their own pace from the comforts of their drawing rooms.
         The journey commenced with a single tutorial on HTML in 2006 and elated 
         by the response it generated, we worked our way to adding fresh tutorials
         to our repository which now proudly flaunts a wealth of tutorials and 
         allied articles on topics ranging from programming languages to web 
         designing to academics and much more.
      </div>
      
   </body>
</html>
It will produce the following result −
For suppose, if user wants to make text as new paper without line, we can do this by removing style syntax as shown below −
.multi {
   /* Column count property */
   -webkit-column-count: 4;
   -moz-column-count: 4;
   column-count: 4;
   
   /* Column gap property */
   -webkit-column-gap: 40px; 
   -moz-column-gap: 40px; 
   column-gap: 40px;
}
It will produce the following result −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2005 | Question 57 - GeeksforGeeks

28 Jun, 2021
Consider the languages:
L1 = {wwR |w ∈ {0, 1}*}
L2 = {w#wR | w ∈ {0, 1}*}, where # is a special symbol
L3 = {ww |  w ∈  (0, 1}*)
Which one of the following is TRUE?(A) L1 is a deterministic CFL(B) L2 is a deterministic CFL(C) L3 is a CFL, but not a deterministic CFL(D) L3 is a deterministic CFLAnswer: (B)Explanation:  
L1: {ww^R | w belongs {0,1}*}This is a CFL but not a DCFL. It can be derived from the following grammarS -> aSa | bSb | epsilonBut it can’t be derived from any deterministic pushdown automaton, because there is no way to figure out where a word w ends and its reverse starts.
L2: {w#w^R | w belongs {0,1}*}This is a CFL, due to the same reason as described above. This is a deterministic CFL because we have a marker to help us find out the end of the word w and start of its reverse. Thus a PDA where all the alphabets are pushed until we get # and afterwards pop only if the top of the stack matches the current alphabet and reject otherwise – will derive L2.
L3: {ww | w belongs {0,1}*}This is not even a CFL. Above claim could be proved using pumping lemma –Consider a string z of the form (0^n 1^n 0^n 1^n).Assuming L3 is a CFL, and z obviously satisfies L3 – thus z should also satisfy pumping lemma.We will take n such that n = p, where p is the pumping length of L3, hence forcing our string to be of length greater than pumping length.Now, according to pumping lemma, there must exist u,v,w,x,y such that z = uvwxy, |vwx| <= p, |vx| > 0 and u{v^i}x{y^i}z belongs L3 for all i>=0.There doesn’t exist any such configuration of u,v,w,x,y such that u{v^0}x{y^0}z belongs L3. Hence z doesn’t satisfy pumping lemma. Hence L3 is not a CFL.
Considering all the above conclusions, only correct option comes out to be (B) L2 is a deterministic CFL.
Reference ;
https://courses.engr.illinois.edu/cs373/sp2013/Lectures/lec17.pdf
This solution is contributed by Vineet Purswani.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
Count digits in a factorial | Practice | GeeksforGeeks

Given an integer N. You have to find the number of digits that appear in its factorial, where factorial is defined as, factorial(N) = 1*2*3*4........*N and factorial(0) = 1.
 
Example 1:
Input:
N = 5
Output:
3
Explanation:
5! is 120 so there are 3
digits in 120

Example 2:
Input:
N = 100
Output:
7
Explanation:
100! is 3628800â€‹ so there are
7 digits in 3628800â€‹


Your Task: 
You don't need to read input or print anything. Your task is to complete the function facDigits() which takes an integer N as input parameter and returns the number of digits in factorial of N.
 
Expected Time Complexity: O(1)
Expected Space Complexity: O(1)
 
Constraints:
1 ≤ N ≤ 104
+1
yashchawla1163 months ago
Java Simple To Understand And Easy To Implement.
 
https://yashboss116.blogspot.com/2022/01/count-digits-in-factorial-geeks-for.html
 
+2
Shreyansh Kumar Singh1 year ago
Shreyansh Kumar Singh
Count of Digits in N!We know,log(a*b) = log(a) + log(b)∴ log( n! ) = log(1*2*3....... * n) = log(1) + log(2) + ........ +log(n)So, digits in N! = ceil (log(n!))Programming Approach:Run a loop from 2 to N,in each iteration add the value of log10(i) to countAt the end return the ceiling value of count.(Take extra care when i<2)
+1
Sumit Pardhiya1 year ago
Sumit Pardhiya
if(N<0)        return 0;        if(N<=1)        return 1;        double r=0;        for(int i=2;i<=N;i++)        {            r=r+log10(i);        }        return floor(r)+1;    }
0
Annanya Mathur1 year ago
Annanya Mathur
def facDigits(self,N):        r=1;        for i in range (1,N+1):            r=r*i        return math. floor(math. log (r,10)+1)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How do I change button size in Python Tkinter?

Tkinter Button widgets are used to create buttons that are necessary for an application. We can also add an event Object in the Button constructor and trigger it to perform some operation.
In order to customize the Button size, we can use the width and height property of the button widget.
In this example, we will create some buttons with different sizes,
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("600x250")

win.resizable(False, False)

Button(win, text="Button-1",height= 5, width=10).pack()
Button(win, text="Button-2",height=8, width=15).pack()
Button(win, text= "Button-3",height=10, width=30).pack()

win.mainloop()
Running the above code will display a window containing buttons of different sizes.
Python | Convert a list into a tuple - GeeksforGeeks

22 Jul, 2019
Given a list, write a Python program to convert the given list into a tuple.
Examples:
Input : [1, 2, 3, 4]
Output : (1, 2, 3, 4)

Input : ['a', 'b', 'c']
Output : ('a', 'b', 'c')

 Approach #1 : Using tuple(list_name).
Typecasting to tuple can be done by simply using tuple(list_name).
# Python3 program to convert a # list into a tupledef convert(list):    return tuple(list)  # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)

 Approach #2 :A small variation to the above approach is to use a loop inside tuple() .
# Python3 program to convert a # list into a tupledef convert(list):    return tuple(i for i in list)  # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)

 Approach #3 : Using (*list, )This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma (, ). This approach is a bit faster but suffers from readability.
# Python3 program to convert a # list into a tupledef convert(list):    return (*list, )  # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)

ManasChhabra2
Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python?
p5.js | curve() function

17 Jan, 2020
The curve() function is used to draws a curved line between two points given in the middle four parameters on the screen. The first two and last two parameters are used as a control point.
Syntax:
curve( x1, y1, x2, y2, x3, y3, x4, y4 )
or
curve( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4 )
Parameters:
Below examples illustrate the curve() function in CSS:
function setup() {         // Create canvas of given size    createCanvas(500, 300);         // Set the background of canvas    background('green'); }   function draw() {           // Use noFill() function to not fill the color    noFill();        // Set the stroke color    stroke('white');        // Use curve() function to create curve    curve(50, 50, 400, 50, 50, 250, 50, 50);      // Set the stroke color    stroke('blue');        // Use curve() function to create curve    curve(400, 50, 50, 250, 50, 50, 50, 50); } 
Output:
function setup() {         // Create canvas of given size    createCanvas(500, 300);         // Set the background of canvas    background('green'); }   function draw() {           // Use noFill() function to not fill the color    noFill();        // Set the stroke color    stroke('white');        // Use curve() function to create curve    curve(50, 50, 50, 200, 50, 10, 50, 250, 150, 50, 50, 50);      // Set the stroke color    stroke('blue');        // Use curve() function to create curve    curve(50, 200, 450, 50, 250, 100, 350, 250, 250, 450, 450, 400); } 
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to access nested object in ReactJS ?

21 May, 2021
The structure of an object in ReactJS can be nested many times and can get complicated quickly. If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object.
Example of a Nested object:
 var person = {
      "name":"Kapil",
      "age":27,
      "vehicles": {
         "car":"city 100",
         "bike":"ktm-duke",
         "plane":"lufthansa"
      }
     }
And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
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 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';  class App extends React.Component {    constructor(props) {    super(props);    this.state = {      person: {        name: {          first: "Kapil",          last: "Chhipa"        },        age: 23,        key1: {          key2: {            key3: {              val: "Welcome to GeeksforGeeks"            }          }        }      }    };  }    helper = (obj) => {    const values = Object.values(obj)      values.forEach(val =>      val && typeof val === "object" ?       this.helper(val) : this.addtoConsole(val))  }    addtoConsole = (val) => {    console.log(val)  }    render() {    return (      <div>        <button onClick={() => {          this.helper(this.state.person)        }}>click here</button>      </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:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2008 | Question 7

11 Jun, 2018
Consider the grammar
S → ABCc ∣ bc
BA → AB
Bb → bb
Ab → ab
Aa → aa
Which of the following sentences can be derived by this grammar?(A) abc(B) aab(C) abcc(D) abbcAnswer: (A)Explanation:Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2018 | Question 74
ISRO | ISRO CS 2013 | Question 21
ISRO | ISRO CS 2018 | Question 44
ISRO | ISRO CS 2011 | Question 56
ISRO | ISRO CS 2014 | Question 64
ISRO | ISRO CS 2007 | Question 16
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2017 - May | Question 14
ISRO | ISRO CS 2018 | Question 79
ISRO | ISRO CS 2013 | Question 54
What is the first class function in JavaScript ?

19 Sep, 2021
First-Class Function: A programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treat function as a first-class-citizens. This means that functions are simply a value and are just another type of object.
Example: Let us take an example to understand more about the first-class function.
Javascript
<script>    const Arithmetics = {        add: (a, b) => {            return `${a} + ${b} = ${a + b}`;        },        subtract: (a, b) => {            return `${a} - ${b} = ${a - b}`        },        multiply: (a, b) => {            return `${a} * ${b} = ${a * b}`        },        division: (a, b) => {            if (b != 0) return `${a} / ${b} = ${a / b}`;            return `Cannot Divide by Zero!!!`;        }      }      document.write(Arithmetics.add(100, 100) + "<br>");    document.write(Arithmetics.subtract(100, 7) + "<br>");    document.write(Arithmetics.multiply(5, 5) + "<br>");    document.write(Arithmetics.division(100, 5));</script>
Note: In the above example, functions are stored as a variable in an object.
 
Output:
100 + 100 = 200
100 - 7 = 93
5 * 5 = 25
100 / 5 = 20
Example 2:
Javascript
<script>    const Geek = (a, b) => {        return (a + " " + b);    }          document.write(Geek("Akshit", "Saxena"));</script>
Output:
Akshit Saxena
Blogathon-2021
javascript-basics
JavaScript-Questions
Picked
Blogathon
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Python program to convert XML to Dictionary
Modes of DMA Transfer
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property
How to get a File Extension in PHP ?

21 Jul, 2021
In this article, we will learn how to get the current file extensions in PHP.
Input  : c:/xampp/htdocs/project/home
Output : ""

Input  : c:/xampp/htdocs/project/index.php
Output : ".php"

Input  : c:/xampp/htdocs/project/style.min.css
Output : ".css"
Using $_SERVER[‘SCRIPT_NAME’]: 
$_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver. There is no other way that every web server will provide any of this information.
Syntax: 
 $_SERVER[‘SCRIPT_NAME’]
‘SCRIPT_NAME’ gives the path from the root to include the name of the directory.
Method 1: The following method uses the strpos() and substr() methods to print the values of the last occurrences.
PHP
<?phpfunction fileExtension($s) {  // strrpos() function returns the position  // of the last occurrence of a string inside  // another string.  $n = strrpos($s,".");     // The substr() function returns a part of a string.  if($n===false)     return "";  else    return substr($s,$n+1);}     // To Get the Current Filename.$currentPage= $_SERVER['SCRIPT_NAME']; //Function Callecho fileExtension($currentPage);?>
php
Method 2: The following method uses a predefined function pathinfo(). In the output, the “Name:” shows the name of the file and “Extension:” shows the file extension.
PHP code: 
PHP
<?php      // To Get the Current Filename.$path= $_SERVER['SCRIPT_NAME']; // path info function is used to get info// of The File Directory   // PATHINFO_FILENAME parameter in// pathinfo() gives File Name$name = pathinfo($path, PATHINFO_FILENAME);   // PATHINFO_EXTENSION parameter in pathinfo()// gives File Extension$ext  = pathinfo($path, PATHINFO_EXTENSION);   echo " Name: ", $name;echo "\n Extension: ", $ext; ?>
 Name: 001510d47316b41e63f337e33f4aaea4
 Extension: php
Method 3: The following code uses the predefined function parse_url() and pathinfo() for URLs.
PHP code: 
PHP
<?php  // This is sample url  $url ="http://www.xyz.com/dir/file.index.php?Something+is+wrong=hello";     // Here parse_url is used to return the  // components of a URL  $url = parse_url($url);     // path info function is used to get info  // of The File Directory     // PATHINFO_FILENAME parameter in pathinfo()  // gives File Name  $name = pathinfo($url['path'], PATHINFO_FILENAME);   // PATHINFO_EXTENSION parameter in pathinfo()  // gives File Extension  $ext  = pathinfo($url['path'], PATHINFO_EXTENSION);   echo " Name: ", $name;  echo "\n Extension: ", $ext;?>
 Name: file.index
 Extension: php
manikarora059
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two binary numbers

01 Jun, 2022
Given two binary numbers, write a Python program to compute their sum.
Examples:
Input:  a = "11", b = "1"
Output: "100"

Input: a = "1101", b = "100"
Output: 10001
Approach:
Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
Using inbuilt function: Calculate the result by using the inbuilt bin() and int() function.
Method 1: Naive Approach: 
The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
Python3
# Python program to add two binary numbers. # Driver code# Declaring the variablesa = "1101"b = "100"max_len = max(len(a), len(b))a = a.zfill(max_len)b = b.zfill(max_len) # Initialize the resultresult = '' # Initialize the carrycarry = 0 # Traverse the stringfor i in range(max_len - 1, -1, -1):    r = carry    r += 1 if a[i] == '1' else 0    r += 1 if b[i] == '1' else 0    result = ('1' if r % 2 == 1 else '0') + result     # Compute the carry.    carry = 0 if r < 2 else 1 if carry != 0:    result = '1' + result print(result.zfill(max_len))
10001

Output:
10001
Method 2: Using inbuilt functions:
We will first convert the binary string to a decimal using int() function in python. The int() function in Python and Python3 converts a number in the given base to decimal. Then we will add it and then again convert it into a binary number using bin() function.
Example 1:
Python3
# Python program to add two binary numbers. # Driver code# Declaring the variablesa = "1101"b = "100" # Calculating binary value using functionsum = bin(int(a, 2) + int(b, 2)) # Printing resultprint(sum[2:])
10001

Example 2:
Python3
# Python program to add two binary numbers. # Driver codeif __name__ == "__main__" :     # Declaring the variables    a = "1101"    b = "100"         # Calculating binary sum by using bin() and int()    binary_sum = lambda a,b : bin(int(a, 2) + int(b, 2))         # calling binary_sum lambda function    print(binary_sum(a,b)[2:])         # This code is contributed by AnkThon
10001

ankthon
school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to find sum of perfect square elements in an array using pointers.

Write a program to find the sum of perfect square elements in an array by using pointers.
Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output.
For example,
Input= 1, 2, 3, 4, 5, 9,10,11,16
The perfect squares are 1, 4, 9,16.
Sum = 1 + 4 + 9 +16 = 30
Output: 30
Refer an algorithm given below to find the sum of perfect square elements in an array by using pointers. 
Step 1 − Read number of elements in array at runtime. 
Step 2 − Input the elements. 
Step 3 − Declare and initialize the sum=0 
Step 4 − Declare a pointer variable. 
Step 5 − Check, whether the array element is a perfect square or not by using a pointer variable 
Step 6 − If it is a perfect square, then, compute sum=sum+number 
Step 7 − Return sum.
Following is the C program to find the sum of perfect square elements in an array by using pointers −
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int sumPositive(int n,int *a){
   int i,sum=0,m;
   for(i=0;i<n;i++){
      m=sqrt(*(a+i));
      if(pow(m,2)==*(a+i)){
         sum+=*(a+i);
      }
   }
   return sum;
}
int main(){
   int i,*a,n;
   printf("Enter the size of array:\n");
   scanf("%d",&n);
   a=(int*)malloc(n*sizeof(int));
   printf("Enter the elements of array:\n");
   for(i=0;i<n;i++){
      scanf("%d",a+i);
   }
   printf("Sum of positive square elements is %d",sumPositive(n,a));
   return 0;
}
When the above program is executed, it produces the following output −
Enter the size of array:
10
Enter the elements of array:
1
2
3
4
5
6
7
8
9
10
Sum of positive square elements is 14
Inter thread communication in Java

If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
 Live Demo
class Chat {
   boolean flag = false;

   public synchronized void Question(String msg) {
      if (flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(msg);
      flag = true;
      notify();
   }

   public synchronized void Answer(String msg) {
      if (!flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

      System.out.println(msg);
      flag = false;
      notify();
   }
}

class T1 implements Runnable {
   Chat m;
   String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

   public T1(Chat m1) {
      this.m = m1;
      new Thread(this, "Question").start();
   }

   public void run() {
      for (int i = 0; i < s1.length; i++) {
         m.Question(s1[i]);
      }
   }
}

class T2 implements Runnable {
   Chat m;
   String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

   public T2(Chat m2) {
      this.m = m2;
      new Thread(this, "Answer").start();
   }

   public void run() {
      for (int i = 0; i < s2.length; i++) {
         m.Answer(s2[i]);
      }
   }
}
public class TestThread {
   public static void main(String[] args) {
      Chat m = new Chat();
      new T1(m);
      new T2(m);
   }
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Above example has been taken and then modified from https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java
How to measure elapsed time in nanoseconds with Java?

In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −
The nanoTime() method returns the current time in nano seconds. To find the elapsed time for the execution of a method in nano seconds −
Retrieve the current time using the nanoTime() method.
Execute the desired method.
Again, retrieve the current time using the nanoTime() method.
Finally, Find the difference between the end value and the start value.
Live Demo
public class Example {
   public void test(){
      int num = 0;
      for(int i=0; i<=50; i++){  
         num =num+i;
         System.out.print(num+", ");
      }      
   }
   public static void main(String args[]){  
      //Start time
      long begin = System.nanoTime();
      //Starting the watch
      new Example().test();
      //End time
      long end = System.nanoTime();          
      long time = end-begin;
      System.out.println();
      System.out.println("Elapsed Time: "+time);
   }
}
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,
Elapsed Time: 1530200
JavaScript | Object.fromEntries() Method - GeeksforGeeks

22 Dec, 2021
The Object.fromEntries() method in JavaScript is standard built-in objects which is used to transforms a list of key-value pairs into an object. This method returns a new object whose properties are given by the entries of the iterable
Syntax:
Object.fromEntries( iterable )
Parameters: This method accept single parameter iterable which holds an iterable such as Array or Map or other objects implementing the iterable protocol.
Return value: This method always returns a new object whose properties are given by the entries of the iterable.
Below examples illustrate the Object.fromEntries() method in JavaScript:
Example 1: Conversion of a Map into an Object.
const map1 = new Map([ ['big', 'small'], [1, 0] ]);const geek = Object.fromEntries(map1);console.log(geek);   const map2 = new Map(    [['Geek1', 'Intern'],    ['stipend', 'Works basis']]);const geek1 = Object.fromEntries(map2);console.log(geek1); 
Output:
Object { 1: 0, big: "small" }
Object { Geek1: "Intern", stipend: "Works basis" }
Example 2: Conversion of a Array into an Object.
const arr1 = [ ['big', 'small'], [1, 0], ['a', 'z' ]];const geek = Object.fromEntries(arr1);console.log(geek);  const arr2 = [ ['Geek1', 'Intern'], ['stipend', 'Works basis'] ];const geek1 = Object.fromEntries(arr2);console.log(geek1);
Output:
Object { 1: 0, big: "small", a: "z" }
Object { Geek1: "Intern", stipend: "Works basis" }
Example 3: Other Conversions
const params = 'type=Get_the Value&geekno=34&paid=10';const searchParams = new URLSearchParams(params);  console.log(Object.fromEntries(searchParams));  const object1 = { val1: 112, val2: 345, val3: 76 };const object2 = Object.fromEntries(  Object.entries(object1)  .map(([ key, val ]) => [ key, val * 3 ]));console.log(object2); 
Output:
Object { type: "Get_the Value", geekno: "34", paid: "10" }
Object { val1: 336, val2: 1035, val3: 228 }
Supported Browsers: The browsers supported by Object.fromEntries() method are listed below:
Google Chrome 73 and above
Firefox 63 and above
Opera 60 and above
Safari 12.1 and above
Edge 79 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
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 PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?