code-rag-bench/online-tutorials huggingface dataset:
Scala List filter() method with example

26 Jul, 2019
The filter() method is utilized to select all elements of the list which satisfies a stated predicate.
Method Definition: def filter(p: (A) => Boolean): List[A]
Return Type: It returns a new list consisting all the elements of the list which satisfies the given predicate.
Example #1:
// Scala program of filter()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying filter method        val result = m1.filter(_ < 10)                  // Displays output        println(result)          }}
List(5, 3)

Example #2:
// Scala program of filter()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying filter method        val result = m1.filter(_ < 3)                  // Displays output        println(result)          }}
List()

Here, an empty list is returned as none of the elements satisfy the stated predicate.
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Enumeration in Scala
Inheritance in Scala
How to get the first element of List in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
How to create a social media login form with CSS?

Following is the code to create a social media login form using CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Responsive login form with social media login buttons</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
* {
   box-sizing: border-box;
}
h1 {
   text-align: center;
}
form {
   border: 1px solid rgb(182, 180, 180);
   padding: 20px;
   width: 800px;
   margin-left: 20%;
}
input {
   width: 100%;
   border: 1px solid #ddd;
   padding: 5px 10px;
   height: 45px;
   margin: 0px 0px 20px;
   border-radius: 4px;
   box-sizing: border-box;
   font-size: 17px;
}
button {
   margin: 10px auto 30px;
   display: table;
   font-size: 20px;
   padding: 10px 30px;
   background-color: #4caf50;
   border: none;
   color: #fff;
   border-radius: 4px;
   cursor: pointer;
}
button:hover {
   opacity: 0.8;
}
input[type="checkbox"] {
   height: 16px;
   width: 16px;
   margin-right: 5px;
   float: left;
}
.Social button.twitter-btn,
.Social button.facebook-btn {
   width: 100%;
   font-size: 18px;
   margin: 0px 0px 10px;
}
.Social button.twitter-btn {
   background-color: #26abfd;
}
.Social button.facebook-btn {
   background-color: #3f68be;
}
.Social {
   border-top: 1px solid #ddd;
   padding-top: 30px;
   margin-top: 30px;
}
.Social button i {
   margin-right: 5px;
   font-size: 20px;
}
@media (max-width: 1000px) {
   form {
      width: 100%;
      margin-left: 0px;
   }
}
</style>
</head>
<body>
<h1>Social Media Login Form example</h1>
<form>
<input type="email" placeholder="Username or email id" name="username" required/>
<input type="password" placeholder="Enter password" name="pass" required/>
<button type="submit">Login</button>
<label class="Remember">
<input type="checkbox" name="remember" />Remember me</label>
<span class="forgotPass">Forgot password?</span>
<div class="Social">
<button type="submit" class="twitter-btn">
<i class="fa fa-twitter" aria-hidden="true"></i> Login with Twitter
</button>
<button type="submit" class="facebook-btn">
<i class="fa fa-facebook" aria-hidden="true"></i> Login with Facebook
</button>
</div>
</form>
</body>
</html>
This will produce the following output −
Python - Dictionary Exercises

Now you have learned a lot about dictionaries, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Use the get method to print the value of the "model" key of the car dictionary.
car =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print()

Start the Exercise
Go to the Exercise section and test all of our Python Dictionary Exercises:

Python Dictionary Exercises

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
VBScript Day Function

The Day function returns a number between 1 and 31 that represents the day of the specified date.
Day(date) 

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         document.write(Day("2013-06-30"))
       
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
How to Add Repositories in Linux

04 Jul, 2022
The installation process of any software in Linux is totally different from Windows. In Linux, the software is installed via repositories. Let us discuss some methods to add repositories to Ubuntu/Debian-based Linux.
The most recommendable method is the command line method, so let’s discuss it.
Use the following commands to add launchpad PPA to your system.
$ sudo add-apt-repository ppa:Software_name/ppa
If you want to download any hosted repositories, then you can get it by providing its reference URL/
$ add-apt-repository 'deb "URL of the software to download "'
You have to open and edit the source list by adding the required repository path in “/etc/apt/sources.list”, by using the following command:
$ vi /etc/apt/sources.list
Many of you prefer graphical interfaces, so for them, there is a  lightweight GUI front end apt package management system Synaptic made for Debian, Ubuntu, Linux Mint, and many other Debian/Ubuntu-based distributions.
Install Synaptic using the following command:
$ sudo apt install synaptic
After you are done with the installation, start synaptic as root user else you can’t perform anything properly
$ sudo synaptic
Now you can do everything you want according to your requirement. For managing the repository go to settings and choose a repository, you will be taken the following window:
simmytarika5
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
numpy.hypot() in Python

