code-rag-bench/online-tutorials huggingface dataset:
Node.js - First Application

Before creating an actual "Hello, World!" application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important components −
Import required modules − We use the require directive to load Node.js modules.
Import required modules − We use the require directive to load Node.js modules.
Create server − A server which will listen to client's requests similar to Apache HTTP Server.
Create server − A server which will listen to client's requests similar to Apache HTTP Server.
Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows −
var http = require("http");

We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return "Hello World".
http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine.
Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −
var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.
Server running at http://127.0.0.1:8081/

Open http://127.0.0.1:8081/ in any browser and observe the following result.
Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081.

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    88 Lectures 
     17 hours 

 Eduonix Learning Solutions

    32 Lectures 
     1.5 hours 

 Richard Wells

    8 Lectures 
     33 mins

 Anant Rungta

    9 Lectures 
     2.5 hours 

 SHIVPRASAD KOIRALA

    97 Lectures 
     6 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
C++ Program to Implement Queue Using Two Stacks

The stack which is implemented as LIFO, where insertion and deletion are done from the same end, top. The last element that entered is deleted first.
Stack operations are −
push (int data) − Insertion at top
int pop() − Deletion from top
The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first.
Queue operations are −
EnQueue (int data) − Insertion at rear end
int DeQueue() − Deletion from front end
This is a C++ Program to Implement Queue Using Two Stacks.
function enQueue() to enqueue an item to queue:Push m to s1.
Push m to s1.
function deQueue() to dequeue items from queue.If both the stacks empty then print queue is empty.If s2 is empty then move elements from s1 to s2.Pop the elements from s2 and return it.
If both the stacks empty then print queue is empty.
If s2 is empty then move elements from s1 to s2.
Pop the elements from s2 and return it.
function push() to push item in the stack.
function pop() to pop out an item from the stack.
#include<stdlib.h>
#include<iostream>
using namespace std;

struct nod//node declaration {
   int d;
   struct nod *n;
};

void push(struct nod** top_ref, int n_d);//functions prototypes.
int pop(struct nod** top_ref);

struct queue {
   struct nod *s1;
   struct nod *s2;
};

void enQueue(struct queue *q, int m) {
   push(&q->s1, m);
}

int deQueue(struct queue *q) {
   int m;
   if (q->s1 == NULL && q->s2 == NULL) {
      cout << "Queue is empty";
      exit(0);
   }
   if (q->s2 == NULL) {
      while (q->s1 != NULL) {
         m = pop(&q->s1);
         push(&q->s2, m);
      }
   }
   m = pop(&q->s2);
   return m;
}

void push(struct nod** top_ref, int n_d) {
   struct nod* new_node = (struct nod*) malloc(sizeof(struct nod));

   if (new_node == NULL) {
      cout << "Stack underflow \n";
      exit(0);
   }
   //put items on stack
   new_node->d= n_d;
   new_node->n= (*top_ref);
   (*top_ref) = new_node;
}

int pop(struct nod** top_ref) {
   int res;
   struct nod *top;
   if (*top_ref == NULL)//if stack is null {
      cout << "Stack overflow \n";
      exit(0);
   } else { //pop elements from stack
      top = *top_ref;
      res = top->d;
      *top_ref = top->n;
      free(top);
      return res;
   }
}

int main() {
   struct queue *q = (struct queue*) malloc(sizeof(struct queue));
   q->s1 = NULL;
   q->s2 = NULL;
   cout << "Enqueuing..7";
   cout << endl;
   enQueue(q, 7);
   cout << "Enqueuing..6";
   cout << endl;
   enQueue(q, 6);
   cout << "Enqueuing..2";
   cout << endl;
   enQueue(q, 2);
   cout << "Enqueuing..3";
   cout << endl;
   enQueue(q, 3);

   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
}
Enqueuing..7
Enqueuing..6
Enqueuing..2
Enqueuing..3
Dequeuing...7
Dequeuing...6
Dequeuing...2
How can we filter a JTable in Java?

