code-rag-bench/online-tutorials huggingface dataset:
Python - Sort given list of strings by part the numeric part of string - GeeksforGeeks

20 Jul, 2021
Given a list of strings. The task is to sort the list by the numeric part of the string.
Examples:
Input : test_list = [“Gfg34”, “is67”, “be3st”, “f23or”, “ge9eks”] Output : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’] Explanation : 3 < 9 < 23 < 34 < 67, numbers extracted from strings.
Input : test_list = [“Gfg4”, “is67”, “be3st”, “f23or”, “ge9eks”] Output : [‘be3st’, ‘Gfg4’, ‘ge9eks’, ‘f23or’, ‘is67’] Explanation : 3 < 4 < 9 < 23 < 67, numbers extracted from strings. 
Method #1 : Using sort() + re.findall()
In this, we perform the task of sorting using sort(), the explicit function is used to extract numbers using findall().
Python3
# Python3 code to demonstrate working of# Sort Strings on numerical substrings# Using sort() + findall()import re # helper function to perform sortdef num_sort(test_string):    return list(map(int, re.findall(r'\d+', test_string)))[0] # initializing listtest_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"] # printing original listprint("The original list is : " + str(test_list)) # calling functiontest_list.sort(key=num_sort) # printing resultprint("Strings after numerical Sort  : " + str(test_list))
Output:
The original list is : [‘Gfg34’, ‘is67’, ‘be3st’, ‘f23or’, ‘ge9eks’] Strings after numerical Sort  : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’]
Method #2 : Using sort() + lambda + findall()
In this, we perform a similar function, but the difference being we use lambda function rather than an external function to perform the task of sorting.
Python3
# Python3 code to demonstrate working of# Sort Strings on numerical substrings# Using sort() + lambda + findall()import re # initializing listtest_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"] # printing original listprint("The original list is : " + str(test_list)) # findall() getting all integers.# conversion to integers using map()test_list.sort(key=lambda test_string : list(    map(int, re.findall(r'\d+', test_string)))[0]) # printing resultprint("Strings after numerical Sort  : " + str(test_list))
Output:
The original list is : [‘Gfg34’, ‘is67’, ‘be3st’, ‘f23or’, ‘ge9eks’] Strings after numerical Sort  : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’]
arorakashish0911
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Node.js Worker Threads - GeeksforGeeks

08 Oct, 2021
Worker Threads in Node.js is useful for performing heavy JavaScript tasks. With the help of threads, Worker makes it easy to run javascript codes in parallel making it much faster and efficient. We can do heavy tasks without even disturbing the main thread. Worker threads were not introduced in the older versions of Node. Therefore first update your Node.js for getting started.
Now create two files for implementing the thread as shown below:Filename: worker.js
const { workerData, parentPort }         = require('worker_threads')  console.log('Technical Articles on '                    + workerData);  parentPort.postMessage(    { fileName: workerData, status: 'Done' })
Here, the workerData and parentPort are part of Worker Thread. The workerData is used for fetching the data from the thread and parentPort is used for manipulating the thread. The postMessage() method is used for posting the given message in the console by taking the filename as fetched by workerData.
Filename: index.js
const { Worker } = require('worker_threads')  function runService(workerData) {    return new Promise((resolve, reject) => {        const worker = new Worker(                './worker.js', { workerData });        worker.on('message', resolve);        worker.on('error', reject);        worker.on('exit', (code) => {            if (code !== 0)                reject(new Error(`Stopped the Worker Thread with the exit code: ${code}`));        })    })}  async function run() {    const result = await runService('GeeksForGeeks')    console.log(result);}  run().catch(err => console.error(err))
Here, the function runService() return a Promise and runs the worker thread. The function run() is used for calling the function runService() and giving the value for workerData.
Step to run this application: Run the following command:
node index.js
The output for above following command is shown below:
Technical Articles on GeeksForGeeks
{ fileName: 'GeeksForGeeks', status: 'Done' }

Conclusion: With worker threads, we can achieve a much efficient application without creating a deadlock situation. This is how you can import the worker thread in an application and implement the thread.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
ReactJS unmountComponentAtNode() Method - GeeksforGeeks

