code-rag-bench/online-tutorials huggingface dataset:
How to create a upload file button in ReactJS? - GeeksforGeeks

03 Aug, 2021
As we know that uploading is a very important step in any application, so we can create a simple upload file button in ReactJS using the following approach. Material UI for React has this component available for us and it is very easy to integrate. 
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/icons
Project Structure: It will look like the following.
Project Structure
Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import Button from '@material-ui/core/Button';import PhotoCamera from '@material-ui/icons/PhotoCamera';import IconButton from '@material-ui/core/IconButton'; const App = () => {   return (    <div style={{      display: 'flex',      margin: 'auto',      width: 400,      flexWrap: 'wrap',    }}>      <div style={{ width: '100%', float: 'left' }}>        <h3>How to use create button to choose file in ReactJS?</h3> <br />      </div>      <input        type="file"        accept="image/*"        style={{ display: 'none' }}        id="contained-button-file"      />      <label htmlFor="contained-button-file">        <Button variant="contained" color="primary" component="span">          Upload        </Button>      </label>      <h3>  OR  </h3>      <input accept="image/*" id="icon-button-file"        type="file" style={{ display: 'none' }} />      <label htmlFor="icon-button-file">        <IconButton color="primary" aria-label="upload picture"        component="span">          <PhotoCamera />        </IconButton>      </label>    </div>  );} export default App;
  
Step to Run Application: Run the application using the following command from the root directory of the project:
 
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
 
 
Now click on any of either button and now you can choose any file to upload. This is how we can create the upload file button in ReactJS.
 
angle361
JavaScript
ReactJS
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
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
Difference Between PUT and PATCH Request
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
PHP program to find the maximum element in an array

To find the maximum element in an array, the PHP code is as follows −
 Live Demo
<?php
   function get_max_value($my_array){
      $n = count($my_array);
      $max_val = $my_array[0];
      for ($i = 1; $i < $n; $i++)
         if ($max_val < $my_array[$i])
            $max_val = $my_array[$i];
      return $max_val;
   }
   $my_array = array(56, 78, 91, 44, 0, 11);
   print_r("The highest value of the array is ");
   echo(get_max_value($my_array));
   echo("\n");
?>
The highest value of the array is91
A function named ‘get_max_value()’ is defined, that takes an array as parameter. Inside this
function, the count function is used to find the number of elements in the array, and it is assigned to
a variable −
$n = count($my_array);
The first element in the array is assigned to a variable, and the array is iterated over, and adjacent
values in the array are compared, and the highest value amongst all of them is given as output −
$max_val = $my_array[0];
for ($i = 1; $i < $n; $i++)
   if ($max_val < $my_array[$i])
      $max_val = $my_array[$i];
return $max_val;
Outside the function, the array is defined, and the function is called by passing this array as a
parameter. The output is displayed on the screen −
$my_array = array(56, 78, 91, 44, 0, 11);
print_r("The highest value of the array is");
echo(get_max_value($my_array));
ES6 - split()

This method splits a String object into an array of strings by separating the string into substrings.
string.split([separator][, limit]); 

separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string.
separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string.
limit − Integer specifying a limit on the number of splits to be found.
limit − Integer specifying a limit on the number of splits to be found.
The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array.
var str = "Apples are round, and apples are juicy."; 
var splitted = str.split(" ", 3); 
console.log(splitted)   
[ 'Apples', 'are', 'round,' ]  


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Difference between Assertions and Triggers in DBMS

21 Sep, 2021
1. What are Assertions? When a constraint involves 2 (or) more tables, the table constraint mechanism is sometimes hard and results may not come as expected. To cover such situation SQL supports the creation of assertions that are constraints not associated with only one table. And an assertion statement should ensure a certain condition will always exist in the database. DBMS always checks the assertion whenever modifications are done in the corresponding table. 
Syntax – 
CREATE ASSERTION  [ assertion_name ]
CHECK ( [ condition ] );
Example –  
CREATE TABLE sailors (sid int,sname varchar(20), rating int,primary key(sid),
CHECK(rating >= 1 AND rating <=10)
CHECK((select count(s.sid) from sailors s) + (select count(b.bid)from boats b)<100) ); 
In the above example, we enforcing CHECK constraint that the number of boats and sailors should be less than 100. So here we are able to CHECK constraints of two tablets simultaneously. 
2. What are Triggers? A trigger is a database object that is associated with the table, it will be activated when a defined action is executed for the table. The trigger can be executed when we run the following statements: 
INSERTUPDATEDELETE
INSERT
UPDATE
DELETE
And it can be invoked before or after the event. 
Syntax –  
create trigger [trigger_name]       
[before | after]          
{insert | update | delete} 
on [table_name]  
[for each row]    
[trigger_body]  
Example –  
create trigger t1  before  UPDATE on sailors
for each row
begin
   if new.age>60 then
      set new.age=old.age;
   else
      set new.age=new.age;
   end if;
