code-rag-bench/online-tutorials huggingface dataset:
How to do basic form validation using JavaScript?

JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. 
Basic form validation includes the form to be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
You can try to run the following code to implement basic form validation in JavaScript −
<html>
   <head>
      <title>Form Validation</title>
      <script>
         // Form validation
         function validate(){
            if( document.myForm.Name.value == "" ) {
               alert( "Please provide your name!" );
               document.myForm.Name.focus() ;
               return false;
            }
            if( document.myForm.EMail.value == "" ){
               alert( "Please provide your Email!" );
               document.myForm.EMail.focus() ;
               return false;
            }
            if( document.myForm.Zip.value == "" ||
                 isNaN( document.myForm.Zip.value ) ||
                 document.myForm.Zip.value.length != 5 )
            {
                alert( "Please provide a zip in the format #####." );
                document.myForm.Zip.focus() ;
                return false;
            }
            if( document.myForm.Country.value == "-1" ){
               alert( "Please provide your country!" );
               return false;
            }
            return( true );
         }
      </script>
   </head>

   <body>
      <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
         <table cellspacing = "2" cellpadding = "2" border = "1">
            <tr>
               <td align = "right">Name</td>
               <td><input type = "text" name = "Name" /></td>
            </tr>
            <tr>
               <td align = "right">EMail</td>
               <td><input type = "text" name = "EMail" /></td>
            </tr>
            <tr>
               <td align = "right">Zip Code</td>
               <td><input type = "text" name = "Zip" /></td>
            </tr>
            <tr>
               <td align = "right">Country</td>
               <td>
                  <select name = "Country">
                     <option value = "-1" selected>[choose yours]</option>
                     <option value = "1">USA</option>
                     <option value = "2">UK</option>
                     <option value = "3">INDIA</option>
                  </select>
               </td>
            </tr>
            <tr>
               <td align = "right"></td>
               <td><input type = "submit" value = "Submit" /></td>
            </tr>
         </table>
      </form>
   </body>
</html>
Scala List dropRight() method with example - GeeksforGeeks

26 Jul, 2019
The dropRight() method is utilized to find all the elements of the list except the last n elements.
Method Definition: def dropRight(n: Int): List[A]
Return Type: It returns all the elements of the list except the last n elements.
Example #1:
// Scala program of dropRight()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2)                  // Applying dropRight method        val res = m1.dropRight(3)                  // Displays output        println(res)          }}
List(1, 1, 3, 3, 3, 5)

Example #2:
// Scala program of dropRight()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2)                  // Applying dropRight method        val res = m1.dropRight(10)                  // Displays output        println(res)          }}
List()

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Tryit Editor v3.7

CSS Grid Item
Tryit: The grid-column property
How to read all excel files under a directory as a Pandas DataFrame ?

To read all excel files in a directory, use the Glob module and the read_excel() method.
Let’s say the following are our excel files in a directory −
Sales1.xlsx
Sales2.xlsx
At first, set the path where all the excel files are located. Get the excel files and read them using glob −
path = "C:\\Users\\amit_\\Desktop\\"

filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)
Next, use the for loop to iterate and read all the excels files in a specific directory. We are also using read_excel() −
for file in filenames:
   print("Reading file = ",file)
   print(pd.read_excel(file))
Following is the complete code −
import pandas as pd
import glob

# getting excel files from Directory Desktop
path = "C:\\Users\\amit_\\Desktop\\"

# read all the files with extension .xlsx i.e. excel 
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)

# for loop to iterate all excel files 
for file in filenames:
   # reading excel files
   print("Reading file = ",file)
   print(pd.read_excel(file))
This will produce the following output −
File names:['C:\\Users\\amit_\\Desktop\\Sales1.xlsx','C:\\Users\\amit_\\Desktop\\Sales2.xlsx']

Reading file = C:\Users\amit_\Desktop\Sales1.xlsx
          Car      Place   UnitsSold
0        Audi  Bangalore          80
1     Porsche     Mumbai         110
2  RollsRoyce       Pune         100

Reading file = C:\Users\amit_\Desktop\Sales2.xlsx
          Car      Place   UnitsSold
0         BMW      Delhi         95
1    Mercedes  Hyderabad         80
2  Lamborgini Chandigarh         80
Replace a substring with another string in Julia - replace() Method - GeeksforGeeks