26 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component.
In class-based components, the unmountComponentAtNode() method Remove a mounted React component from the DOM.
Creating React Application:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import ReactDOM from 'react-dom';  // Exporting your App Componentexport default function App() {    // Function to unmount root component  function unm() {    ReactDOM.unmountComponentAtNode(document.getElementById("root"));  }    return (    <div>      <h1>GeeksforGeeks</h1>      <div>Hi Geek, this is the rendered content</div>      <button onClick={unm}>Unmount</button>    </div>  );}
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:
Reference:https://reactjs.org/docs/react-dom.html#unmountcomponentatnode
ReactJS-Methods
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to add new value to an existing array in JavaScript?

To add new value to an existing array, use the JavaScript splice() method.
You can try to run the following code to add new value −
Live Demo
<html>
   <head>
      <title>JavaScript Array splice Method</title>
   </head>
   <body>
      <script>
         var arr = ["orange", "mango", "banana", "sugar", "tea"];
         document.write("Original array:"+arr)

         var newArr = arr.splice(2, 0, "water");
         document.write("<br>After adding new element: " + arr );
      </script>
   </body>
</html>
Original array:orange,mango,banana,sugar,tea
After adding new element: orange,mango,water,banana,sugar,tea
Character Stream vs Byte Stream in Java


Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −
import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {        
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}
Now let's have a file input.txt with the following content −
This is a test for copy file.
As a next step, compile the above program and execute it, which will result in creating an output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit Unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having Unicode characters) into an output file −
import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {
      FileReader in = null;
      FileWriter out = null;

      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating an output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Matplotlib.axes.Axes.get_yticks() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_yticks() function in axes module of matplotlib library is used to return the y ticks as a list of locations.
Syntax: Axes.get_yticks(self, minor=False)
Parameters: This method accepts the following parameters.
minor : This parameter is used whether set major ticks or to set minor ticks
Return value: This method does not returns any value
Below examples illustrate the matplotlib.axes.Axes.get_yticks() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms    fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10))  w = ax.get_yticks()ax.text(15, 9, "ytick values : "+str(w),        fontweight ="bold")  fig.suptitle('matplotlib.axes.Axes.get_yticks() \function Example\n\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.mlab as mlabimport matplotlib.gridspec as gridspec    fs = 1000t = np.linspace(0, 0.3, 301)A = np.array([2, 8]).reshape(-1, 1)f = np.array([150, 140]).reshape(-1, 1)xn = (A * np.sin(2 * np.pi * f * t)).sum(axis = 0)xn += 5 * np.random.randn(*t.shape)  fig, ax = plt.subplots()  yticks = np.arange(-50, 30, 10)  ax.psd(xn, NFFT = 301,       Fs = fs,        window = mlab.window_none,        pad_to = 1024,        scale_by_freq = True)  ax.set_yticks(yticks)ax.grid(True)  w = ax.get_yticks()ax.text(80, 12, "ytick values : "+str(w),         fontweight ="bold")  fig.suptitle('matplotlib.axes.Axes.get_yticks() \function Example\n\n', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
What is the use of the “no-js” class in HTML ? - GeeksforGeeks

22 Apr, 2020
Purpose:
The primary purpose of the no-js class is to allow the use of CSS to style JavaScript-free pages, i.e. defining CSS styles for JavaScript-enabled browsers as well as for JavaScript-disabled browsers.
Thus, the “no-js” class will only be present if JavaScript has been disabled. This enables styling a pure HTML and CSS page without the use of any client side-scripting.
But if JavaScript is enabled, it removes the “no-js” class automatically.
The “no-js” class is available in the markup by default.
The “no-js” class is basically a way to be able to style things with or without using JavaScript.
The “no-js” class is added to the topmost html element which serves as an instruction for Modernizr.
Syntax:
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->
Example:
<!DOCTYPE html><html class="no-js">  <head>    <script>document.documentElement.className        = document.documentElement.className        .replace(/\bno-js\b/g, '') + ' js ';    </script>      <!-- Other files and libraries        to be included -->    <head>      <body>        <center>            <h1>GeeksforGeeks</h1>        </center>    </body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Legion Tool in Kali Linux - GeeksforGeeks

24 Dec, 2020
If you are using Kali Linux 2020.1 or up, then instead of Sparta, Kali Linux comes with the Legion, fork version of Sparta with improved features. Legion tool is a super-extensible and semi-automated network penetration testing framework. Legion is very easy to operate. 
Features of Legion Tool:  
GUI with panels and a long list of options that allow pentesters to quickly find and exploit attack vectors on hosts.
It has the feature of real-time auto-saving of project results and tasks.
Legion also provides services like Automatic recon and scanning with NMAP, whataweb, sslyzer, Vulners, webslayer, SMBenum, dirbuster, nikto, Hydra, and almost 100 auto-scheduled scripts are added to it.
Modular functionality of Legion Tool allows users to easily customize Legion.
Automatic detection of  CVEs (Common Vulnerabilities and Exposures and CPEs (Common Platform Enumeration).
Notable changes from Sparta tool:
Legion tool provides estimates of Task completion.
The elimination of deprecated and unmaintained libraries has been done as Legion is refactored from Python 2.7 to Python 3.6.
Support for hostname resolution.
Legion tool revises the processes in queue and execution routines for increased app reliability and performance.
Legion has a real-time auto-saving of project tasks and results.
Scanning of vhosts/sni hosts.
Legion tool is supported by a highly-active development team.
Installation of Legion tool: Usually Legion tool comes pre-installed with Kali Linux but, if we need to install it we can run the following command :
sudo apt-get install legion -y
After the complete execution of the above command, you can start the legion tool from any terminal by simply “legion” command.
legion
In the Hosts section, we have an option to add hosts to the scope. Simply click on add hosts and you will get the below screen :
Here we can add a single IP, a range of IPs, or hostnames in the section. In order to add multiple targets simply separate them with a semicolon. Then there is the option for Mode selection, in this section, we have Easy and Hard mode. In Easy mode, we got nmap scanning options like staged scan and nmap host discovery. In Hard mode, we get options like host discovery, custom port scanning, and custom discovery options. In the additional arguments we have -O flag for OS detection and -sV flag for service version.
Performing scan with Legion Tool: We are performing an Easy mode scan on yahoo.com with -sV and -O arguments.
We will get results as shown in the below image.
Kali-Linux
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
HTML | <td> scope Attribute - GeeksforGeeks

06 Jan, 2022
The HTML <td> scope Attribute is used to specify the cell is used for header row, column, colgroup or rowgroup. This attribute does not display any visual effect on the browser but it is used for screen readers.
Note: This attribute is not supported by HTML5.
Syntax:
<td scope="col | row | colgroup | rowgroup">
Attribute Values:
col: It specifies that the header cell is used for column.
row: It specifies that the header cell is used for row.
colgroup: It specifies that the header cell is used for group of column.
rowgroup: It specifies that the header cell is used for group of row.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML scope Attribute</title>    <style>        table,        th,        td {            border: 1px solid black;            border-collapse: collapse;            padding: 6px;        }    </style></head>  <body style="text-align:center">      <h1 style="color: green;">GeeksforGeeks</h1>    <h2>HTML <td>scope Attribute</h2>    <center>        <table>            <tr>                <th>Name</th>                <th>Age</th>            </tr>            <tr>                <td scope="col">Ajay</td>                <!-- This cell will take up space on                     two rows -->                <td>24</td>                <td>24</td>                <td>44</td>            </tr>            <tr>                <td>Priya</td>            </tr>        </table>    </center>  </body>  </html>
Output:
Supported Browsers: The browsers supported by HTML <td> scope Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Scala Map isEmpty() method with example - GeeksforGeeks

13 Aug, 2019
The isEmpty() method is utilized to check if the given map is empty or not.
Method Definition: def isEmpty: Boolean
Return Type: It returns true if the stated map is empty else returns false.
Example #1:
// Scala program of isEmpty()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 3 -> "geeks")                  // Applying isEmpty method         val result = m1.isEmpty                  // Displays output        println(result)    }}
false

Example #2:
// Scala program of isEmpty()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map()                  // Applying isEmpty method         val result = m1.isEmpty                  // Displays output        println(result)    }}
true

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Inheritance in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
Python Program to Extract Elements from list in set - GeeksforGeeks

05 Apr, 2021
Given a list, the task is to write a Python Program to extract all the elements with its occurrence matching in set.
Input : test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9], search_set = {6, 2, 8}
Output : [6, 2, 2, 6, 8]
Explanation : 2, 6 occur twice and in order with respect to other elements is output.
Input : test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9], search_set = {8, 3, 5}
Output : [5, 3, 5, 8]
Explanation : 5 occurs twice and in order with respect to other elements is output.
Method #1 : Using loop
In this, each list element is iterated and checked for its presence in set using in operator and appended to result if found. 
Python3
# Python3 code to demonstrate working of# Elements from list in set# Using loop  # initializing listtest_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]               # printing original listprint("The original list is : " + str(test_list))  # initializing search setsearch_set = {6, 2, 8}  res = []for ele in test_list:          # check if element is present in set    if ele in search_set:        res.append(ele)  # printing resultprint("Set present list elements : " + str(res))
Output:
The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]
Method #2 : Using repeat() + from_iterable() + count()
In this, we test for each set element in list and repeat using repeat() by the count required to be computed using count(). The order is not maintained in this result.
Python3
# Python3 code to demonstrate working of# Elements from list in set# Using repeat() + from_iterable() + count()from itertools import chain, repeat  # initializing listtest_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]               # printing original listprint("The original list is : " + str(test_list))  # initializing search setsearch_set = {6, 2, 8}  # repeat repeats all the occurrences of elementsres = list(chain.from_iterable((repeat(ele, test_list.count(ele))                                 for ele in search_set)))  # printing resultprint("Set present list elements : " + str(res))
Output:
The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
IntStream reduce(int identity, IntBinaryOperator op) in Java with Examples - GeeksforGeeks