A JTable provides a very flexible possibility to create and display tables. The TableModel interface defines methods for objects that specify the contents of a table. The AbstractTableModel class is typically extended to provide a custom implementation of a model table. A JTable class provides the ability to edit tables using the method setCellEditor() allows an object of the TableCellEditor interface.
We can filter a table using the setRowFilter() method of TableRowSorter class.
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.table.*;
public class FilterTableTest extends JFrame {
   private JTable table;
   private TableModel model;
   public FilterTableTest() {
      setTitle("FilterTable Test");
      Object rows[][] = {{"Adithya", "Content Developer", 25000}, {"Jai", "SME", 30000},  {"Chaitanya", "Java Engineer", 45000}, {"Ramesh", "Scala Developer", 40000}, {"Ravi", "SAP  Consultant", 70000}};
      Object columns[] = {"Name", "Designation", "Salary"};
      model = new DefaultTableModel(rows, columns) {
         public Class getColumnClass(int column) {
            Class returnValue;
            if((column >= 0) && (column < getColumnCount())) {
               returnValue = getValueAt(0, column).getClass();
            } else {
               returnValue = Object.class;
            }
            return returnValue;
         }
      };
      table = new JTable(model);
      final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
      table.setRowSorter(sorter);
      add(new JScrollPane(table), BorderLayout.CENTER);
      JPanel panel = new JPanel(new BorderLayout());
      JLabel label = new JLabel("Filter");
      panel.add(label, BorderLayout.WEST);
      final JTextField filterText = new JTextField("");
      panel.add(filterText, BorderLayout.CENTER);
      add(panel, BorderLayout.NORTH);
      JButton button = new JButton("Filter");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String text = filterText.getText();
            if(text.length() == 0) {
               sorter.setRowFilter(null);
            } else {
               try {
                  sorter.setRowFilter(RowFilter.regexFilter(text));
               } catch(PatternSyntaxException pse) {
                     System.out.println("Bad regex pattern");
               }
             }
         }
      });
      add(button, BorderLayout.SOUTH);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new FilterTableTest();
   }
}
ES6 - Array Method sort()

sort() method sorts the elements of an array.
array.sort( compareFunction );    

compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically.
compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically.
Returns a sorted array.
var arr = new Array("orange", "mango", "banana", "sugar"); 
var sorted = arr.sort(); 
console.log("Returned string is : " + sorted );   
Returned string is : banana,mango,orange,sugar 


    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
\surd - Tex Command

\surd - Used to create surd symbol.
{ \surd}
\surd command draws surd symbol.

\surd

√



\surd

√


\surd

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Java Examples - Rename a File

How to rename a file?
This example demonstrates how to renaming  a file using oldName.renameTo(newName) method of File class.
import java.io.File;

public class Main {
   public static void main(String[] args) {
      File oldName = new File("C:/program.txt");
      File newName = new File("C:/java.txt");
      
      if(oldName.renameTo(newName)) {
         System.out.println("renamed");
      } else {
         System.out.println("Error");
      }
   }
}
The above code sample will produce the following result.To test this example, first create a file 'program.txt' in 'C' drive.
renamed

The following is another example of rename a file in java
import java.io.File;

public class RenameFileExample { 
   public static void main(String[] args) { 
      File oldfile = new File("C:/oldfile_name.txt");
      File newfile = new File("C:/newfile_name.txt");

      if(oldfile.renameTo(newfile)) {
         System.out.println("File name changed succesful");
      } else {
         System.out.println("Rename failed");
      } 
   }
}
The above code sample will produce the following result. To test this example, first create a file 'oldfile_name.txt' in 'C' drive.
File name changed succesful

 Print
 Add Notes
 Bookmark this page
How to pass data from child component to its parent in ReactJS ?