23 Feb, 2021
The replace() is an inbuilt function in julia that is used to replace a word or character with the specified string or character. 
Syntax: 
replace(s::AbstractString, pattern=>Word; count::Integer)
Parameters:  
s::AbstractString: Specified string.
pattern=>Word: Pattern is searched from the given sentence and then that pattern is replaced with the word.
count::Integer: It is a number that is the count of specified pattern available in the sentence.
Returns: It returns a new sentence with replaced words.  Example 1: 
Python
# Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace("GFG is a CS portal.", "CS" => "Computer Science"))println(replace("GeeksforGeeks is a CS portal.", "GeeksforGeeks" => "GFG"))
Output:  
Example 2: 
Python
# Julia program to illustrate# the use of String replace() method # Getting a new sentence with replaced wordsprintln(replace("GFG Geeks.", "GFG" => "GeeksforGeeks", count = 1))println(replace("GFG Geeks GFG.", "GFG" => "GeeksforGeeks", count = 2))
Output:  
 
arorakashish0911
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Tuples in Julia
Storing Output on a File in Julia
while loop in Julia
Taking Input from Users in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
When to use yield instead of return in Python?

07 Jun, 2022
The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.
Let’s see with an example:
# A Simple Python program to demonstrate working# of yield  # A generator function that yields 1 for the first time,# 2 second time and 3 third timedef simpleGeneratorFun():    yield 1    yield 2    yield 3  # Driver code to check above generator functionfor value in simpleGeneratorFun():     print(value)
Output:
1
2
3
Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.
Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
# A Python program to generate squares from 1# to 100 using yield and therefore generator  # An infinite generator function that prints# next square number. It starts with 1def nextSquare():    i = 1      # An Infinite loop to generate squares     while True:        yield i*i                        i += 1  # Next execution resumes                 # from this point       # Driver code to test above generator # functionfor num in nextSquare():    if num > 100:         break        print(num)
Output:
1
4
9
16
25
36
49
64
81
100
julthep
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Difference between volatile and transient keywords in Java