06 Dec, 2018
IntStream reduce(int identity, IntBinaryOperator op) performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
A reduction operation or fold takes a sequence of input elements and combines them into a single summary result, such as finding the sum or maximum of a set of numbers. An operator or function op is associative if the following holds :
(a op b) op c == a op (b op c)

This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
int reduce(int identity,  IntBinaryOperator op)

Parameters :
identity : The identity value for the accumulating function.
IntBinaryOperator : An operation upon two int-valued operands and producing an int-valued result.
op : An associative, stateless function for combining two values.
Return Value : The result of the reduction.
Example 1 :
// Java code for IntStream reduce// (int identity, IntBinaryOperator op)import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(2, 3, 4, 5, 6);          // Using IntStream reduce        // (int identity, IntBinaryOperator op)        int answer = stream.reduce(0, (num1, num2)                                          -> (num1 + num2) * 2);          // Displaying the result        System.out.println(answer);    }}
Output :
176

Example 2 :
// Java code for IntStream reduce// (int identity, IntBinaryOperator op)import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(4, 10);          // Using IntStream reduce        // (int identity, IntBinaryOperator op)        int answer = stream.reduce(0, (num1, num2)                                          -> (num1 + num2) - 2 * (num1 - num2));          // Displaying the result        System.out.println(answer);    }}
Output :
9

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
How to specify an input field is read-only in HTML ? - GeeksforGeeks