18 Nov, 2020
This mathematical function helps user to calculate hypotenuse for the right angled triangle, given its side and perpendicular. Result is equivalent to Equivalent to sqrt(x1**2 + x2**2), element-wise.Syntax :
numpy.exp2(arr1, arr2[, out]) = ufunc 'hypot') : 
Parameters :
arr1, arr2  : [array_like] Legs(side and perpendicular) of triangle
out         : [ndarray, optional] Output array with result.

Return :
An array having hypotenuse of the right triangle.

 Code #1 : Working
# Python3 program explaining# hypot() function  import numpy as np  leg1 = [12, 3, 4, 6]print ("leg1 array : ", leg1)    leg2 = [5, 4, 3, 8]print ("leg2 array : ", leg2)  result = np.hypot(leg1, leg2)print("\nHypotenuse is as follows :")print(result)
Output :
leg1 array :  [12, 3, 4, 6]
leg2 array :  [5, 4, 3, 8]

Hypotenuse is as follows :
[ 13.   5.   5.  10.]

 Code #2 : Working with 2D array
# Python3 program explaining# hypot() function  import numpy as np  leg1 = np.random.rand(3, 4)print ("leg1 array : \n", leg1)  leg2 = np.ones((3, 4))print ("leg2 array : \n", leg2)  result = np.hypot(leg1, leg2)print("\nHypotenuse is as follows :")print(result)
Output :
leg1 array : 
 [[ 0.57520509  0.12043366  0.50011671  0.13800957]
 [ 0.0528084   0.17827692  0.44236813  0.87758732]
 [ 0.94926413  0.47816742  0.46111934  0.63728903]]