22 Feb, 2021
Following are the steps to pass data from child component to parent component:
In the parent component, create a callback function. This callback function will retrieve the data from the child component.
Pass the callback function to the child as a props from the parent component.
The child component calls the parent callback function using props and passes the data to the parent component.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Filepath- src/App.js:
Javascript
import React from 'react';import Child from './Child'class App extends React.Component{             state = {        name: "",       }      handleCallback = (childData) =>{        this.setState({name: childData})    }      render(){        const {name} = this.state;        return(            <div>                <Child parentCallback = {this.handleCallback}/>                {name}            </div>        )    }}export default App
Filepath- src/component/Child.js
Javascript
import React from 'react'class Child extends React.Component{        onTrigger = (event) => {        this.props.parentCallback(event.target.myname.value);        event.preventDefault();    }      render(){        return(        <div>            <form onSubmit = {this.onTrigger}>                <input type = "text"                 name = "myname" placeholder = "Enter Name"/>                <br></br><br></br>                <input type = "submit" value = "Submit"/>                <br></br><br></br>            </form>        </div>        )    }}export default Child
Output:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get first element of each sublist

10 Jul, 2022
Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists. Examples:
Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
Output : [1, 3, 6]

Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']]
Output : ['x', 'm', 'a', 'u']
  Approach #1 : List comprehension 
Python3
# Python3 program to extract first and last# element of each sublist in a list of lists def Extract(lst):    return [item[0] for item in lst]     # Driver codelst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]print(Extract(lst))
[1, 3, 6]
Time Complexity: O(n)
Space Complexity: O(n) (length of the list given as argument)
  Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the ‘lst’ as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose. 
Python3
# Python3 program to extract first and last# element of each sublist in a list of lists def Extract(lst):    return list(list(zip(*lst))[0])     # Driver codelst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]print(Extract(lst))
[1, 3, 6]
Time Complexity: O(n) (zip function has complexity of O(1) and conversion to list has O(n))
Space Complexity: O(n) (length of the list given as argument)
Another method of using zip is given below:- 
Python3
def Extract(lst):    return list(next(zip(*lst)))
  Approach #3 : Using itemgetter() 
Python3
# Python3 program to extract first and last# element of each sublist in a list of listsfrom operator import itemgetter def Extract(lst):    return list( map(itemgetter(0), lst ))     # Driver codelst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]print(Extract(lst))
[1, 3, 6]
Time Complexity: O(n) (itemgetter has O(1) and conversion to list O(n))
Space Complexity: O(n)
harshmaster07705
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js response.getHeaders() Method

15 Sep, 2020
The response.getHeaders() (Added in v7.7.0) method is an inbuilt method of the ‘http’ module which returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the response.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.
In order to get a response and a proper result, we need to import ‘http’ module.
const http = require('http');

Syntax:
response.getHeaders()

Parameters: This property does not accept any parameters.
Return Value <Object>: It returns a shallow copy of the current outgoing headers. 
The below examples illustrate the use of response.getHeaders() property in Node.js.
Example: Filename: index.js
// Node.js program to demonstrate the // response.getHeaders() Method  // Importing http modulevar http = require('http');  // Setting up PORTconst PORT = process.env.PORT || 3000;  // Creating http Servervar httpServer = http.createServer(          function(req, response) {    // Setting up Headers  response.setHeader('Alfa', 'Beta');  response.setHeader('Cookie-Setup',         ['Alfa=Beta', 'Beta=Romeo']);     // Getting the set Headers  const headers = response.getHeaders();    // Printing those headers  console.log(headers);    // Prints Hello GeeksforGeeks...   // on browser in response  response.write('Hello GeeksforGeeks...');  response.end();});  // Listening to http ServerhttpServer.listen(PORT, () => {    console.log("server started at 3000...")});
Output:
In Console:>> server started at 3000...>> [Object: null prototype] {alfa: ‘Beta’,‘cookie-setup’: [‘Alfa=Beta’, ‘Beta=Romeo’]}>> [Object: null prototype] {alfa: ‘Beta’,‘cookie-setup’: [‘Alfa=Beta’, ‘Beta=Romeo’]}
Now run http://localhost:3000/ in the browser.
Output: (In Browser)
Hello GeeksforGeeks...
Reference: https://nodejs.org/api/http.html#http_response_getheaders
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Express.js req.params Property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert UTF-8 to Unicode in Java