25 Dec, 2020
In this article, we will specify an input field is read-only in HTML. The readonly attribute of <input> element is used to specify that the input field is read-only. If an input is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute.
Syntax:
<input readonly>
Example: This example using <input> readonly attribute to set the read-only value.
HTML
<!DOCTYPE html><html>  <head>    <title>        How to specify an input        field is read-only in HTML?    </title></head>  <body style="text-align:center">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h2>        How to specify an input        field is read-only in HTML?    </h2>      <label>Input Value:          <!--A readonly input-->        <input type="text" name="value"             value="This input field is readonly"            readonly>    </label></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Lodash _.padStart() Method - GeeksforGeeks

10 Feb, 2021
The _.padStart() method is used to pad a string with another string until it reaches the given length. The padding is applied from the left end of the string. Padding characters are truncated if they exceed the length.
Syntax:
_.padStart( [string = ''], [length = 0], [chars = ' '] )
Parameters: This method accepts three parameters as mentioned above and described below:
string: This parameter holds the string to the pad.
length: This parameter holds the length of the pad.
chars: This parameter holds the string used as padding.
Return Value: This method returns the padded string.
Below examples illustrate the Lodash _.padStart() method in JavaScript:
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash");       // Use of _.padStart methodconsole.log(_.padStart('GFG', 5));console.log(_.padStart('1234', 6, '#'));
Output:
'  GFG'
'##1234'
Example 2:  
Javascript
// Requiring the lodash library const _ = require("lodash");       // Use of _.padStart methodconsole.log(_.padStart('GFG', 6, '-'));console.log(_.padStart('1234', 3, '#'));
Output:
'---GFG'
'1234'
arorakashish0911
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Ruby | Array shift() function - GeeksforGeeks