leg2 array : 
 [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

Hypotenuse is as follows :
[[ 1.15362944  1.00722603  1.11808619  1.0094784 ]
 [ 1.00139339  1.01576703  1.09347591  1.33047342]
 [ 1.37880469  1.10844219  1.10119528  1.18580661]]
 Code 3 : Equivalent to sqrt(x1**2 + x2**2), element-wise.
# Python3 program explaining# hypot() function  import numpy as np  leg1 = np.random.rand(3, 4)print ("leg1 array : \n", leg1)  leg2 = np.ones((3, 4))print ("leg2 array : \n", leg2)  result = np.sqrt((leg1 * leg1) + (leg2 * leg2))print("\nHypotenuse is as follows :")print(result)
Output :
leg1 array : 
 [[ 0.7015073   0.89047987  0.1595603   0.27557254]
 [ 0.67249153  0.16430312  0.70137114  0.48763522]
 [ 0.68067777  0.52154819  0.04339669  0.2239366 ]]
leg2 array : 
 [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

Hypotenuse is as follows :
[[ 1.15362944  1.00722603  1.11808619  1.0094784 ]
 [ 1.00139339  1.01576703  1.09347591  1.33047342]
 [ 1.37880469  1.10844219  1.10119528  1.18580661]]
References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.hypot.html#numpy.hypot.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to convert JPG to PNG using Node.js ? - GeeksforGeeks

06 Apr, 2021
JPG and PNG both are widely used image formats. Using these formats allows the user to contain and use digital images. In this article, we will discuss how to convert a given JPG image to a PNG image using Node.js which can then be helpful to use the image in our web application.
Jimp (JavaScript Image Manipulation Program):
Jimp is an image processing library that is written entirely in JavaScript and is used by Node. For the conversion of JPG to PNG, we will be using Jimp.
Installation:
To install Jimp in our project, we simply have to install its npm module into our project. This can be done by executing the following line in our terminal.
npm install --save jimp
Usage:
To use it in our project, we will need to import the package into our index.js file by using the following line of code.
const Jimp = require("jimp");
Now that we have Jimp installed and ready to use, we can move ahead to convert JPG to PNG.
JPG to PNG Conversion:
We will use .read() and .write() method to do the conversion. Let’s consider an example where we will have an input JPG image and then convert it into PNG image.
Example:
Let’s suppose we have a JPG image given below as input.
gfg.jpg
We are keeping the code in the images folder. Now to convert it into PNG format, our script code will look like the following.
index.js
// Importing the jimp moduleconst Jimp= require("jimp");  //We will first read the JPG image using read() method. Jimp.read("images/gfg.jpg", function (err, image) {  //If there is an error in reading the image,   //we will print the error in our terminal  if (err) {    console.log(err)  }   //Otherwise we convert the image into PNG format   //and save it inside images folder using write() method.  else {    image.write("images/gfg.png")  }})
On executing the code using node, we should be able to get the PNG converted image in our images folder as shown below.
Output:
NodeJS-Questions
Picked
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
Mongoose find() Function
How to connect Node.js with React.js ?
Mongoose Populate() Method
Node.js Export Module
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
How to create an empty and a full NumPy array? - GeeksforGeeks

01 Oct, 2020
Sometimes there is a need to create an empty and full array simultaneously for a particular question. In this situation, we have two functions named as numpy.empty() and numpy.full() to create an empty and full arrays.
Syntax:
numpy.full(shape, fill_value, dtype = None, order = ‘C’)
numpy.empty(shape, dtype = float, order = ‘C’) 

Example 1: 
Python3
# python program to create# Empty and Full Numpy arrays  import numpy as np    # Create an empty arrayempa = np.empty((3, 4), dtype=int)print("Empty Array")print(empa)  # Create a full arrayflla = np.full([3, 3], 55, dtype=int)print("\n Full Array")print(flla)
Output:
In the above example, we create an empty array of 3X4 and full array of 3X3 of INTEGER type.
Example 2: 
Python3
# python program to create# Empty and Full Numpy arrays  import numpy as np    # Create an empty arrayempa = np.empty([4, 2])print("Empty Array")print(empa)  # Create a full arrayflla = np.full([4, 3], 95)print("\n Full Array")print(flla)
Output:
In the above example, we create an empty array of 4X2 and full array of 4X3 of INTEGER and FLOAT type.
Example 3:
Python3
# python program to create # Empty and Full Numpy arrays  import numpy as np  # Create an empty arrayempa =  np.empty([3,3]) print("Empty Array")print(empa)  # Create a full arrayflla = np.full([5,3], 9.9)print("\n Full Array")print(flla)
Output:
In the above example, we create an empty array of 3X3 and full array of 5X3 of FLOAT type.
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
How to determine length or size of an Array in Java?

30 Sep, 2019
There is no size() method available with the array. But there is a length field available in the array that can be used to find the length or size of the array.
array.length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array.
Examples:
int size = arr[].length;

// length can be used 
// for int[], double[], String[] 
// to know the length of the arrays.

Below is the illustration of how to get the length of array[] in Java using length variable:
Example 1:
// Java program to illustrate// how to get the length of the array  public class Test {    public static void main(String[] args)    {          // Here array is the        // array name of int type        int[] array = new int[4];          System.out.println("The size of "                           + "the array is "                           + array.length);    }}
The size of the array is 4

Example 2:
// Java program to illustrate// how to get the length of the array  public class Test {    public static void main(String[] args)    {          // Here str is the array name        // of String type.        String[] str            = { "GEEKS", "FOR", "GEEKS" };          System.out.println("The size of "                           + "the array is "                           + str.length);    }}
The size of the array is 3

Arrays
Java-Array-Programs
Picked
Java
Arrays
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
HashMap in Java with Examples
Math pow() method in Java with Example
PriorityQueue in Java
Stack Class in Java
List Interface in Java with Examples
Initialize an ArrayList in Java
ArrayList in Java
INSTR() function in MySQL

07 Dec, 2020
INSTR() :This function in MySQL is used to return the location of the first occurrence of a substring within a given string.
Syntax :
INSTR(string_1, string_2)
Parameters :This function accepts 2 parameters.
string_1 –The string where searching takes place.
string_2 –The string/sub-string which will be searched in string_1.
Returns :It returns the position of the first occurrence of a substring within a given string.
Note –
The function will return 0 if string_2 is not found in string_1.
INSTR() function only performs case-insensitive searches.
Example-1:Finding the position of a sub-string.
SELECT INSTR("Python is a powerful Language", "powerful") 
AS Found;
Output :
Example-2:Showing that INSTR() function is case-insensitive.
SELECT  
 INSTR("Python is a powerful Language", "IS") 
AS 'Found1';
 INSTR("Python is a powerful Language", "is") 
AS 'Found2';
Output :
Example-3:If string_2 is not found in string_1.
SELECT INSTR("Python is awesome", "hey") 
AS Found;
Output :
Example-4:All possible errors in INSTR() function.If only one parameter is passed.
SELECT INSTR("Python is a powerful Language") 
AS 'Found';
Output :
Incorrect parameter count in the call to native function 'INSTR'
If three or more parameters are passed.
SELECT INSTR("Python is a powerful Language", "is", "a", "lang) 
AS 'Found';
Output :
Incorrect parameter count in the call to native function 'INSTR'
DBMS-SQL
mysql
Technical Scripter 2020
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to Create a Class and Compute the Area and the Perimeter of the Circle

When it is required to find the area and perimeter of a circle using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area and perimeter of the circle.
Below is a demonstration for the same −
 Live Demo
import math
class circle_compute():
   def __init__(self,my_radius):
      self.radius=my_radius
   def area_calculate(self):
      return math.pi*(self.radius**2)
   def perimeter_calculate(self):
      return 2*math.pi*self.radius
my_result = int(input("Enter the radius of circle..."))
my_instance = circle_compute(my_result)
print("The radius entered is :")
print(my_result)
print("The computed area of circle is ")
print(round(my_instance.area_calculate(),2))
print("The computed perimeter of circle is :")
print(round(my_instance.perimeter_calculate(),2))
Enter the radius of circle...7
The radius entered is :
7
The computed area of circle is
153.94
The computed perimeter of circle is :
43.98
A class named ‘circle_compute’ class is defined, that has functions like ‘area_calculate’, ‘perimeter_calculate’.
These are used to calculate the area and perimeter of a circle respectively.
An instance of this class is created.
The value for radius is entered and operations are performed on it.
Relevant messages and output is displayed on the console.
Python | Test if string contains element from list

17 Aug, 2021
During web development in Python, we generally come across a problem where we need to test if a particular element from a given list lies as sub-string or not. This kind of problem is also very common in Machine Learning domain. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension This problem can be solved using the list comprehension, in this, we check for the list and also with string elements if we can find a match, and return true, if we find one and false is not using the conditional statements. 
Python3
# Python3 code to demonstrate# checking if string contains list element# using list comprehension # initializing stringtest_string = "There are 2 apples for 4 persons" # initializing test listtest_list = ['apples', 'oranges'] # printing original stringprint("The original string : " + test_string) # printing original listprint("The original list : " + str(test_list)) # using list comprehension# checking if string contains list elementres = [ele for ele in test_list if(ele in test_string)] # print resultprint("Does string contain any list element : " + str(bool(res)))
The original string : There are 2 apples for 4 persons
The original list : ['apples', 'oranges']
Does string contain any list element : True
 
 Method #2 : Using any() Using any function is the most classical way in which you can perform this task and also efficiently. This function checks for match in string with match of each element of list. 
Python3
# Python3 code to demonstrate# checking if string contains list element# using list comprehension # initializing stringtest_string = "There are 2 apples for 4 persons" # initializing test listtest_list = ['apples', 'oranges'] # printing original stringprint("The original string : " + test_string) # printing original listprint("The original list : " + str(test_list)) # using list comprehension# checking if string contains list elementres = any(ele in test_string for ele in test_list) # print resultprint("Does string contain any list element : " + str(res))
The original string : There are 2 apples for 4 persons
The original list : ['apples', 'oranges']
Does string contain any list element : True
 
16lhug5vg65vjnw16xbsazgqn4mtkwtopox28iy4
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.
What is the lifetime of a static variable in a C++ function?

A static variable is a variable that is declared using the keyword static. The space for the static variable is allocated only one time and this is used for the entirety of the program.
Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is the lifetime of the program.
A program that demonstrates a static variable is given as follows.
 Live Demo
#include <iostream>
using namespace std;
void func() {
   static int num = 1;
   cout <<"Value of num: "<< num <<"\n";
   num++;
}
int main() {
   func();
   func();
   func();
   return 0;
}
The output of the above program is as follows.
Value of num: 1
Value of num: 2
Value of num: 3
Now, let us understand the above program.
In the function func(), num is a static variable that is initialized only once. Then the value of num is displayed and num is incremented by one. The code snippet for this is given as follows −
void func() {
   static int num = 1;
   cout <<"Value of num: "<< num <<"\n";
   num++;
}
In the function main(), the function func() is called 3 times. The value num is allocated only once and not on every function call. The code snippet for this is given as follows.
int main() {
   func();
   func();
   func();
   return 0;
}
Python - Backtracking

Backtracking is a form of recursion. But it involves choosing only option out of any possibilities. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution.
Below is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer list else it is ignored.
def permute(list, s):
   if list == 1:
      return s
   else:
      return [ 
         y + x
         for y in permute(1, s)
         for x in permute(list - 1, s)
      ]
print(permute(1, ["a","b","c"]))
print(permute(2, ["a","b","c"]))
When the above code is executed, it produces the following result −
['a', 'b', 'c']
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
Python | os.get_exec_path() method

01 Nov, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.get_exec_path() method in Python is used to get the list of directories that will be searched for a named executable while launching a process.
Syntax: os.get_exec_path(env = None)
Parameter:env (optional): A dictionary representing the environment variables. The default value of this parameter is None. If its value is None environ is used.
Return Type: This method returns a list which represents the paths of directories that will be used to search a named executable while launching a process.
# Python program to explain os.get_exec_path() method     # importing os module import os  # Get the list of directories # that will be used to search # a named executable# while launching a processexec_path = os.get_exec_path()  # Print the listprint("Following paths will be searched for a named executable:")print(exec_path)
Following paths will be searched for a named executable:
['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/usr/games', '/usr/local/games', '/snap/bin', '/usr/local/java/jdk-10.0.1/bin', '/usr/local/java/jdk-10.0.1/jre/bin', '/opt/jdk-10.0.1/bin', '/opt/jdk-10.0.1/jre/bin']

Code #2: Specifying env parameter
# Python program to explain os.get_exec_path() method     # importing os module import os  # Dictionary of environment variableenv = {'HOME': '/home/ihritik'}    # Get the list of directories # that will be used to search # a named executable# while launching a processexec_path = os.get_exec_path(env)  # Print the listprint("Following paths will be searched for a named executable:")print(exec_path)
Following paths will be searched for a named executable:
['', '/bin', '/usr/bin']

Akanksha_Rai
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert the value of the current DateTime object to UTC in C#

To convert the value of the current DateTime object to Coordinated Universal Time (UTC), the code is as follows −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 12, 11, 7, 11, 25);
      Console.WriteLine("Date = {0}", d);
      DateTime res = d.ToUniversalTime();
      Console.WriteLine("String representation = {0}", res);
   }
}
This will produce the following output −
Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM
Let us now see another example −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      DateTime localDate, universalDate;
      String str = "11/11/2019 4:10:55";
      localDate = DateTime.Parse(str);
      universalDate = localDate.ToUniversalTime();
      Console.WriteLine("Local time = {0} ", localDate);
      Console.WriteLine("Universal time = {0} ", universalDate);
   }
}
This will produce the following output −
Local time = 11/11/2019 4:10:55 AM
Universal time = 11/11/2019 4:10:55 AM
PriorityQueue peek() Method in Java