end;
$ 
In the above example, we are creating triggers before updates. so, if the new age is greater than 60 we should not update else we should update. We can call this trigger by using “$” symbol. 
Difference between Assertions and Triggers : 
Assertions can’t modify the data and they are not linked to any specific tables or events in the database but Triggers are more powerful because they can check conditions and also modify the data within the tables inside a database, unlike assertions. 
 
sweetyty
DBMS-SQL
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Difference between OLAP and OLTP in DBMS
MySQL | Regular expressions (Regexp)
Relational Model in DBMS
What is Temporary Table in SQL?
Difference between BFS and DFS
Class method vs Static method in Python
Difference Between Method Overloading and Method Overriding in Java
Difference between var, let and const keywords in JavaScript
Differences between JDK, JRE and JVM
Smart calculator in Python

11 Jan, 2022
Problem – This smart calculator works on the text statement also. The user need not provide algebraic expression always. It fetches the word form the command (given by the user) and then formulates the expression.Examples: 
Input  : Hi calculator plz find the lcm of 4 and 8.  
Output : 8 

Input  : Hi smart plz find the  multiplication of 3 and 9. 
Output : 27 

Input  : Hi smart plz end the program. 
Output : Thanks for enjoy with me.
 Code : Python code for smart calculation   
Python3
# main python proghramresponse=['Welcome to smart calculator','My name is MONTY',          'Thanks for enjoy with me ','Sorry ,this is  beyond my ability'] # fetching tokens from the text commanddef extract_from_text(text):    l=[]    for t in text.split(' '):        try:            l.append(float(t))        except ValueError:            pass    return l # calculating LCMdef lcm(a,b):    L=a if a>b else b    while L<=a*b:        if L%a==0 and L%b==0:            return L        L+=1 # calculating HCFdef hcf(a,b):    H=a if a<b else b    while H>=1:        if a%H==0 and b%H==0:            return H        H-=1 # Additiondef add(a,b):    return a+b # Subtractiondef sub(a,b):    return a-b # Multiplicationdef mul(a,b):    return a*b # Divisiondef div(a,b):    return a/b # Remainderdef mod(a,b):    return a%b # Response to command# printing - "Thanks for enjoy with me" on exitdef end():    print(response[2])    input('press enter key to exit')    exit()  def myname():    print(response[1])def sorry():    print(response[3])  # Operations - performed on the basis of text tokensoperations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add,            'SUB':sub,'SUBTRACT':sub, 'MINUS':sub,            'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf,            'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul,            'DIVISION':div,'MOD':mod,'REMAINDER'            :mod,'MODULAS':mod} # commandscommands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end}          print('--------------'+response[0]+'------------')print('--------------'+response[1]+'--------------------')    while True:    print()    text=input('enter your queries:  ')    for word in text.split(' '):        if word.upper() in operations.keys():            try:                l = extract_from_text(text)                r = operations[word.upper()] (l[0],l[1])                print(r)            except:                print('something went wrong going plz enter again !!')            finally:                      break        elif word.upper() in commands.keys():                      commands[word.upper()]()                      break    else:                sorry()
Output: 
--------------Welcome to smart calculator------------
--------------My name is MONTY--------------------


enter your queries:  tell me the hcf of 4 and 8
4.0


enter your queries:  hi plz tell me 7 + 8
Sorry ,this is  beyond my ability


enter your queries:  pls add 7 and 8
15.0
varshagumber28
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList push() Method in Java

10 Dec, 2018
The java.util.LinkedList.push() method is used to push an element at the starting(top) of the stack represented by LinkedList. This is similar to the addFirst() method of LinkedList and simply inserts the element at the first position or top of the linked list.
Syntax:
LinkedListObject.push(Object element)