06 Dec, 2019
Array#shift() : shift() is a Array class method which removes the first element of self and returns it or nil if the array is empty.
Syntax: Array.shift()
Parameter: Array
Return: removes the first element of self and returns it or nil if the array is empty.
Example #1 :
# Ruby code for shift() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 50, 6]  # shift method exampleputs "shift() method form : #{a.shift()}\n\n"  puts "shift() method form : #{b.shift(2)}\n\n"  puts "shift() method form : #{c.shift(3)}\n\n"
Output :
shift() method form : 18

shift() method form : [1, 4]

shift() method form : [18, 22, 50]


Example #2 :
# Ruby code for shift() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", nil]  # declaring arrayb = ["cow", nil, "dog"]    # shift method exampleputs "shift() method form : #{a.shift()}\n\n"  puts "shift() method form : #{b.shift()}\n\n"  puts "shift() method form : #{c.shift()}\n\n"
Output :
shift() method form : abc

shift() method form : cow

shift() method form : cat


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
Ruby | String gsub! Method
Time delay in C - GeeksforGeeks

18 Dec, 2019
In this post, we will see how to give a time delay in C code. Basic idea is to get current clock and add the required delay to that clock, till current clock is less then required clock run an empty loop.
Here is implementation with a delay function.
// C function showing how to do time delay#include <stdio.h>// To use time library of C#include <time.h>  void delay(int number_of_seconds){    // Converting time into milli_seconds    int milli_seconds = 1000 * number_of_seconds;      // Storing start time    clock_t start_time = clock();      // looping till required time is not achieved    while (clock() < start_time + milli_seconds)        ;}  // Driver code to test above functionint main(){    int i;    for (i = 0; i < 10; i++) {        // delay of one second        delay(1);        printf("%d seconds have passed\n", i + 1);    }    return 0;}
Output:


This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
Algorithms | Analysis of Algorithms (Recurrences) | Question 1 - GeeksforGeeks

21 May, 2019
What is the value of following recurrence.

T(n) = T(n/4) + T(n/2) + cn2
T(1) = c
T(0) = 0
Where c is a positive constant
(A) O(n3)(B) O(n2)(C) O(n2 Logn)(D) O(nLogn)Answer: (B)Explanation: Following is the initial recursion tree for the given recurrence relation.
           cn^2
         /      \
     T(n/4)     T(n/2)

If we further break down the expression T(n/4) and T(n/2), we get following recursion tree.
               cn^2
           /           \      
       c (n^2)/16       c(n^2)/4
      /      \          /     \
  T(n/16)     T(n/8)  T(n/8)    T(n/4) 

Breaking down further gives us following
                 cn^2
            /             \      
       c(n^2)/16           c(n^2)/4
       /      \            /      \
c(n^2)/256  c(n^2)/64  c(n^2)/64    c(n^2)/16
 /    \      /    \    /    \         /    \    
 


To know the value of T(n), we need to calculate sum of tree nodes level by level. If we sum the above tree level by level, we get the following seriesT(n) = c(n^2 + 5(n^2)/16 + 25(n^2)/256) + ....The above series is geometrical progression with ratio 5/16To get an upper bound, we can sum the above series for infinite terms. We get the sum as (n^2) / (1 – 5/16) which is O(n^2)
Refer following video lecture for more details.http://www.youtube.com/watch?v=whjt_N9uYFIQuiz of this Question
Algorithms-Analysis of Algorithms (Recurrences)
Analysis of Algorithms (Recurrences)
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Greedy Algorithms | Question 1
Algorithms | Recursion | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
Algorithms | NP Complete | Question 4
Algorithms | Sorting | Question 5
How to display open cursors in Oracle?