10 Dec, 2018
The java.util.PriorityQueue.peek() method in Java is used to retrieve or fetch the first element of the Queue or the element present at the head of the Queue. The element retrieved does not get deleted or removed from the Queue.
Syntax:
Priority_Queue.peek()
Parameters: The method does not take any parameters.
Return Value: The method returns the element at the head of the Queue else returns NULL if the Queue is empty.
Below programs illustrate the java.util.PriorityQueue.peek() method:Program 1:
// Java code to illustrate peek()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<String> queue = new PriorityQueue<String>();          // Use add() method to add elements into the Queue        queue.add("Welcome");        queue.add("To");        queue.add("Geeks");        queue.add("For");        queue.add("Geeks");          // Displaying the PriorityQueue        System.out.println("Initial PriorityQueue: " + queue);          // Fetching the element at the head of the queue        System.out.println("The element at the head of the"                           + " queue is: " + queue.peek());          // Displaying the Queue after the Operation        System.out.println("Final PriorityQueue: " + queue);    }}
Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The element at the head of the queue is: For
Final PriorityQueue: [For, Geeks, To, Welcome, Geeks]

Program 2:
// Java code to illustrate peek()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();          // Use add() method to add elements into the Queue        queue.add(10);        queue.add(15);        queue.add(30);        queue.add(20);        queue.add(5);          // Displaying the PriorityQueue        System.out.println("Initial PriorityQueue: " + queue);          // Fetching the element at the head of the queue        System.out.println("The element at the head of the"                           + " queue is: " + queue.peek());          // Displaying the Queue after the Operation        System.out.println("Final PriorityQueue: " + queue);    }}
Initial PriorityQueue: [5, 10, 30, 20, 15]
The element at the head of the queue is: 5
Final PriorityQueue: [5, 10, 30, 20, 15]

Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python – Getting all the Wifi Devices the system has connected