Before moving onto their conversions, let us learn about Unicode and UTF-8.
Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \u0000 and the highest value is \uFFFF.
UTF-8 is a variable width character encoding. UTF-8 has the ability to be as condense as ASCII but can also contain any unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4.
In order to convert UTF-8 to Unicode, we create a String Object which has the parameters as the UTF-8 byte array name and the charset the array of bytes which it is in i.e. UTF-8.
Let us see a program to convert UTF-8 to Unicode by creating a new String Object.
 Live Demo
public class Example {
   public static void main(String[] args) throws Exception {
      String str = "hey\u6366";
      byte[] charset = str.getBytes("UTF-8");
      String result = new String(charset, "UTF-8");
      System.out.println(result);
   }
}
hey捦
Let us understand the above program. Firstly we converted a given Unicode string to UTF-8 for future verification using the getBytes() method −
String str = "hey\u6366";
byte[] charset = str.getBytes("UTF-8")
Then we converted the charset byte array to Unicode by creating a new String object as follows −
String result = new String(charset, "UTF-8");
System.out.println(result);
How to get the IIS Application Pool queue length using PowerShell?

From the GUI, to retrieve the Application Pool queue length you need to check the Advanced Settings of the Application Pool.
To get the IIS application Pool queue length using PowerShell, first, we need to the application pool name. There are two ways (and maybe others) to retrieve once we have the name of the application pool.
For example, we need to retrieve the queue length for the application pool DefaultAppPool.
(Get-IISAppPool -Name DefaultAppPool).queuelength
To run the above command, you need the IISAdministration Module. You can also use the IIS PS drive but for that WebAdministration module should be loaded.
(Get-ItemProperty IIS:\AppPools\DefaultAppPool).queuelength
Move all zeroes to end of array in C++