Parameters: The method accepts one parameter element of object type and represents the element to be inserted. The type ‘Object’ should be of same Stack represented by the LinkedList.
Return Type: The return type of the method is void i.e. it doesn’t returns any value.
Below programs illustrate the java.util.LinkedList.push() method:
Program 1:
// Java code to demonstrate push() methodimport java.util.LinkedList;  public class GfG {    // Main method    public static void main(String[] args)    {          // Creating a LinkedList object to represent a stack.        LinkedList<String> stack = new LinkedList<>();          // Pushing an element in the stack        stack.push("I");          // Pushing an element in the stack        stack.push("Like");          // Pushing an element in the stack        stack.push("GeeksforGeeks");          // Printing the complete stack.        System.out.println(stack);    }}
[GeeksforGeeks, Like, I]

Program 2 :
// Java code to demonstrate push() method  import java.util.LinkedList;  public class GfG {    // main method    public static void main(String[] args)    {          // Creating a LinkedList object to represent a stack.        LinkedList<Integer> stack = new LinkedList<>();          // Pushing an element in the stack        stack.push(30);          // Pushing an element in the stack        stack.push(20);          // Pushing an element in the stack        stack.push(10);          // Printing the complete stack.        System.out.println(stack);    }}
[10, 20, 30]

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form Handling in ReactJS

In this article, we are going to see how to handle the forms properly in a React application.
Handling Forms is one of the most crucial parts needed while building a real-world React application. It is all about taking the inputs from the user, validating it and displaying if there are errors in the data submitted by the user.
In this example, we will build an Information Page that takes the information from the user, validates it and displays the result accordingly.
Here, we have App.js as the parent component of the Details.js component.
Details.js
import React, { useState } from 'react';

const Details = () => {
   const [name, setName] = useState('');
   const [number, setNumber] = useState(null);
   const [mssg, setMssg] = useState(null);

   const submit = (e) => {
      e.preventDefault();
      if (!Number(number)) {
         setMssg('Phone Number should be of number type only');
      } else {
         setMssg('Form Submitted!');
      }
   };
   return (
      <form onSubmit={submit}>
      <input
      placeholder="Name"
      value={name}
      onChange={(e) => setName(e.target.value)}
      />

      <input
      placeholder="Phone Number"
      value={number}
         onChange={(e) => setNumber(e.target.value)}
      />
      <button>Submit</button>
      {mssg}
      </form>
   );
};
export default Details;
App.js
import React from 'react';
import Details from './Details';

const App = () => {
   return (
      <div>
      <h1>Information Page:</h1>
      <Details />
      </div>
   );
};
export default App;
In the above example, we are taking the inputs from the user and storing it in the state of the application. If the phone number entered by the user is not of number type, then the error message will be displayed.
This will produce the following result.
Check if list is sorted or not in Python

Lists are the most widely used data collectios in python. We may come across situation when we need to know if the given list is already sorted or not. In this article we will see the approaches to achieve this.
We take a copy of the given list, apply sort function to it and store that copy as a new list. Then we compare it with the original list and check if they are equal or not.
 Live Demo
listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
listA_copy = listA[:]
# Apply sort to copy
listA_copy.sort()
if (listA == listA_copy):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")

# Checking again
listB = [11,23,21,51,67]
#Given list
print("Given list : ",listB)
listB_copy = listB[:]
# Apply sort to copy
listB_copy.sort()
if (listB == listB_copy):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
Running the above code gives us the following result −
Given list : [11, 23, 42, 51, 67]
Yes, List is sorted.
Given list : [11, 23, 21, 51, 67]
No, List is not sorted.
We can use the all function to check if every element of the list is smaller than the element next to it and apply the range function to traverse through all the elements.
 Live Demo
listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
# Apply all and range
if (all(listA[i] <= listA[i + 1] for i in range(len(listA)-1))):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
# Checking again
listB = [11,23,21,51,67]
print("Given list : ",listB)
# Apply all and range
if (all(listB[i] <= listB[i + 1] for i in range(len(listB)-1))):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")
Running the above code gives us the following result −
Given list : [11, 23, 42, 51, 67]
Yes, List is sorted.
Given list : [11, 23, 21, 51, 67]
No, List is not sorted.
Java - The Map.Entry Interface

The Map.Entry interface enables you to work with a map entry.
The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object.
Following table summarizes the methods declared by this interface −
boolean equals(Object obj)
Returns true if obj is a Map.Entry whose key and value are equal to that of the invoking object.
Object getKey( )
Returns the key for this map entry.
Object getValue( )
Returns the value for this map entry.
int hashCode( )
Returns the hash code for this map entry.
Object setValue(Object v)
Sets the value for this map entry to v. A ClassCastException is thrown if v is not the correct type for the map. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed.
Following is an example showing how Map.Entry can be used −
import java.util.*;
public class HashMapDemo {

   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();