Problem:
You want to display open cursors in Oracle.
Solution
We can query the data dictionary to determine the number of cursors that are open per session. "V$SESSION" provides a more accurate number of the cursors currently open than "V$OPEN_CURSOR".
select
 a.value
 ,c.username
 ,c.machine
 ,c.sid
 ,c.serial#
from v$sesstat a
 ,v$statname b
 ,v$session c
where a.statistic# = b.statistic#
and c.sid  = a.sid
and b.name  = 'opened cursors current'
and a.value  != 0
and c.username IS NOT NULL
order by 1,2;
select
 a.value
 ,c.username
 ,c.machine
 ,c.sid
 ,c.serial#
from v$sesstat a
 ,v$statname b
 ,v$session c
where a.statistic# = b.statistic#
and c.sid  = a.sid
and b.name  = 'opened cursors current'
and a.value  != 0
and c.username IS NOT NULL
order by 1,2;
The OPEN_CURSORS initialization parameter determines the maximum number of cursors a session can have open.
Get the specified row value of a given Pandas DataFrame - GeeksforGeeks

17 Aug, 2020
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). 
Now let’s see how to get the specified row value of a given DataFrame.
We shall be using loc[ ], iloc[ ], and [ ] for a data frame object to select rows and columns from our data frame. 
iloc[ ] is used to select rows/ columns by their corresponding labels.loc[ ] is used to select rows/columns by their indices.[ ] is used to select columns by their respective names.
iloc[ ] is used to select rows/ columns by their corresponding labels.
loc[ ] is used to select rows/columns by their indices.
[ ] is used to select columns by their respective names.
Method 1: Using iloc[ ].
Example: Suppose you have a pandas dataframe and you want to select a specific row given its index.
Python3
# import pandas libraryimport pandas as pd  # Creating a dictionaryd = {'sample_col1': [1, 2, 3],     'sample_col2': [4, 5, 6],      'sample_col3': [7, 8, 9]}   # Creating a Dataframedf = pd.DataFrame(d)   # show the dataframe print(df)   print()  # Select Row No. 2print(df.iloc[2])
Output:
Method 2: Using loc[ ].
Example: Suppose you want to select rows where the value of a given column is given.
Python3
# import pandas libraryimport pandas as pd  # Creating a dictionaryd = {'sample_col1': [1, 2, 1],     'sample_col2': [4, 5, 6],      'sample_col3': [7, 8, 9]}   # Creating a Dataframedf = pd.DataFrame(d)   # show the dataframeprint(df)   print()  # Select rows where sample_col1 is 1print(df.loc[df['sample_col1'] == 1])
Output:
Method 3: Using [ ] and iloc[ ]. 
Example: Suppose you want only the values pertaining to specific columns of a specific row.
Python3
# import pandas libraryimport pandas as pd  # Creating a dictionaryd = {'sample_col1': [1, 2, 1],     'sample_col2': [4, 5, 6],      'sample_col3': [7, 8, 9]}    # Creating a Dataframedf = pd.DataFrame(d)   # show the dataframeprint(df)   print()  # Display column 1 and 3 for row 2print(df[['sample_col1' , 'sample_col3']].iloc[1])
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
DAX Date & Time - CALENDARAUTO function

Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is calculated automatically based on the data in the model.
DAX CALENDARAUTO function is new in Excel 2016.
CALENDARAUTO ([<fiscal_year_end_month>]) 

fiscal_year_end_month
Any DAX expression that returns an integer from 1 to 12.
If omitted, defaults to the value specified in the calendar table template for the current user, if present. Otherwise, defaults to 12.
Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is calculated automatically based on data in the model.
The date range is calculated as follows
The earliest date in the model which is not in a calculated column or calculated table is taken as the MinDate.
The earliest date in the model which is not in a calculated column or calculated table is taken as the MinDate.
The latest date in the model which is not in a calculated column or calculated table is taken as the MaxDate.
The latest date in the model which is not in a calculated column or calculated table is taken as the MaxDate.
The date range returned is dates between the beginning of the fiscal year associated with MinDate and the end of the fiscal year associated with MaxDate.
The date range returned is dates between the beginning of the fiscal year associated with MinDate and the end of the fiscal year associated with MaxDate.
An error is returned if the model does not contain any datetime values which are not in calculated columns or calculated tables.
= COUNTROWS (CALENDARAUTO ()) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to set your python path on Mac?