01 Jun, 2021
In this article we will see how we can all those wifi network on which the system is ever connected to. Wi-Fi is a wireless networking technology that allows devices such as computers (laptops and desktops), mobile devices (smart phones and wearables), and other equipment (printers and video cameras) to interface with the Internet.In order to do this we will use the subprocess module. The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands.In order to get the information about the wifi devices system is connected to we will use the command given below  
subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
This command will return the meta data in bytes format in order to get the names of network we have to decode and filter it to get the desired output.Below is the implementation  
Python3
# importing subprocessimport subprocess # getting meta data of the wifi networkmeta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']) # decoding meta data from byte to stringdata = meta_data.decode('utf-8', errors ="backslashreplace") # splitting data by line by line# string to listdata = data.split('\n') # creating a list of wifi namesnames = [] # traverse the listfor i in data:         # find "All User Profile" in each item    # as this item will have the wifi name    if "All User Profile" in i :                 # if found split the item        # in order to get only the name        i = i.split(":")                 # item at index 1 will be the wifi name        i = i[1]                 # formatting the name        # first and last chracter is use less        i = i[1:-1]                 # appending the wifi name in the list        names.append(i) # printing the wifi namesprint("All wifi that system has connected to are ")print("-----------------------------------------")for name in names:    print(name)
Output :  
All wifi that system has connected to are 
-----------------------------------------
Engineer_5GHz
Engineer
honor
Redmi
Ayush
BiGX-cmtqaGFtYjc
UERJTTBV8e0GUmVkbWkg 2
DESKTOP-F32H70N 5009
UERJTTBV8e0GUmVkbWkg
Bunns
Hogwarts
Cgc wireless
Moto G (5) Plus 8691
AndroidAP
AndroidAPab7e
roshan
Svj?
Hey
AndroidAP202
JARVIS
B6NO-wq5hamF0IGt1bWHCrg
CDAC
 