Given array with multiple zeroes in it. We have to move all the zeroes in the array to the end. Let's see an example.
Input
arr = [4, 5, 0, 3, 2, 0, 0, 0, 5, 0, 1]
Output
4 5 3 2 5 1 0 0 0 0 0
Initialise the array.
Initialise the array.
Initialise an index to 0.
Initialise an index to 0.
Iterate over the given array.If the current element is not zero, then update the value at the index with the current element.Increment the index.
Iterate over the given array.
If the current element is not zero, then update the value at the index with the current element.
If the current element is not zero, then update the value at the index with the current element.
Increment the index.
Increment the index.
Write a loop that iterates from the above index to nUpdate all the elements to 0.
Write a loop that iterates from the above index to n
Update all the elements to 0.
Update all the elements to 0.
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
void moveZeroesToEnd(int arr[], int n) {
   int index = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] != 0) {
         arr[index++] = arr[i];
      }
   }
   while (index < n) {
      arr[index++] = 0;
   }
}
int main() {
   int arr[] = {4, 5, 0, 3, 2, 0, 0, 0, 5, 0, 1};
   int n = 11;
   moveZeroesToEnd(arr, n);
   for (int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
   return 0;
}
If you run the above code, then you will get the following result.
4 5 3 2 5 1 0 0 0 0 0
JavaScript Number - toString()

This method returns a string representing the specified object. The toString() method parses its first argument, and attempts to return a string representation in the specified radix (base).
Its syntax is as follows −
number.toString( [radix] )

radix − An integer between 2 and 36 specifying the base to use for representing numeric values.
Returns a string representing the specified Number object.
Try the following example.
<html>
   <head>
      <title>JavaScript toString() Method </title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         num = new Number(15);
         document.write("num.toString() is " + num.toString());
         document.write("<br />"); 
         
         document.write("num.toString(2) is " + num.toString(2)); 
         document.write("<br />"); 
         
         document.write("num.toString(4) is " + num.toString(4)); 
         document.write("<br />"); 
      </script>      
   </body>
</html>
num.toString() is 15
num.toString(2) is 1111
num.toString(4) is 33


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to add colour to text Python? - GeeksforGeeks

24 Jan, 2021
There are multiple ways supported by python in which color can be added ot text. This article discusses all with proper examples to help you understand better.
ANSI escape sequence is a sequence of ASCII characters, the first two of which are the ASCII “Escape” character 27 (1Bh) and the left-bracket character ” [ ” (5Bh). The character or characters following the escape and left-bracket characters specify an alphanumeric code that controls a keyboard or display function.
To add color and style to text, you should create a class called ANSI, and inside this class, declare the configurations about the text and color with code ANSI.
Approach
Declare class ANSI
Declare functions in this class to perform a special text formatting task
Call the required function using the class object
Functions Used:
background: allows background formatting. Accepts ANSI codes between 40 and 47, 100 and 107
style_text: corresponds to formatting the style of the text. Accepts ANSI code between 0 and 8
color_text:  Corresponds to the text of the color. Accepts ANSI code between 30 and 37, 90 and 97
Example:
Python3
class ANSI():    def background(code):        return "\33[{code}m".format(code=code)      def style_text(code):        return "\33[{code}m".format(code=code)      def color_text(code):        return "\33[{code}m".format(code=code)    example_ansi = ANSI.background(    97) + ANSI.color_text(35) + ANSI.style_text(4) + " TESTE ANSI ESCAPE CODE"print(example_ansi)
Table ANSI Escape Code
TABLE ANSI ESCAPE CODE
Output:
Example Ansi Escape Code
To use this module it first needs to be installed using pip since it doesn’t come inbuilt with python.  
pip install termcolor
Approach
Import module
Use colored() function to add color to the text
Print colored text 
Syntax:
colored(text, color, attribute_array)
Example:
Python3
from termcolor import colored  text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])  print(text)
Output:
It makes ANSI escape character sequences for producing colored terminal text and cursor positioning work under MS Windows.
It needs to be installed manually using pip
pip install colorama
Approach
Import module
Call Fore with required color
Pass the text to be colored.
Print result
Syntax:
Fore.(color_of_text, text)
In colorama, the implementation is different in comparison to ANSI escape and Colored.
Example:
Python
from colorama import Fore, Back, Style  print(Fore.RED + 'some red text')
Output:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to validate an email in ReactJS ?