      // Put elements to the map
      hm.put("Zara", new Double(3434.34));
      hm.put("Mahnaz", new Double(123.22));
      hm.put("Ayan", new Double(1378.00));
      hm.put("Daisy", new Double(99.22));
      hm.put("Qadir", new Double(-19.08));
      
      // Get a set of the entries
      Set set = hm.entrySet();
      
      // Get an iterator
      Iterator i = set.iterator();
     
      // Display elements 
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
     
      // Deposit 1000 into Zara's account
      double balance = ((Double)hm.get("Zara")).doubleValue();
      hm.put("Zara", new Double(balance + 1000));
      System.out.println("Zara's new balance: " + hm.get("Zara"));
   }
}
This will produce the following result −
Daisy: 99.22
Ayan: 1378.0
Zara: 3434.34
Qadir: -19.08
Mahnaz: 123.22

Zara's new balance: 4434.34


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How To Add Identifier Column When Concatenating Pandas dataframes?

18 Apr, 2022
We generally want to concat two or more dataframes when working with some data. So, when we concat these dataframes we need to actually want to provide an identifier column in order to identify the concatenated dataframes. In this article, we’ll see with the help of examples of how we can do this.
Example 1:
To add an identifier column, we need to specify the identifiers as a list for the argument “keys” in concat() function, which creates a new multi-indexed dataframe with two dataframes concatenated. Now we’ll use reset_index to convert multi-indexed dataframe to a regular pandas dataframe.
Python3
import pandas as pdimport numpy as np  dict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'],        'Maths':[87, 91, 97, 95],        'Science':[83, 99, 84, 76]       } df1 = pd.DataFrame(dict) dict = {'Name':['Amy', 'Maddy'],        'Maths':[89, 90],        'Science':[93, 81]       } df2 = pd.DataFrame(dict) # Concatenating two dataframesdf = pd.concat([df1,df2],keys=['t1', 't2'])display(df) df = pd.concat([df1,df2], keys=['t1', 't2']).reset_index()display(df)
  
Output:
 
 
In the output, we can see a column with the identifiers of each dataframe where “t1” represents the first dataframe and “t2” represents the second dataframe.
 
Example 2:
 
We can do this similarly for any number of dataframes. In this example, we’ll combine three dataframes.
 
Python3
import pandas as pdimport numpy as np  dict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'],        'Maths': [87, 91, 97, 95],        'Science': [83, 99, 84, 76]        } df1 = pd.DataFrame(dict) dict = {'Name': ['Amy', 'Maddy'],        'Maths': [89, 90],        'Science': [93, 81]        } df2 = pd.DataFrame(dict) dict = {'Name': ['Rob', 'Rick', 'Anish'],        'Maths': [89, 90, 87],        'Science': [93, 81, 90]        } df3 = pd.DataFrame(dict) # Concatenating Dataframesdf = pd.concat([df1, df2, df3],               keys=['t1', 't2', 't3'])display(df) df = pd.concat([df1, df2, df3],               keys=['t1', 't2', 't3']).reset_index()display(df)
  
Output:
 
 
In the output, we can see a column with the identifiers of each dataframe where “t1”, “t2” and “t3” represent first, second and third dataframe respectively. 
 
gabaa406
simranarora5sos
pandas-dataframe-program
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
PostgreSQL – BIGINT Integer Data Type