sooda367
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update nested state properties in ReactJS?

28 Dec, 2020
There are the following approaches to update nested state properties in ReactJS:
Approach 1: We can create a dummy object to perform operations on it (update properties that we want) then replace the component’s state with the updated object.
Approach 2: We can pass the old nested object using the spread operator and then override the particular properties of the nested object.
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.
Project Structure
Approach 1: App.js
Javascript
import React, { Component } from "react";class App extends Component {    // Nested object  state = {    name: 'kapil',    address: {      colony: 'vaishnav nagar',      city: 'Jaipur',      state: 'Rajasthan'    }  };    handleUpdate = () => {    // Creating a dummy object using spread operator    var address = { ...this.state.address }      // Updating the city    address.city = 'Kota';    this.setState({ address })  }    render() {    return (      <div style={{ margin: 200 }}>        <h1>{this.state.name}</h1>        <h1>{this.state.address.colony} {","}          {this.state.address.city}{", "}          {this.state.address.state}</h1>        <button          onClick={this.handleUpdate}        >UpdateCity </button>      </div>    );  }}  export default App;
Approach 2: App.js
Javascript
import React, { Component } from "react";class App extends Component {    // Nested object  state = {    name: 'kapil',    address: {      colony: 'vaishnav nagar',      city: 'Jaipur',      state: 'Rajasthan'    }  };    handleUpdate = () => {    // Overriding the city property of address object    this.setState({ address: { ...this.state.address, city: "kota" } })  }    render() {    return (      <div style={{ margin: 200 }}>        <h1>{this.state.name}</h1>        <h1>{this.state.address.colony} {","}          {this.state.address.city}{", "}          {this.state.address.state}</h1>        <button          onClick={this.handleUpdate}        >UpdateCity </button>      </div>    );  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
react-js
JavaScript
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript | fetch() Method
JavaScript String includes() Method
Async/Await Function in JavaScript
Python | Ways to sort list of float values

11 May, 2020
Given a list of float values, write a Python program to sort the list.
Examples:
Input: list = ['1.2', '.8', '19.8', '2.7', '99.8', '80.7']
Output: ['.8', '1.2', '2.7', '19.8', '80.7', '99.8']

Input: list = [12.8, .178, 1.8, 782.7, 99.8, 8.7]
Output: [0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

Let’s discuss different ways to solve this problem.
Method #1 :Using lambda
# Python code to sort list of decimal values  # List initializationInput =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]  # Using sorted and lambdaOutput = sorted(Input, key = lambda x:float(x))  # Printing outputprint(Output)
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

 Method #2 : Using sorted
# Python code to sort list of decimal values  # List initializationInput =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]  # Using sorted + keyOutput = sorted(Input, key = float)  # Printing outputprint(Output)
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

 Method #3 : Using sort
# Python code to sort list of decimal values  # List initializationInput =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]  # Using sort + keyInput.sort(key = float)  # Printing outputprint(Input)
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select values from a JSON object using jQuery ?

18 Jan, 2021
In this article, we will select values from a JSON object and display them on the browser using jQuery. To select values from a JSON object to webpage, we use append() method. 
This append() method in jQuery is used to insert some content at the end of the selected elements.
Syntax:
$(selector).append( content, function(index, html) )
Approach: First we store a JSON object containing (key, value) pair in a variable. We have created a button using <button> element and when we click the button, the jQuery function called with selector and click events. After click the button, the attr() method added the name attribute with <select> element. The <option> element is appended to each element using append() and each() methods.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        How to select values from a        JSON object using jQuery?    </title>      <!-- Import jQuery cdn library -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>      <script>        $(document).ready(function () {              var json = [                { "name": "GFG", "text": "GFG" },                { "name": "Geeks", "text": "Geeks" },                { "name": "GeeksforGeeks",                     "text": "GeeksforGeeks" }            ];              $('button').click(function () {                var select = $("<select></select>")                    .attr("name", "cities");                  $.each(json, function (index, json) {                    select.append($("<option></option>")                    .attr("value", json.name).text(json.text));                });                $("#GFG").html(select);            });        });      </script></head>  <body style="text-align: center;">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h3>        How to select values from a        JSON object using jQuery?    </h3>      <div id="GFG"></div>      <button>Submit</button></body>  </html>
Output:
Before Click Button:
After Click Button:
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
3-Way QuickSort (Dutch National Flag)

Here we will see the quicksort technique but we will use three-way quicksort. The basic quicksort technique is just finding an element as pivot then partition the array around pivot, after that, recur for sub arrays on left and right of the pivot.
The three-way quicksort is similar, but there are three sections. array arr[1 to n] is divided into three parts.
arr[1 to i]
arr[i + 1, j]
arr[j + 1, n]
partition(arr, left, right, i, j) −
begin
   if right – left <= 1, then
      if arr[right] < arr[left], then
         swap arr[right] and arr[left]
      i := left
      j := right
      return
   end if
   mid := left, pivot = arr[right]
   while mid <= right, do
      if arr[mid] < pivot, then
         swap arr[left], arr[mid]
         increase left and mid by 1
      else if arr[mid] = pivot, then increase mid by 1
      else
         swap arr[mid], arr[right]
         decrease right by 1
   done
   i := left – 1
   j := mid
end
quicksort(arr, left, right) −
begin
   if left >= right, then
      return
   end if
   define i and j
   partition(arr, left, right, i, j)
   quicksort(arr, left, i)
   quicksort(arr, j, right)
end
#include<iostream>
#include<vector>
using namespace std;
void partition(int arr[], int left, int right, int &i, int &j) {
   if (right - left <= 1) {
      if (arr[right] < arr[left])
         swap(arr[right], arr[left]);
      i = left;
      j = right;
      return;
}
int mid = left;
int pivot = arr[right];
while (mid <= right) {
   if (arr[mid]<pivot)
      swap(arr[left++], arr[mid++]);
      else if (arr[mid]==pivot)
         mid++;
      else if (arr[mid] > pivot)
         swap(arr[mid], arr[right--]);
   }
   i = left-1;
   j = mid;
}
void quicksort(int arr[], int left, int right) {
   if (left >= right) //1 or 0 elements
      return;
   int i, j;
   partition(arr, left, right, i, j);
   quicksort(arr, left, i);
   quicksort(arr, j, right);
}
void display(int arr[], int n) {
   for (int i = 0; i < n; ++i)
   cout << " " << arr[i];
   cout << endl;
}
int main() {
   int a[] = {4, 9, 4, 3, 1, 9, 4, 3, 9, 4, 3, 1, 4};
   int n = sizeof(a) / sizeof(int);
   display(a, n);
   quicksort(a, 0, n - 1);
   display(a, n);
}
4 9 4 3 1 9 4 3 9 4 3 1 4
1 1 3 3 3 4 4 4 4 4 9 9 9
Batch Script - Replace a String

To replace a substring with another string use the string substitution feature.
@echo off 
set str=This message needs changed. 
echo %str% 

set str=%str:needs=has% 
echo %str%
The key thing to note about the above program is, the example replaces the word ‘needs’ with the string ‘has’ via the statement %str:needs = has%
The above command produces the following output.
This message needs changed. 
This message has changed.

 Print
 Add Notes
 Bookmark this page
Maximum Sum Increasing Subsequence


Maximum Sum Increasing subsequence is a subsequence of a given list of integers, whose sum is maximum and in the subsequence, all elements are sorted in increasing order.
Let there is an array to store max sum increasing subsequence, such that L[i] is the max sum increasing subsequence, which is ending with array[i].
Input:
Sequence of integers. {3, 2, 6, 4, 5, 1}
Output:
Increasing subsequence whose sum is maximum. {3, 4, 5}.
maxSumSubSeq(array, n)
Input: The sequence of numbers, number of elements.
Output: Maximum sum of the increasing sub sequence.
Begin
   define array of arrays named subSeqLen of size n.
   add arr[0] into the subSeqLen
   for i in  range (1 to n-1), do
      for j in range (0 to i-1), do
         if arr[i] > arr[j] and sum of subSeqLen [i] < sum of subSeqLen [j], then
            subSeqLen[i] := subSeqLen[j]
      done
   done

   add arr[i] into subSeqLen[i]
   res := subSeqLen[0]
           
   for all values of subSeqLen, do
      if sum of subSeqLen[i] > sum of subSeqLen[res], then
         res := subSeqLen[i]
   done

   print the values of res.

End
#include <iostream>
#include <vector>
using namespace std;
 
int findAllSum(vector<int> arr) {    //find sum of all vector elements
   int sum = 0;

   for(int i = 0; i<arr.size(); i++) {
      sum += arr[i];
   }

   return sum;
}
 
void maxSumSubSeq(int arr[], int n) {
   vector <vector<int> > subSeqLen(n);    //max sum increasing subsequence ending with arr[i]
   subSeqLen[0].push_back(arr[0]);

   for (int i = 1; i < n; i++) {         //from index 1 to all
      for (int j = 0; j < i; j++) {     //for all j, j<i
           
         if ((arr[i] > arr[j]) && (findAllSum(subSeqLen[i]) < findAllSum(subSeqLen[j])))
            subSeqLen[i] = subSeqLen[j];
      }
       
      subSeqLen[i].push_back(arr[i]);    //sub Sequence ends with arr[i]
   }
 
   vector<int> res = subSeqLen[0];
 
   for(int i = 0; i<subSeqLen.size(); i++) {
      if (findAllSum(subSeqLen[i]) > findAllSum(res))
         res = subSeqLen[i];
   }

   for(int i = 0; i<res.size(); i++)
      cout << res[i] << " ";
   cout << endl;
}

int main() {
   int arr[] = { 3, 2, 6, 4, 5, 1 };
   int n = 6;
   cout << "The Maximum Sum Subsequence is: ";
   maxSumSubSeq(arr, n);
}
The Maximum Sum Subsequence is: 3 4 5
C# NullReferenceException

NullReferenceException occurs when you try to to access member fields, or function types that points to null.
Here is an example −
 Live Demo
using System;

class Demo {
   static void Main() {
      string str = null;

      if (str.Length > 0) {
         Console.WriteLine(str);
      }
   }
}
The following is the output. It throws NullReferenceException, since you are tryonhg access a memebt that points to null −
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
at Demo.Main () [0x00002] in <0bc5fbf292484d5194a19866ae5c2018>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at Demo.Main () [0x00002] in <0bc5fbf292484d5194a19866ae5c2018>:0
How to split a data frame by column in R?

If we have a data frame column that contains some duplicate values or represent categories then we might want to split the data frame based on that column.
For example, if we have a data frame called df that contains a column say Col then we can split the data frame by Col by using the command given below −
split(df,df$Col)
Following snippet creates a sample data frame −
Group<-sample(c("Male","Female"),20,replace=TRUE)
Score<-rpois(20,8)
df1<-data.frame(Group,Score)
df1
The following dataframe is created −
  Group  Score
1  Male    8
2  Female  6
3  Female  5
4  Female  7
5  Female 12
6  Female 10
7  Female  9
8  Male    9
9  Male   10
10 Female 13
11 Female  4
12 Male   11
13 Female  5
14 Male    6
15 Female  9
16 Male    9
17 Female  5
18 Female  8
19 Male    3
20 Female  5
To split df1 based on Group column, add the following code to the above snippet −
Group<-sample(c("Male","Female"),20,replace=TRUE)
Score<-rpois(20,8)
df1<-data.frame(Group,Score)
split(df1,df1$Group)
If you execute all the above given snippets as a single program, it generates the following output −
$Female
    Group Score
2  Female  6
3  Female  5
4  Female  7
5  Female 12
6  Female 10
7  Female  9
10 Female 13
11 Female  4
13 Female  5
15 Female  9
17 Female  5
18 Female  8
20 Female  5

$Male
  Group Score
1  Male  8
8  Male  9
9  Male 10
12 Male 11
14 Male  6
16 Male  9
19 Male  3
Following snippet creates a sample data frame −
Class<-sample(c("I","II","III"),20,replace=TRUE)
Number_of_Customers<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Number_of_Customers)
df2
The following dataframe is created −
 Class Number_of_Customers
1   II   2
2    I  10
3  III   2
4  III   4
5  III   5
6  III   7
7  III  10
8   II   4
9   II   9
10   I   7
11 III   4
12   I   1
13   I   1
14   I   1
15 III   5
16  II   5
17  II   9
18  II   8
19  II   8
20   I   9
To split df2 based on Class column, add the following code to the above snippet −
Class<-sample(c("I","II","III"),20,replace=TRUE)
Number_of_Customers<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Number_of_Customers)
split(df2,df2$Class)
If you execute all the above given snippets as a single program, it generates the following output −
$I
  Class Number_of_Customers
2   I   10
10  I    7
12  I    1
13  I    1
14  I    1
20  I    9

$II
 Class Number_of_Customers
1  II   2
8  II   4
9  II   9
16 II   5
17 II   9
18 II   8
19 II   8

$III
 Class Number_of_Customers
3  III   2
4  III   4
5  III   5
6  III   7
7  III  10
11 III   4
15 III   5