16 Dec, 2020
Email validation is an important step in every application in order to authenticate user email. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered email and checking whether it is valid or not using the npm module in React Application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app emailvalidatordemo
Step 2: After creating your project folder i.e. emailvalidatordemo, move to it using the following command:
cd emailvalidatordemo
Step 3: After creating the React application, Install the validator module using the following command:
npm install validator
Project Structure: It Will look like the following.
Project Structure
App.js: Now write down the following code in App.js file. Here, App is our default component where we have written our code to validate email with basic UI.
Javascript
import React, { useState } from "react";import validator from 'validator'  const App = () => {    const [emailError, setEmailError] = useState('')  const validateEmail = (e) => {    var email = e.target.value      if (validator.isEmail(email)) {      setEmailError('Valid Email :)')    } else {      setEmailError('Enter valid Email!')    }  }    return (    <div style={{      margin: 'auto',      marginLeft: '300px',    }}>      <pre>        <h2>Validating Email in ReactJS</h2>        <span>Enter Email: </span><input type="text" id="userEmail"         onChange={(e) => validateEmail(e)}></input> <br />        <span style={{          fontWeight: 'bold',          color: 'red',        }}>{emailError}</span>      </pre>    </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:
The following will be the output if the user enters an invalid email as shown below:
The following will be the output if the user enters a valid email as shown below:
react-js
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to know which php.ini file is used ?

11 Jun, 2020
The php.ini file is the default configuration file used for running applications that require PHP. It is an effective way to work on PHP’s functionality. It is used to control variables like file timeouts, sizes of the upload, and the limits of the resource on which it works.
1. Check php.ini in CGI (Common Gateway Interface): Here, we can use two inbuilt functions to get which php.ini used.
php_ini_loaded_file: It retrieves a path to the loaded php.ini file.PHPPHP<?php$php_inipath = php_ini_loaded_file();  if ($php_inipath) {    echo 'Loaded php.ini is: ' . $php_inipath;} else {    echo 'A php.ini file is not loaded';}?>
PHP
<?php$php_inipath = php_ini_loaded_file();  if ($php_inipath) {    echo 'Loaded php.ini is: ' . $php_inipath;} else {    echo 'A php.ini file is not loaded';}?>
php_ini_scanned_files: It returns a list of .ini files parsed from the additional ini directory.PHPPHP<?phpif ($list_of_files = php_ini_scanned_files()) {    if (strlen($list_of_files) > 0) {        $files = explode(', ', $list_of_files);          foreach ($files as $file) {            echo "<li>" . trim($file) . "</li>\n";        }    }}?>
PHP
<?phpif ($list_of_files = php_ini_scanned_files()) {    if (strlen($list_of_files) > 0) {        $files = explode(', ', $list_of_files);          foreach ($files as $file) {            echo "<li>" . trim($file) . "</li>\n";        }    }}?>
2. Check php.ini in CLI (Command Line Interface): To know about php.ini, simply run on CLI.
php --ini
It look for Loaded Configuration File in output for the location of php.ini used by your CLI.
Note: If we run a PHP script from CLI, it is possible that a different php.ini file will be used than if a server (i.e. apache or Nginx ) runs it.
3. Other Options to know about php.ini:
php -i|grep ‘php.ini’
Simply create ‘information.php’ file in the web-root and add code(below), and run it in your browser.<?php phpinfo(); ?>
<?php phpinfo(); ?>
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
Multiple Line Plots or Time Series Plots with ggplot2 in R

24 Oct, 2021
In this article, we will discuss how to plot Multiple Line Plots or Time Series Plots with the ggplot2 package in the R Programming Language. We can create a line plot using the geom_line() function of the ggplot2 package.
Syntax:
ggplot( df, aes( x, y ) ) + geom_line()
where, 
df: determines the dataframe used
x and y: determines the axis variables
Example:
Here, is a basic line plot made using the geom_line() function of the ggplot2 package. Here, the dataset used is the city crime dataset from 1975 to 2015 which can be downloaded from ucr_crime.
R
# load package tidyverselibrary(tidyverse)   # read sample data from given csv filesample_data <- read_csv("ucr_crime_1975_2015.csv")  # plot a basic line plot using ggplot() function# color parameter is used to colot the plot according # to department_nameggplot(sample_data, aes(x=year, violent_per_100k)) +  # geom_line function is used to plot line plotgeom_line()
Output:
Here, the resulting plot doesn’t look like multiple time series. It is because for a multiple time series in the above example we just used two variables and those two are needed for a single time series plot. To get a multiple time series plot we need one more differentiating variable. So we will use the color parameters to group and color the line plot according to another variable of differentiating caliber.
Syntax:
ggplot( df, aes( x, y, color ) ) + geom_line()
where,
df: determines the data frame used
x and y: determines the axis variable
color: determines the variable according to which plot is grouped and colored
Example:
Here, is a basic line plot made using the geom_line() function of the ggplot2 package. Here we have grouped and colored the plot according to department_name. This creates the necessary three differentiating variables for multiple time series.
R
# load package tidyverselibrary(tidyverse)   # read sample data from given csv filesample_data <- read_csv("ucr_crime_1975_2015.csv")  # plot a basic line plot using ggplot() function# color parameter is used to colot the plot according# to department_nameggplot(sample_data, aes(x=year, violent_per_100k, color=department_name)) +  # geom_line function is used to plot line plotgeom_line()+  # theme with legend.position as none removes the # legend form plottheme(legend.position = "none")
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
Find the column and row names in the R data frame based on condition.

To find the column names and row names in an R data frame based on a condition, we
can use row.names and colnames function. The condition for which we want to find the
row names and column names can be defined inside these functions as shown in the
below Examples.
Following snippet creates a sample data frame −
x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
df1

The following dataframe is created
  x1 x2 x3
1  1 11 15
2  3  6 15
3  0  9 18
4  2 10 26
5  1  9 17
6  1  7 23
7  0 11 21
8  2 11 23
9  1  6 22
10 2  6 28
11 2  7 22
12 0  8 16
13 1  7 28
14 1  7 25
15 0  6 14
16 0 10 23
17 0 12 16
18 0  8 23
19 2  8 17
20 2  8 21
To find which rows has value 17 in it on the above created data frame, add the following
code to the above snippet −
x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
row.names(df1[which(df1==17,arr.ind=T)[,1],] )
If you execute all the above given snippets as a single program, it generates the
following Output −
[1] "5" "19"

To find which columns has value 17 in it on the above created data frame, add the
following code to the above snippet −
x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
colnames(df1)[apply(df1, 2, function(x) any(x==17))]
If you execute all the above given snippets as a single program, it generates the
following Output −
[1] "x3"

Following snippet creates a sample data frame −
y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
df2
The following dataframe is created
   y1 y2 y3
1  75 52 32
2  37  5 46
3  43 31 60
4 100 30 11
5  28 18 79
6  31 80 53
7   8 85 49
8  62 38 56
9  48 82 15
10 97 48 69
11 69 25 40
12 12 92 21
13 77 55 26
14 39 95 63
15 82 61 75
16 98 40 14
17 61 78 22
18 93 63 58
19 10 21 17
20 2 68 83
To find which rows has value 92 in it on the above created data frame, add the following
code to the above snippet −
y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
row.names(df2[which(df2==92,arr.ind=T)[,1],] )
If you execute all the above given snippets as a single program, it generates the
following Output −
[1] "12"

To find which columns have value 92 in it on the above created data frame, add the
following code to the above snippet −
y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
colnames(df2)[apply(df2, 2, function(x) any(x==92))]
If you execute all the above given snippets as a single program, it generates the
following Output −
[1] "y2"
\mathop - Tex Command

\mathop - forces the argument to be treated in the 'large operator' class.
{ \mathop #1}
\mathop command is used to force the argument to be treated in the 'large operator' class.

atbtc

atbtc


a\mathop{t}b\mathop{t}c

at⁡bt⁡c


\star_a^b

⋆ab



atbtc

atbtc


atbtc
a\mathop{t}b\mathop{t}c

at⁡bt⁡c


a\mathop{t}b\mathop{t}c
\star_a^b

⋆ab


\star_a^b

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to get mapped drives using PowerShell?

There are few methods to get the mapped network drive using PowerShell.
CMD command method.
CMD command method.
You can use the cmd command net use in PowerShell to get the mapped drives.
net use
PS C:\WINDOWS\system32> net use
New connections will be remembered.
Status       Local     Remote                    Network

-------------------------------------------------------------------------------
OK           K:        \\localhost\shared folder Microsoft Windows Network
OK           L:        \\localhost\Shared        Microsoft Windows Network
The command completed successfully.
To get the mapped drives on the remote computer,
Invoke-Command -ComputerName RemoteComputer -ScriptBlock{Net use}

Or
Invoke-Command -ComputerName RemoteComputer -ScriptBlock{Invoke-Expression -Command "Net use"}
PowerShell WMI and CimInstance method.
PowerShell WMI and CimInstance method.
You can also use the PowerShell WMI method with classname Win32_MappedLogicalDisk to get the mapped network drive on the local computer.
Get-WmiObject -ClassName Win32_MappedLogicalDisk | Select PSComputerName, Name,ProviderName

PSComputerName  Name ProviderName
--------------  ---- ------------
DESKTOP-9435KM9 K:   \\localhost\shared folder
DESKTOP-9435KM9 L:   \\localhost\Shared
To get the same on the remote computer.
Get-WmiObject -ClassName Win32_MappedLogicalDisk –ComputerName RemoteComputer | Select PSComputerName, Name,ProviderName

Using the CIM method.
Get-CimInstance -ClassName Win32_MappedLogicalDisk | Select SystemName, DeviceID, ProviderName
On the remote system.
Get-CimInstance -ClassName Win32_MappedLogicalDisk –ComputerName RemoteSystem | Select SystemName, DeviceID, ProviderName

Get-PSDrive method.
Get-PSDrive method.
On the local computer, you can run Get-PSDrive PowerShell cmdlet but it will get all the available drives. To get the network drives we need to filter the output as given below.
Get-PSDrive | where{$_.DisplayRoot -match "\\"}
Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
K                 318.16         47.24 FileSystem    \\localhost\shared folder
M                 286.07         79.36 FileSystem    \\localhost\Shared Folder
To get mapped drives on the remote computer.
Invoke-Command –ComputerName RemoteComputer -ScriptBlock{Get-PSDrive | where{$_.DisplayRoot -match "\\"}}
Print Number series without using any loop in Python Program

In this article, we will learn about the solution to the problem statement given below −
Given Two number N and K, our problem is to subtract a number K from N until number(N) is greater than zero(0), once the N becomes negative or zero then we start adding K to it until that number becomes the original number(N).
For Example
N = 10
K = 4
Output
10 6 2 -2 2 6 10
we call the function again and again until N is greater than zero (in every function call we subtract K from N ).
we call the function again and again until N is greater than zero (in every function call we subtract K from N ).
Once the number becomes negative or zero we start adding K in each function call until the number becomes the original number.
Once the number becomes negative or zero we start adding K in each function call until the number becomes the original number.
Here we used a single function for purpose of addition and subtraction but to switch between addition or subtraction function we used a Boolean type variable flag.
Here we used a single function for purpose of addition and subtraction but to switch between addition or subtraction function we used a Boolean type variable flag.
Now let’s observe the implementation in Python
def PrintNumber(N, Original, K, flag):
   #print the number
   print(N, end = " ")
   #if number become negative
   if (N <= 0):
      if(flag==0):
         flag = 1
      else:
         flag = 0
   if (N == Original and (not(flag))):
      return
   # if flag is true
   if (flag == True):
      PrintNumber(N - K, Original, K, flag)
      return
   if (not(flag)):
      PrintNumber(N + K, Original, K, flag);
      return
N = 10
K = 4
PrintNumber(N, N, K, True)
10 6 2 -2 2 6 10
Here all variables are declared in global namespace as shown in the image below −
In this article, we learned about the terminology for printing a number series without using any kind of looping construct in Python 3.x. Or earlier.
C - Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of the programming languages −
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
You can use one if or else if statement inside another if or else if statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
You can use one switch statement inside another switch statement(s).
We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

15 Oct, 2019
Consider the following relational schema:
  employee(empId, empName, empDept)
  customer(custId, custName, salesRepId, rating)
salesRepId is a foreign key referring to empId of the employee relation. Assume that each employee makes a sale to at least one customer. What does the following query return?
SELECT empName
       FROM employee E
       WHERE NOT EXISTS ( SELECT custId
                          FROM customer C
                          WHERE C.salesRepId = E.empId
                            AND C.rating <> `GOOD`);
(A) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.(B) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.(C) Names of all the employees with none of their customers having a ‘GOOD’ rating.(D) Names of all the employees with all their customers having a ‘GOOD’ rating.Answer: (D)Explanation: If any employee has received rating other than ‘GOOD’ from any of their customers, then there will be some rows returned by the inner query;And NOT EXISTS will return false so those employees won’t be printed.
Only those employees which have got rating ‘GOOD’ from all of their customers will be printed.Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2001 | Question 48