To set the PYTHONPATH on Mac OS to point Python to look in other directories for module and package imports, export the PYTHONPATH variable as follows:
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
 In this case are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble
How to Install Face Recognition in Python on Windows? - GeeksforGeeks

26 Oct, 2021
In this article, we will learn how to install Face Recognition in Python on Windows. Recognize and manipulate faces from Python or from the command line with the world’s simplest face recognition library. Built using dlib’s state-of-the-art face recognition built with deep learning.
Face Recognition module can only be installed for Python version 3.7 and 3.8.
Step 1: Install git for Windows
Step 2: Clone this repository and go inside the folder using the following commands
git clone https://github.com/RvTechiNNovate/face_recog_dlib_file.git
cd face_recog_dlib_file
Step 3: Enter the following command to install dlib and cmake using pip
Python 3.7:
pip install dlib-19.19.0-cp37-cp37m-win_amd64.whl

Python 3.8:
pip install dlib-19.19.0-cp38-cp38-win_amd64.whl
pip install cmake
Follow the below steps to install the Face Recognition package on Windows using pip:
Step 1: Install the latest Python3 in Windows 
Step 2: Check if pip and python are correctly installed.
python --version
pip --version
Step 3: Upgrade your pip to avoid errors during installation.
pip install --upgrade pip
Step 4: Enter the following command to install Face Recognition using pip3.
pip install face-recognition
Follow the below steps to install the Face Recognition on Windows using the setup.py file:
Step 1: Download the latest source package of Face Recognition for python3 from here.
curl https://files.pythonhosted.org/packages/6c/49/75dda409b94841f01cbbc34114c9b67ec618265084e4d12d37ab838f4fd3/face_recognition-1.3.0.tar.gz > face_recognition-1.3.0.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf face_recognition-1.3.0.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
cd face_recognition-1.3.0
python setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import face_recognition
If there is any error while importing the module then is not installed properly.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to use MySQL decimal?

MySQL decimal data type can be used to store the exact numerical value. The syntax of DECIMAL data type.
yourColumnName Decimal(integerValue,intgerValue);
Example of DECIMAL data type.
mysql> create table EmployeeInformation
   -> (
   -> EmpId int auto_increment primary key,
   -> EmpName varchar(200),
   -> EmpSalary DECIMAL(6.2)
   -> );
Query OK, 0 rows affected (0.54 sec)
Whenever we insert a value in “EmpSalary” column greater than 6 digits, it raise an error. The error is as follows −
mysql> insert into EmployeeInformation(EmpName,EmpSalary) values('John',6999999.50);
ERROR 1264 (22003): Out of range value for column 'EmpSalary' at row 1
Inserting value in “EmpSalary” column with exact number of digits.
mysql> insert into EmployeeInformation(EmpName,EmpSalary) values('John',6999.50);
Query OK, 1 row affected, 1 warning (0.15 sec)

mysql> insert into EmployeeInformation(EmpName,EmpSalary) values('John',69999.50);
Query OK, 1 row affected, 1 warning (0.20 sec)
To display all records.
mysql> select *from EmployeeInformation;
The following is the output.
+-------+---------+-----------+
| EmpId | EmpName | EmpSalary |
+-------+---------+-----------+
|     1 | John    |      7000 |
|     2 | John    |     70000 |
+-------+---------+-----------+
2 rows in set (0.00 sec)
JavaScript - Date toLocaleString() Method

Javascript date toLocaleString()  method converts a date to a string, using the operating system's local conventions.
The toLocaleString method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system where the script is running. For example, in the United States, the month appears before the date (04/15/98), whereas in Germany the date appears before the month (15.04.98).
Its syntax is as follows −
Date.toLocaleString ()

Returns the formatted date in a string fromat.
Try the following example.
<html>   
   <head>
      <title>JavaScript toLocaleString Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var dt = new Date(1993, 6, 28, 14, 39, 7);
         document.write( "Formated Date : " + dt.toLocaleString() ); 
      </script>      
   </body>
</html>
Formated Date : 7/28/1993, 2:39:07 PM


    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