16 Aug, 2020
Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. 
Before getting into the differences, let us first understand what each of them actually means.
Volatile:
The Volatile keyword is used to mark the JVM and thread to read its value from primary memory and not utilize cached value present in the thread stack. It is used in concurrent programming in java.
Java
class GFG extends Thread {      // using volatile    volatile boolean working = true;      // if non-volatile it will    // sleep in main and    // runtime error will coocur    public void run()    {        long count = 0;        while (working) {            count++;        }          System.out.println("Thread terminated."                           + count);    }      // Driver code    public static void main(String[] args)        throws InterruptedException    {        GFG test = new GFG();        test.start();        Thread.sleep(100);        System.out.println("After Sleeping in Main");        test.working = false;        test.join();        System.out.println("Working set to "                           + test.working);    }}
Output:  
Volatile Code Output
Transient:
The Transient keyword is used with the instance variable to eliminate it from the serialization process. During serialization, the value of the transient field or variable is not saved.
Java
import java.io.*;  class Test implements Serializable {      // Making Accesskey transient for security    transient String accessKey;      // Making age transient as age can be    // calculated from Date of Birth    // and current date.    transient int age;      // serialize other fields    String name, address;    public Test(String accessKey, int age,                String name, String address)    {        this.accessKey = accessKey;        this.age = age;        this.name = name;        this.address = address;    }}  public class GFG {    public static void main(String[] args)        throws Exception    {        ObjectInputStream in            = new ObjectInputStream(                (new FileInputStream(                    "login_details.txt")));        Test obj = (Test)in.readObject();          /* Transient variable will be shown         null due to security reasons.*/        System.out.println("Accesskey: "                           + obj.accessKey);        System.out.println("Age: "                           + obj.age);        System.out.println("Name: "                           + obj.name);        System.out.println("Address: "                           + obj.address);    }}
Output:
Transient Code Output
The following table describes the differences:
Java-keyword
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MoviePy –Saving Video File Clip

01 Aug, 2020
In this article we will see how we can save a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Visual multimedia source that combines a sequence of images to form a moving picture. The video transmits a signal to a screen and processes the order in which the screen captures should be shown. Videos usually have audio components that correspond with the pictures being shown on the screen.
In order to do this we will use write_videofile method with the VideoFileClip object
Syntax : clip.write_videofile(new_name)
Argument : It takes takes string as argument which is new name or location of file
Return : It returns None
Note : If only new name is given in parameters then the file will get saved in the same folder of the code.
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")  # getting subclip as video is largeclip = clip.subclip(55, 65)  # saving the clipclip.write_videofile("gfg_intro.webm")  # showing clipclip.ipython_display(width = 480)
Output :
Moviepy - Building video gfg_intro.webm.
Moviepy - Writing video gfg_intro.webm

                                                                                                                       
Moviepy - Done !
Moviepy - video ready gfg_intro.webm
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

When we go into the code folder we can see the new file is created, below is how the created file will be
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")  # getting subclip clip = clip.subclip(0, 7)  # saving the clipclip.write_videofile("handmade_gfg.mp4")  # showing clipclip.ipython_display()
Output :
Moviepy - Building video handmade_gfg.mp4.
MoviePy - Writing audio in handmade_gfgTEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video handmade_gfg.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready handmade_gfg.mp4
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the current position of cursor from output screen in C?

06 Mar, 2019
The given task is to get the current position of the cursor from the output screen in C.
Approach: There is a predefined function wherex() in C language that returns the x coordinate of the cursor in the current output screen. And wherey() function that returns the y coordinate of the cursor in current output screen. Both the functions are defined in conio.h headerfile.
wherex(): This method returns the horizontal position of the cursor.Syntax:int wherex();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size.
Syntax:
int wherex();
Parameters: This method do not accepts any parameters.
Return Value: This method returns an integer value in range 1 to 80, or as per the system’s screen size.
wherey(): This method returns the vertical position of the cursor.Syntax:int wherey();Parameters: This method do not accepts any parameters.Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size.
Syntax:
int wherey();
Parameters: This method do not accepts any parameters.
Return Value: This method returns an integer value in range 1 to 50, or as per the system’s screen size.
Note: This code is according to turbo C.
Example 1:
// C program to get the current// cursor position from output screen  #include <conio.h>#include <stdio.h>  void main(){    clrscr();      // print current location of x.    printf("current location of x is:%d\n", wherex());      // print the current location of y.    print("currentlocation of y is:%d", wherey());      getch();}
Output:
Example 2:
// C program to get the current// cursor position from output screen  #include <conio.h>#include <stdio.h>  void main(){    clrscr();      // takes the cursor to given coordinates    // here at (10, 15).    gotoxy(10, 15);      // print current location of x.    printf("current location of x is:%d\n", wherex());      // print the current location of y.    print("currentlocation of y is:%d", wherey());      getch();}
Output:
References:
https://code-reference.com/c/conio.h/wherex
https://code-reference.com/c/conio.h/wherey
C-Misc
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.to_frame()

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_frame() function is used to convert the given series object to a dataframe.
Syntax: Series.to_frame(name=None)
Parameter :name : The passed name should substitute for the series name (if it has one).
Returns : data_frame : DataFrame
Example #1: Use Series.to_frame() function to convert the given series object to a dataframe.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.to_frame() function to convert the given series object to a dataframe.
# convert to dataframesr.to_frame()
Output :
As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe.
Example #2: Use Series.to_frame() function to convert the given series object to a dataframe.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Print the seriesprint(sr)
Output :
Now we will use Series.to_frame() function to convert the given series object to a dataframe.
# convert to dataframesr.to_frame()
Output :
As we can see in the output, the Series.to_frame() function has successfully converted the given series object to a dataframe.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS | saturate() Function - GeeksforGeeks

22 Aug, 2019
The saturate() function is an inbuilt function in CSS which is used to super-saturate or desaturates the input image.
Syntax:
saturate( amount )
Parameters: This function accepts single parameter amount, which holds the amount of conversion. The value of the parameter is set in terms of number or percentage. The value 0% represents completely unsaturated and 100% represents completely saturated you can increase the saturation more.
Below example illustrate the saturate() function in CSS:
Example:
<!DOCTYPE html><html>  <head>    <title>      CSS saturate() Function    </title>      <style>        h1 {            color: green;        }                  body {            text-align: center;        }                  .saturate_effect {            filter: saturate(250%);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h4>CSS saturate() function</h4>      <img class="saturate_effect" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"          alt="GeeksforGeeks logo"></body>  </html>
Output:
Supported Browsers: The browsers supported by saturate() function are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
IntSummaryStatistics getMin() method in Java with Examples - GeeksforGeeks

27 Jun, 2019
The getMin() method of IntSummaryStatistics class in Java is used to get the minimum of records in this IntSummaryStatistics.
Syntax:
public int getMin()

Parameter: This method do not accept any value as parameter.
Return Value: This method returns the minimum of the records in this IntSummaryStatistics.
Program:
// Java program to demonstrate// the above method  import java.util.*;  public class IntSummaryStatisticsDemo {    public static void main(String[] args)    {          IntSummaryStatistics intSummaryStatistics            = new IntSummaryStatistics();          List<Integer> list            = Arrays.asList(10, 20, 30, 40, 50);          Iterator<Integer> iterator = list.listIterator();        while (iterator.hasNext()) {              // Add the integers to the IntSummaryStatistics object            intSummaryStatistics.accept(iterator.next());        }          System.out.println("The minimum of values is "                           + intSummaryStatistics.getMin());    }}
The minimum of values is 10

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html#getMin()
Java - util package
Java-Functions
Java-IntSummaryStatistics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
Data Structure and Algorithms - Quick Sort

Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.
Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n2), respectively.
Following animated representation explains how to find the pivot value in an array.
The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element.
Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is as follows.
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

The pseudocode for the above algorithm can be derived as −
function partitionFunc(left, right, pivot)
   leftPointer = left
   rightPointer = right - 1

   while True do
      while A[++leftPointer] < pivot do
         //do-nothing            
      end while
		
      while rightPointer > 0 && A[--rightPointer] > pivot do
         //do-nothing         
      end while
		
      if leftPointer >= rightPointer
         break
      else                
         swap leftPointer,rightPointer
      end if
		
   end while 
	
   swap leftPointer,right
   return leftPointer
	
end function
Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then processed for quick sort. We define recursive algorithm for quicksort as follows −
Step 1 − Make the right-most index value pivot
Step 2 − partition the array using pivot value
Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

To get more into it, let see the pseudocode for quick sort algorithm −
procedure quickSort(left, right)

   if right-left <= 0
      return
   else     
      pivot = A[right]
      partition = partitionFunc(left, right, pivot)
      quickSort(left,partition-1)
      quickSort(partition+1,right)    
   end if		
   
end procedure
To know about quick sort implementation in C programming language, please click here.

    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
PHP date_add() Function

The date_add() function is an alias of DateTime::add(). It accepts a DateTime object as parameters and a DateInterval object, adds the specified interval to the given DateTime.
date_add($object, $interval)

object(Optional)
This is a DateTime object specifying/representing the date to which you need to add the time interval.
interval (Optional)
This is a DateInterval object specifying the interval to be added.
PHP date_add() function returns a DateTime object with added interval. In case of failure, this function returns the boolean value false.
This function was first introduced in PHP Version 5.3.0 and, works with all the later versions.
Following example demonstrates the usage of the date_add() function −
<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $res = date_add($date, new DateInterval('PT10H30S'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y H:i:s");
   print($format);
?>
This will produce following result −
25-09-1989 10:00:30

You can create an interval using the date_interval_create_from_date_string() function. Following example creates an interval using this function, adds it to a date −
<?php
   $date = date_create("25-09-1989");
   $interval = date_interval_create_from_date_string('1025 days');
   $res = date_add($date, $interval);   
   $format = date_format( $res, "d-m-Y H:i:s");
   print($format);   
?>
This will produce following result −
16-07-1992 00:00:00

Now, let us try to add interval with years, months and days −
<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $res = date_add($date, new DateInterval('P29Y2M5D'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y");
   print($format);
?>
This will produce following result −
30-11-2018

<?php
   $date = date_create('1995-05-07');
   $interval = date_interval_create_from_date_string('150 days');
   $date->add($interval);
   print($date -> format('d-m-Y'));
?>
This produces the following result −
04-10-1995


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
p5.js | jump() Function - GeeksforGeeks

01 Sep, 2021
The jump() function is an inbuilt function in the p5.js library. This function is used to jump at some specific point of playing audio, just required the time position of that audio. which is playing that time on the web. 
Syntax: 
jump( cueTime, duration )
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.
Parameter: This function accepts two parameter as mentioned above and described below.  
cueTime: This parameter holds an integer number as seconds that define the cue time in seconds.
duration: This parameter holds an integer number that defines the duration of playback in seconds.
Below examples illustrates the p5.js jump() function in JavaScript: 
Example 1: In this example the song will jump at second 7 position of the song.  
Javascript
var sound;     function preload() {        // Initialize sound    sound = loadSound("pfivesound.mp3");}    function setup() {        // Playing the preloaded sound    sound.play();    //sound will jump at that point    sound.jump( 7 ); }
Example 2: In this example, the song will jump at middle position of the song if you press the button. 
Javascript
var sound;var jmp;   function preload() {         // Initialize sound    sound = loadSound("song.mp3");}     function setup() {         // Playing the preloaded sound    sound.play();        //Creating button    jmp = createButton("Jump");    jmp.mousePressed(jumpAudio);} function jumpAudio() {     //sound will jump at that point    var len = sound.duration();    sound.jump( len/2);}
Note: May after crossing the middle position if you press the button again another time song will be played from middle position.
Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers supported by p5.js jump() function are listed below: 
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
adnanirshad158
JavaScript-p5.js
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
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
How to remove an HTML element using JavaScript ?
Remove elements from a JavaScript Array
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
JavaScript escape() Function

22 Nov, 2021
Below is the example of the escape() function.
Example:<script>   // Special character encoded with   // escape function   document.write(escape("Geeks for Geeks!!!"));     document.write("<br>");     // Print encoded string using escape() function   // Also include exceptions i.e. @ and .   document.write(escape("To contribute articles contact"+                    " us at review-team@geeksforgeeks.org"));</script>                    
<script>   // Special character encoded with   // escape function   document.write(escape("Geeks for Geeks!!!"));     document.write("<br>");     // Print encoded string using escape() function   // Also include exceptions i.e. @ and .   document.write(escape("To contribute articles contact"+                    " us at review-team@geeksforgeeks.org"));</script>                    
Output:Geeks%20for%20Geeks%21%21%21
To%20contribute%20articles%20contact%20us%20atcontribute
@geeksforgeeks.org 
Geeks%20for%20Geeks%21%21%21
To%20contribute%20articles%20contact%20us%20atcontribute
@geeksforgeeks.org 
The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters.
Syntax:
escape(string)
Parameters: This function accepts a single parameter as mentioned above and described below:
string: This parameters holds the string that will be encoded.
Return value: This function returns a encoded string.
Note: This function only encodes the special characters, this function is depricated.Exceptions: @ – + . / * _
More example codes for the above function are as follows:
Program 1:
<script>   // Special character encoded with   // escape function   document.write(escape("Geeks for Geeks!!!"));     document.write("<br>");     // Print encoded string using escape() function   // Also include exceptions i.e. @ and .   document.write(escape("A Computer Science Portal"));</script>                    
Output:
Geeks%20for%20Geeks%21%21%21
A%20Computer%20Science%20Portal
Program 2:
<script>    // Special character encoded with    // escape function    document.write(escape("GeeksforGeeks"));      document.write("<br>");      // Print encoded string using escape() function    // Also include exceptions i.e. @ and .    document.write(escape("A#Computer-Science"+                          "%Portal@for*Geeks"));</script>                  
Output:
GeeksforGeeks
A%23Computer-Science%25Portal@for*Geeks
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Edge 12 and above
Mozilla Firefox 1 and above
Safari 1 and above
Opera 3 and above
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to get Current Time

26 Mar, 2020
In this article, we will know the approaches to get the current time in Python. There are multiple ways to get it. The most preferably date-time module is used in Python to create the object containing date and time.1: Current time of a timezone – Using pytZ module
from datetime import *import pytz    tz_INDIA = pytz.timezone('Asia/Kolkata') datetime_INDIA = datetime.now(tz_INDIA)print("INDIA time:", datetime_INDIA.strftime("%H:%M:%S"))
Output:
INDIA time: 19:29:53
2 : Current time – Using date time object
Example 1:
from datetime import datetime  # now() method is used to# get object containing # current date & time.now_method = datetime.now()  # strftime() method used to# create a string representing# the current time.currentTime = now_method.strftime("%H:%M:%S")print("Current Time =", currentTime)
Output:
Current Time = 19:31:51

Example 2:
from datetime import datetime  # Time object containing # the current time.time = datetime.now().time()   print("Current Time =", time)
Output:
Current Time = 19:33:29.087840
3. Getting Time – using Time module.
import time    # localtime() method used to# get the object containing# the local time.Time = time.localtime()  # strftime() method used to# create a string representing# the current time.currentTime = time.strftime("%H:%M:%S", Time)print(currentTime)
Output:
19:35:17
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Exit handlers (atexit)

29 Jun, 2022
atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not handled by Python, when os.exit() is called, or Python fatal internal error is detected, the functions registered via this module are not executed.
register(): Register function takes a function as an argument that is to be executed at interpreter termination. If there are multiple functions passed as arguments e.g. (fun1(), fun2()..) then there execution will be in reverse order (...fun2(), fun1()). The execution occurs in last in first out (LIFO) concept.
Syntax: atexit.register(fun, *args, **kwargs) 
Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘. 
Return: This function returns the called fun and hence the calling can be traced.
Note: This function can also be used as a decorator. 
# Example 1: 
Python3
# Python program to demonstrate# atexit module  import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name):    print (name) for name in names:     # Using register()    atexit.register(hello, name)
Output :
Geeks
for
Geeks
# Example 2: Using register as a decorator 
Python3
# Python program to demonstrate# atexit module  import atexit # Using register() as a decorator@atexit.registerdef goodbye():    print("GoodBye.")
Output :
GoodBye.
unregister(): The unregister() function removes the specified fun from the functions defined in the program. It provides a surety that the fun will not be called when the interpreter terminates.
Syntax: atexit.unregister(fun) 
Parameters: The function may or may not contain any parameter. If any present then the fun name is to be specified. 
Return: No return.
Example: 
Python3
# Python program to demonstrate# atexit module  import atexit names = ['Geeks', 'for', 'Geeks'] def hello(name):    print (name) for name in names:     # Using unregister()    atexit.unregister(hello)
Output :
No Output
jjlopezb4e40
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Lodash | _.cloneDeep() Method

18 Jan, 2022
The _.cloneDeep() method is used to create a deep copy of the value i.e. it recursively clones the value. This method is similar to the _.clone() method.
Syntax: 
_.cloneDeep( value )
Parameters: This method accepts single parameter as mentioned above and described below:  
value: This parameter holds the value that need to be clone recursively.
Return Value: This method returns the deep cloned value.
Example 1: Cloning Simple Object  
Javascript
const _ = require('lodash');   var obj = {    x: 23};   // Deep copyvar deepCopy = _.cloneDeep(obj);   console.log('Comparing original with'    + ' deep ', obj === deepCopy);   obj.x = 10; // Changing original value   console.log('After changing original value');   console.log("Original value ", obj);   console.log("Deep Copy value ", deepCopy);
Output: 
Comparing original with deep  false
After changing original value
Original value  { x: 10 }
Deep Copy value  { x: 23 }
Example 2: Cloning complex object  
Javascript
const _ = require('lodash');    var obj = [{  x: 1 }, {y: 2}];   // Deep copyvar deepCopy = _.cloneDeep(obj);    console.log('Comparing original with deep ',            obj[0] === deepCopy[0]);    // Changing original valueobj[0].x = 10;    // Values after changing original valueconsole.log("After changing original value");    console.log("Original value ", obj);    console.log("Deep Copy value ", deepCopy);
Output: 
Comparing original with deep  false
After changing original value
Original value  [ { x: 10 }, { y: 2 } ]
Deep Copy value  [ { x: 1 }, { y: 2 } ]
So, here we have seen that after changing the original value the deep copy of the values didn’t change because _.cloneDeep() recursively copied the value deeply.
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#cloneDeep 
gulshankumarar231
sagartomar9927
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UnaryOperator Interface in Java

18 Nov, 2019
The UnaryOperator Interface<T> is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. However what distinguishes it from a normal Function is that both its argument and return type are the same.
Hence this functional interface which takes in one generic namely:-
T: denotes the type of the input argument to the operation
Hence the UnaryOperator<T> overloads the Function<T, T> type. So it inherits the following methods from the Function Interface:
T apply(T t)
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
The lambda expression assigned to an object of UnaryOperator type is used to define its accept() which eventually applies the given operation on its argument.
The UnaryOperator interface consists of the following functions:
This method returns a UnaryOperator which takes in one value and returns it. The returned UnaryOperator does not perform any operation on its only value.
Syntax:
static  UnaryOperator identity()
Parameters: This method does not take in any parameter.
Returns: A UnaryOperator which takes in one value and returns it.
Below is the code to illustrate accept() method:
Program 1:
import java.util.function.UnaryOperator;  public class GFG {    public static void main(String args[])    {          // Instantiate the UnaryOperator interface        UnaryOperator<Boolean>            op = UnaryOperator.identity();          // Apply identify() method        System.out.println(op.apply(true));    }}
true

Below are few examples to demonstrate the methods inherited from Function<T, T>:
1.accept()
import java.util.function.Function;import java.util.function.UnaryOperator;  public class GFG {    public static void main(String args[])    {        UnaryOperator<Integer> xor = a -> a ^ 1;        System.out.println(xor.apply(2));    }}
3

2.addThen()
import java.util.function.Function;import java.util.function.UnaryOperator;  public class GFG {    public static void main(String args[])    {        UnaryOperator<Integer> xor = a -> a ^ 1;        UnaryOperator<Integer> and = a -> a & 1;        Function<Integer, Integer> compose = xor.andThen(and);        System.out.println(compose.apply(2));    }}
1

3.compose()
import java.util.function.Function;import java.util.function.UnaryOperator;  public class GFG {    public static void main(String args[])    {        UnaryOperator<Integer> xor = a -> a ^ 1;        UnaryOperator<Integer> and = a -> a & 1;        Function<Integer, Integer> compose = xor.compose(and);        System.out.println(compose.apply(231));    }}
0

psil123
Akanksha_Rai
Java - util package
Java 8
java-basics
Java-Functional Programming
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lex program to count the number of lines, spaces and tabs

22 Mar, 2021
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let’s the how to count the number of lines, spaces and tabs using Lex. Example:  
Input:
Geeks for       Geeks 
gfg  gfg

Output:
No. of lines=2 
No. of spaces=3 
No. of tabs=1 
No. of other characters=19

Input:
Hello
How    are    you?

Output:
No. of lines=2 
No. of spaces=4 
No. of tabs=1 
No. of other characters=15
 Below is the implementation:  
C
/*lex code to count the number of lines,    tabs and spaces used in the input*/ %{#include<stdio.h>int lc=0, sc=0, tc=0, ch=0; /*Global variables*/%} /*Rule Section*/%%\n lc++; //line counter([ ])+ sc++; //space counter\t tc++; //tab counter. ch++;     //characters counter%% int main(){    // The function that starts the analysis    yylex();         printf("\nNo. of lines=%d", lc);     printf("\nNo. of spaces=%d", sc);    printf("\nNo. of tabs=%d", tc);    printf("\nNo. of other characters=%d", ch);     }
Output:  
 
ankita_chandra
architgwl2000
Lex program
C Language
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Different Methods to Reverse a String in C++
Left Shift and Right Shift Operators in C/C++
Issues in the design of a code generator
Three address code in Compiler
Phases of a Compiler
Peephole Optimization in Compiler Design
Code Optimization in Compiler Design
What is the difference between .py and .pyc files ?

Python compliles the .py files and save it as .pyc file
The .pyc contain the compiled bytecode of Python source files, A .pyc is not created for your main program file that you execute (only for imported modules).
The .pyc file contains encoded python bytecode.
If We Want to import module.The Module calculate Addition of Two Numbers
 Live Demo
def recursive_sum(n):
"""Function to return the sum of recursive numbers"""
if n <= 1:
return n
else:
return n + recursive_sum(n-1)

# change this value for a different result
number = 16

if number < 0:
print("Enter a positive number")
else:
print("The sum is",recursive_sum(number))
The sum is 136
If you store this program with the name "example",then it will be stored as "example.py" when you run a example.py file,it takes some to create a example.pyc file once the code is executed it first executes .py file where as code is first turned into byte code by the compiler in the form of "example.pyc” file.