28 Aug, 2020
PostgreSQL allows a type of integer type namely BIGINT. It requires 8 bytes of storage size and can store integers in the range of -9, 223, 372, 036, 854, 775, 808 to +9, 223, 372, 036, 854, 775, 807. Using BIGINT type is not only consuming a lot of storage but also decreasing the performance of the database, therefore, you should have a good reason to use it. It comes in handy for storing data like the number of stars in a galaxy, the scientific constants, etc.
Syntax: variable_name BIGINT
Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of stars in various galaxies by using the below commands:
CREATE TABLE galaxy(
    id SERIAL PRIMARY KEY,
    name VARCHAR (255) NOT NULL,
    stars BIGINT NOT NULL CHECK (stars> 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO galaxy(name, stars)
VALUES
    ('Milky_Way', 2500000000000),
    ('Bodes', 2700000000000), 
    ('Cartwheel', 1300000000000),  
    ('Comet', 5700000000000);
Now let’s check our inserted data using the below commands:
SELECT * FROM galaxy;
Output:Example 2:In this example we will create a table that stores the value of various scientific constants by using the below commands:
CREATE TABLE constants(
    id SERIAL PRIMARY KEY,
    name VARCHAR (255) NOT NULL,
    value BIGINT NOT NULL CHECK (value> 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO constants(name, value)
VALUES
    ('Mole', 602213950000000000),
    ('Rydberg_constant', 10973731568525000), 
    ('Bohr_radius ', 13000000000);
Now let’s check our inserted data using the below commands:
SELECT * FROM constants;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for n-th odd number

23 Apr, 2021
Given a number n, print the nth odd number. The 1st odd number is 1, 2nd is 3, and so on.Examples:  
Input : 3
Output : 5
First three odd numbers are 1, 3, 5, ..

Input : 5
Output : 9
First 5 odd numbers are 1, 3, 5, 7, 9, ..
 
 
The nth odd number is given by the formula 2*n-1.
 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the nth odd number#include <bits/stdc++.h>using namespace std; // Function to find the nth odd numberint nthOdd(int n){    return (2 * n - 1);} // Driver codeint main(){    int n = 10;    cout << nthOdd(n);    return 0;}
// JAVA program to find the nth odd number class GFG{    // Function to find the nth odd number    static int nthOdd(int n)    {        return (2 * n - 1);    }         // Driver code    public static void main(String [] args)    {        int n = 10;        System.out.println(nthOdd(n));             }} // This code is contributed// by ihritik
# Python 3 program to find the# nth odd number # Function to find the nth odd numberdef nthOdd(n):     return (2 * n - 1)          # Driver codeif __name__=='__main__':    n = 10    print(nthOdd(n)) # This code is contributed# by ihritik
// C# program to find the nth odd numberusing System; class GFG{     // Function to find the nth odd numberstatic int nthOdd(int n){    return (2 * n - 1);} // Driver codepublic static void Main(){    int n = 10;    Console.WriteLine(nthOdd(n));}} // This code is contributed// by inder_verma
<?php// PHP program to find the// Nth odd number // Function to find the// Nth odd numberfunction nthOdd($n){    return (2 * $n - 1);} // Driver code$n = 10;echo nthOdd($n); // This code is contributed// by inder_verma?>
<script> // Javascript program to find the nth odd number // Function to find the nth odd numberfunction nthOdd(n){    return (2 * n - 1);} // Driver code var n = 10;document.write( nthOdd(n));  </script>
Output: 
19
 
ihritik
inderDuMCA
rutvik_56
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Python – Nearest occurrence between two elements in a List

11 Jun, 2021
Given a list and two elements, x and y find the nearest occurrence index of element x from element y.
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6 Output : 3 Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index. 
Method : Using list comprehension + loop + index()
In this, we find all indices of y using list comprehension, and then get index of x using index(), post that loop is used to get index difference, the nearest index is returned as result.
Python3
# Python3 code to demonstrate working of# Nearest occurrence of x from y in List# Using list comprehension + loop + index()  # function to find index of nearest# occurrence between two elementsdef nearestOccurrenceIndex(test_list, x, y):     # checking if both elements are present in list    if x not in test_list or y not in test_list:        return -1    # getting indices of x    x_idx = [idx for idx in range(len(test_list)) if test_list[idx] == x]     # getting y index    y_idx = test_list.index(y)     # getting min_dist index    min_dist = 1000000    res = None    for ele in x_idx:         # checking for min ele, and updating index        if abs(ele - y_idx) < min_dist:            res = ele            min_dist = abs(ele - y_idx)    return res  # initializing listinput_list = [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] # printing original listprint("The original list is : " + str(input_list)) # initializing xx = 4 # initializing yy = 6 # printing resultprint("Minimum distance index: ", nearestOccurrenceIndex(input_list, x, y))
Output:
The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] Minimum distance index:  8  
varshagumber28
Python list-programs
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Node.js URL.hash API

14 Oct, 2021
The url.hash is an inbuilt application programming interface of class URL within url module which is used to get and set the fragment portion of the URL.
Syntax: 
url.hash
Return value: It gets and sets the fragment portion of the URL.
Below programs illustrate the use of url.hash Method:
Example 1:  
Javascript
// node program to demonstrate the // url.hash API as Setter   // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');  // Display href value of myURL before changeconsole.log("Before Change");console.log(myURL.href);  // assigning fragment portion// using hash console.log();myURL.hash = 'rahim';  // Display href value of myURL after changeconsole.log("After Change");console.log(myURL.href);
Output: 
Before Change
https://example.org/foo#ram

After Change
https://example.org/foo#rahim
Example 2:  
Javascript
// node program to demonstrate the // url.hash API as Getter   // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');  // getting the fragment portion// using hash const hash = myURL.hash;  // Display hash value console.log(hash);
Output: 
#ram
NOTE: The above program could be run by using the node myapp.js command. 
Reference: https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_url_hash 
AshishkrGoyal
sweetyty
Node-URL
Web technologies
Node.js
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Node.js forEach() function
How to use an ES6 import in Node.js?
What are the differences between npm and npx ?
Node.js Readable Stream close Event

12 Oct, 2021
The ‘close’ Event in a Readable Stream is emitted when the stream and any of its hidden resources are being closed This event implies that no further events can be emitted, and no further computations can take place. Moreover, if a Readable stream is created with the emitClose option then it can always emit ‘close’ event.
Syntax:
Event: 'close '
Below examples illustrate the use of close event in Node.js:
Example 1:
// Node.js program to demonstrate the     // readable close event  // Including fs moduleconst fs = require('fs');  // Constructing readable streamconst readable = fs.createReadStream("input.txt");  // Calling close methodreadable.close();  // Handling close eventreadable.on("close", () => {    console.log("Stream ended");});  console.log("Done...");
Output:
Done...
Stream ended

Example 2:
// Node.js program to demonstrate the     // readable close event  // Including fs moduleconst fs = require('fs');  // Constructing readable streamconst readable = fs.createReadStream("input.txt");  // Handling close eventreadable.on("close", () => {    console.log("Stream ended");});  console.log("Done...");
Output:
Done...

Here, close method is not called so close event is not emitted.
Reference: https://nodejs.org/api/stream.html#stream_event_close_1.
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.str.lower(), upper() and title()

17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Python has some inbuilt methods to convert a string into lower, upper or Camel case. But these methods don’t work on list and other multi string objects. Pandas is a library for Data analysis which provides separate methods to convert all values in a series to respective text cases. Since, lower, upper and title are Python keywords too, .str has to be prefixed before calling these function on a Pandas series.Syntax:
Series.str.lower()
Series.str.upper()
Series.str.title()
Parameters: Doesn’t take any parameter
Return Type: Series with new values
To download the CSV file used, Click Here.
In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below.Example #1: Using .lower() on a Series
In this example, .lower() function is being called by the First Name column and hence, all the values in the First name column will be converted in to lower case.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # converting and overwriting values in columndata["First Name"]= data["First Name"].str.lower()  # displaydata
Output:As shown in the output image of data frame, all values in the First name column have been converted into lower case.
 
Example #2: Using .upper() on a Series
In this example, .upper() function is being called by the Team column and hence all the values in the Team column will be converted into upper case.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # converting and overwriting values in columndata["Team"]= data["Team"].str.upper()  # displaydata
Output:As shown in the output image of data frame, all values in the Team column have been converted into upper case.
 
Example #3: Using .title() on a Series
In this example, .title() function is being called by the Team column and hence, all the values in the into column will be converted in to Camel case. Since the values in the Team column were already in camel case, it has been converted to Upper case before and then again to camel case in order to verify the functionality of .title() method.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # converting and overwriting values in columndata["Team"]= data["Team"].str.upper().str.title()  # displaydata
Output:As shown in the output image of data frame, all values in the Team column have been converted into Camel case.
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.
How to match date with MongoDB $match?

To match date, use $match along with aggregate(). Let us create a collection with documents −
> db.demo491.insertOne({"ShippingDate":new ISODate("2020-01-10")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a09b0f3fa88e22790be")
}
> db.demo491.insertOne({"ShippingDate":new ISODate("2020-02-21")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a0eb0f3fa88e22790bf")
}
> db.demo491.insertOne({"ShippingDate":new ISODate("2020-03-23")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a1db0f3fa88e22790c0")
}
> db.demo491.insertOne({"ShippingDate":new ISODate()});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a28b0f3fa88e22790c1")
}
Display all documents from a collection with the help of find() method −
> db.demo491.find();
This will produce the following output −
{ "_id" : ObjectId("5e849a09b0f3fa88e22790be"), "ShippingDate" : ISODate("2020-01-
10T00:00:00Z") }
{ "_id" : ObjectId("5e849a0eb0f3fa88e22790bf"), "ShippingDate" : ISODate("2020-02-
21T00:00:00Z") }
{ "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03-
23T00:00:00Z") }
{ "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04-
01T13:42:00.090Z") }
Following is the query to match date with $match using MongoDB −
> db.demo491.aggregate([
... {
...    '$match' : { 'ShippingDate' : { '$gte' : ISODate('2020-02-24T18:10:11.000Z') } }
... }
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03-
23T00:00:00Z") }
{ "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04-
01T13:42:00.090Z") }
numpy.nonzero() in Python

28 Nov, 2018
numpy.nonzero()function is used to Compute the indices of the elements that are non-zero.
It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] . To group the indices by element, rather than dimension we can use transpose(nonzero(arr)).
Syntax : numpy.nonzero(arr)
Parameters :arr : [array_like] Input array.
Return : [tuple_of_arrays] Indices of elements that are non-zero.
Code #1 : Working
# Python program explaining# nonzero() function  import numpy as geekarr = geek.array([[0, 8, 0], [7, 0, 0], [-5, 0, 1]])  print ("Input  array : \n", arr)    out_tpl = geek.nonzero(arr)print ("Indices of non zero elements : ", out_tpl) 
Output :
Input array :[[ 0 8 0][ 7 0 0][-5 0 1]]Indices of non zero elements : (array([0, 1, 2, 2], dtype=int64), array([1, 0, 0, 2], dtype=int64))
 Code #2 :
# Python program for getting# The corresponding non-zero values:out_arr = arr[geek.nonzero(arr)]  print ("Output array of non-zero number: ", out_arr) 
Output :
Output array of non-zero number:  [ 8  7 -5  1]

 Code #3 :
# Python program for grouping the indices# by element, rather than dimension  out_ind = geek.transpose(geek.nonzero(arr))  print ("indices of non-zero number: \n", out_ind) 
Output :
indices of non-zero number: 
 [[0 1]
 [1 0]
 [2 0]
 [2 2]]

Python numpy-Indexing
Python-numpy
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
How to convert an enum type variable to a string in C++?

Here we will see how to convert some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string.
We shall create a function that takes an enum value as an argument, and we manually return the enum names as a string from that function.
 Live Demo
#include <iostream>
using namespace std;

enum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};

string enum_to_string(Animal type) {
   switch(type) {
      case Tiger:
         return "Tiger";
      case Elephant:
         return "Elephant";
      case Bat:
         return "Bat";
      case Dog:
         return "Dog";
      case Cat:
         return "Cat";
      case Mouse:
         return "Mouse";
      default:
         return "Invalid animal";
   }
}

int main() {
   cout << "The Animal is : " << enum_to_string(Dog) << " Its number: " << Dog <<endl;
   cout << "The Animal is : " << enum_to_string(Mouse) << " Its number: " << Mouse << endl;
   cout << "The Animal is : " << enum_to_string(Elephant) << " Its number: " << Elephant;
}
The Animal is : Dog Its number: 3
The Animal is : Mouse Its number: 5
The Animal is : Elephant Its number: 1
Designing Non-Deterministic Finite Automata (Set 5) - GeeksforGeeks

20 Nov, 2019
Prerequisite: Finite Automata IntroductionIn this article, we will see some designing of Non-Deterministic Finite Automata (NFA).
Problem-1: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language contain ‘ab’ as the substring.Explanation: The desired language will be like:
L1 = {ab, abba, abaa, ...........}
Here as we can see that each string of the above language contains ‘ab’ as the substring but the below language is not accepted by this NFA because some of the string of below language does not contain ‘ab’ as the substring.
L2 = {bb, b, bbbb, .............}
The state transition diagram of the desired language will be like below:In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself.
The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’. The final state ‘Z’ on getting either ‘a’ or ‘b’ as the input it remains in the state of itself.
Problem-2: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not containing ‘ab’ as the substring.Explanation: The desired language will be like:
L1 = {b, bb, bbbb, ...........}
Here as we can see that each string of the above language is not containing ‘ab’ as the substring But the below language is not accepted by this NFA because some of the string of below language is containing ‘ab’ as the substring.
L2 = {ab, aba, ababaab..............}
The state transition diagram of the desired language will be like below:In the above NFA, the initial and final state ‘X’ on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transits to another final state ‘Y’.
Another final state ‘Y’ on getting ‘a’ as the input it remains in the state of itself.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
LRU Cache Implementation
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Difference between DFA and NFA
Conversion from NFA to DFA
Turing Machine in TOC
Introduction of Pushdown Automata
Minimization of DFA
Calculator Program with Batch Scripting in Windows

07 Sep, 2020
By using the Batch Scripting of command prompt one could even design a normal basic calculator that takes expressions and returns the result. Type the following script in notepad or any other text editor software:
@echo off
:a
echo ________Calculator________
echo.
set /p expression= Enter expression to calculate:
set /a ans=%expression%
echo.
echo = %ans%
echo
pause
cls
goto a

After writing the above text in a text editor, save the file with the extension “ .bat “. To run the program, simply double-click on the saved file, the program will open and the code will get executed in Command Prompt. It should look something like:
Welcome screen!
@echo off — signals Command Prompt to not display the commands (code).
: a — the signals starting point of a loop.
echo — same as print/println/printf/etc. Displays the specified message as output to the screen.
echo. — will output a blank line.
set — used to set value against a variable.
set /p expression — /p signals that this is prompt. “Expression” is just a variable name.
set /a ans – /a signal that variable has a numerical value. “ans” is the variable name.
%ans% — calls the variable “ans”
pause — will pause/ stop the program flow until the user will press a key (any key) and continue the program flow only when the users press a key (any).
cls – clears the screen
goto a- signals to go to the start point of the loop, effectively looping our calculator program so it can take in and calculate new expression.
Program Test Cases:
The program can handle simple expression calculations like:
Calculating Simple Expression
And it can also handle complex expressions, such as:
Calculating Complex Expression
Note:-
The above program is calculating expressions by utilizing the calculator (that can perform simple arithmetic on 32-bit signed integers) that comes with Command Prompt.
Since we are utilizing built-in calculator of Command Prompt, we can only perform following expression: + (addition), – (subtraction), * (multiplication),  / (divide), % (modulo).
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1
numpy.isscalar() in Python

29 Nov, 2018
numpy.isscalar(num) : This is a logical function that returns true if the type of input num is scalar.
Parameters :
num : Input argument of any type and shape.
Return :
True, if input is scalar; else False

Code 1 : Working
# Python program explaining# isscalar() functionimport numpy as np  in_array = [1, 3, 5, 4]print ("Input array : ", in_array)  isscalar_values = np.isscalar(in_array)print ("\nIs scalar : ", isscalar_values)  # inputprint ("\nisscalar(7) : ", np.isscalar(7))  # list input print ("\nisscalar([7]) : ", np.isscalar([7]))
Output :
Input array :  [1, 3, 5, 4]

Is scalar :  False

isscalar(7) :  True

isscalar([7]) :  False

References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isscalar.html.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
log() function in C++

10 Dec, 2019
Log() function in C++ : The log() function in C++ returns the natural logarithm (base-e logarithm) of the argument passed in the parameter.
Syntax for returning natural logarithm:result = log(x)
Syntax for returning logarithm (base-10 logarithm) of the argument.result = log10(x)
The parameters can be of any data-type like int, double or float or long double.
Log() function returns value according to the following conditions:
..a) if x>1 then positive..b) if 0<x<1 returns a negative value..c) if x=1 then it returns 0..d) if x=0 then it returns -inf..e) if x<0 then it returns NaN(not a number)
// CPP program to implement log() function#include <bits/stdc++.h>using namespace std;  // function to evaluate natural logarithm base-edouble valueE(double d){    return log(d);}  // function to evaluate logarithm base-10double value10(double d){    return log10(d);}  // driver program to test the above functionint main(){    double d = 10;    cout << "The logarithm value(base-e) of " << d          << " is " << valueE(d) << endl;    cout << "The logarithm value(base-10) of " << d          << " is " << value10(d) << endl;    return 0;}
Output:
The logarithm value(base-e) of 10 is 2.30259
The logarithm value(base-10) of 10 is 1

Application:One of the applications of log() function is to calculated values related to log, for e.g., while finding polite number we need the formula to be written in code, for that we can use log() function. Given below is an implementation of log() function.
// CPP program to find Nth polite number#include <bits/stdc++.h>using namespace std;  // function to evaluate n-th polite numberdouble polite(double n){    n += 1;    double base = 2;    return n + (log((n + (log(n) /                 log(base))))) / log(base);}  // driver codeint main(){    double n = 7;    cout << (int)polite(n);    return 0;}
Output:
11 

mathemagic
a7medsaber
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.