code-rag-bench/online-tutorials huggingface dataset:
Python - How to Count the NaN Occurrences in a Column in Pandas Dataframe?

To count the NaN occurrences in a column, use the isna(). Use the sum() to add the values and find the count.
At first, let us import the required libraries with their respective aliases −
import pandas as pd
import numpy as np
Create a DataFrame. We have set the NaN values using the Numpy np.inf in “Units_Sold” column −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN]
})
Count NaN values from column "Units_Sold" −
dataFrame["Units_Sold"].isna().sum()

Following is the code −
import pandas as pd
import numpy as np

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, np.NaN, 150, np.NaN, 200, np.NaN]
})

print("Dataframe...\n",dataFrame)

# count NaN values from column "Units_Sol"
count = dataFrame["Units_Sold"].isna().sum()

print("\nCount of NaN values in column Units_Sold...\n",count)
This will produce the following output −
Dataframe...
        Car   Cubic_Capacity   Reg_Price   Units_Sold
0       BMW             2000        7000        100.0
1     Lexus             1800        1500          NaN
2     Tesla             1500        5000        150.0
3   Mustang             2500        8000          NaN
4  Mercedes             2200        9000        200.0
5    Jaguar             3000        6000          NaN

Count of NaN values in column Units_Sold...
3
Python Pandas - Create a subset by choosing specific values from columns based on indexes

To create a subset by choosing specific values from columns based on indexes, use the iloc() method. Let us first import the pandas library
import pandas as pd
Create a Pandas DataFrame with Product records. We have 3 columns in it
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],
"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Creating a subset with 2 columns and 1st 2 rows using iloc(
print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]

Following is the complete code
import pandas as pd

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],
"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

print"DataFrame...\n",dataFrame

print"\nDisplaying a subset:\n",dataFrame['Product']

# creating a subset with 2 columns and 1st 2 rows using iloc()
print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]
This will produce the following output
DataFrame...
   Closing_Stock   Opening_Stock   Product
0          200             300     SmartTV
1          500             700     ChromeCast
2         1000            1200     Speaker
3          900            1500     Earphone

Displaying a subset:
0      SmartTV
1      ChromeCast
2      Speaker
3      Earphone
Name: Product, dtype: object

Displaying a subset using iloc() =
   Closing_Stock   Opening_Stock
0           200            300
1           500            700
Matplotlib.axes.Axes.invert_yaxis() 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.invert_yaxis() function in axes module of matplotlib library is used to invert the y-axis.
Syntax: Axes.invert_yaxis(self)
Parameters: This method does not accepts any parameters.
Returns:This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.invert_yaxis() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y)   fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x])   fig, ax = plt.subplots()ax.plot(yy)w = ax.invert_yaxis()ax.set_title('matplotlib.axes.Axes.invert_yaxis()\ Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Dictionary keys() Method in Java with Examples - GeeksforGeeks

27 Dec, 2018
The keys() method of Dictionary class in Java is used to get the enumeration of the keys present in the dictionary.
Syntax:
Enumeration enu = DICTIONARY.keys()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the keys of the Dictionary.
Below programs are used to illustrate the working of the java.util.Dictionary.keys() method:Program 1:
// Java code to illustrate the keys() methodimport java.util.*;  public class Dictionary_Demo {    public static void main(String[] args)    {          // Creating an empty Dictionary        Dictionary<Integer, String> dict            = new Hashtable<Integer, String>();          // Inserting elements into the Dictionary        dict.put(10, "Geeks");        dict.put(15, "4");        dict.put(20, "Geeks");        dict.put(25, "Welcomes");        dict.put(30, "You");          // Displaying the Dictionary        System.out.println("The Dictionary is: " + dict);          // Creating an empty enumeration to store        Enumeration enu = dict.keys();          System.out.println("The enumeration of keys are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
The Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of keys are:
10
20
30
15
25

Program 2:
// Java code to illustrate the keys() methodimport java.util.*;  public class Dictionary_Demo {    public static void main(String[] args)    {          // Creating an empty Dictionary        Dictionary<String, Integer> dict            = new Hashtable<String, Integer>();          // Inserting elements into the table        dict.put("Geeks", 10);        dict.put("4", 15);        dict.put("Geeks", 20);        dict.put("Welcomes", 25);        dict.put("You", 30);          // Displaying the Dictionary        System.out.println("The Dictionary is: " + dict);          // Creating an empty enumeration to store        Enumeration enu = dict.keys();          System.out.println("The enumeration of keys are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
The Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of keys are:
You
Welcomes
4
Geeks

Java - util package
Java-Collections
Java-Dictionary
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
Java new Keyword

❮ Java Keywords

Create an object called "myObj" and print the value of x:
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}


Try it Yourself »

The new keyword creates new objects.
Read more about objects in our Java Classes/Objects Tutorial.

❮ Java Keywords

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.
List of tuples to dictionary conversion in Python

In this article, we are going to learn how to convert the list of tuples into a dictionary. Converting a list of tuples into a dictionary is a straightforward thing.
Follow the below steps to complete the code.
Initialize the list with tuples.
Use the dict to convert given list of tuples into a dictionary.
Print the resultant dictionary.
Let's see the code.
# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# converting to dict
result = dict(tuples)

# printing the result
print(result)
If you run the above code, you will get the following result.
{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}

Let's add value as list in the resultant dictionary using setdefault() method.
Follow the below steps to complete the code.
Initialize the list with tuples.
Iterate over the list of tuples.
Set default value for the key and append the value.
Print the result.
Let's see the code.
# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# result
result = {}

# iterating over the tuples lists
for (key, value) in tuples:
   # setting the default value as list([])
   # appending the current value
   result.setdefault(key, []).append(value)

# printing the list
print(result)
If you run the above code, you will get the following result.
{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}

If you have any queries in the article, mention them in the comment section.
MATLAB - Scalar Multiplication of Vectors

When you multiply a vector by a number, this is called the scalar multiplication. Scalar multiplication produces a new vector of same type with each element of the original vector multiplied by the number.
Create a script file with the following code −
v = [ 12 34 10 8];
m = 5 * v
When you run the file, it displays the following result −
m =
   60   170    50    40

Please note that you can perform all scalar operations on vectors. For example, you can add, subtract and divide a vector with a scalar quantity.

    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Python 3 - Number max() Method

The max() method returns the largest of its arguments i.e. the value closest to positive infinity.
Following is the syntax for max() method −
max( x, y, z, .... )

x − This is a numeric expression.
x − This is a numeric expression.
y − This is also a numeric expression.
y − This is also a numeric expression.
z − This is also a numeric expression.
z − This is also a numeric expression.
This method returns the largest of its arguments.
The following example shows the usage of the max() method.
#!/usr/bin/python3

print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))
When we run the above program, it produces the following result −
max(80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to check if a vector contains given value in R ? - GeeksforGeeks

05 Apr, 2021
We can check if a vector contains a given value using the %in% operator. For this, we have to create a vector with some values. And we have to read input from the user for what value to be checked. Or we can assign some value to a variable explicitly. Using the %in% operator with the below-given syntax we can find the element we are looking for.
Syntax :
value_to_be_checked %in% vector
The above operation only returns a boolean value that is true or false.
Steps –
Create vector
Set value to be searched
Using the given syntax, search for the element in the vector
If found print true
Else false
Example 1 :
R
vec1 = c(1,2,3,4,5)  a = 1   a %in% vec1
Output :
TRUE
Example 2 :
R
vec1 = c("karthik", "nikhil", "sravan")   a = "karthik"   a %in% vec1
Output :
TRUE
Example 3 :
R
vec1 = c("karthik", "nikhil", "sravan")   a = "krishna"   a %in% vec1
Output :
FALSE
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
JavaScript String substr() Method - GeeksforGeeks

06 Oct, 2021
Below is the example of the String substr() Method.  
Example:  
JavaScript
<script>function func() {    var str = 'Geeks for Geeks';    var sub_str = str.substr(6);    document.write(sub_str);}func();</script>
Output:  
for Geeks
str.substr() method returns the specified number of characters from the specified index from the given string.Syntax:  
str.substr(start , length)
 
start: It defines the starting index from where the substring is to be extracted from the base string.
length: It defines the number of characters to be extracted starting from the start in the given string. If the second argument to the function is undefined then all the characters from the start till the end of the length are extracted.
Return value: This method returns a string that is the part of the given string. If the length is 0 or negative value then it returns an empty string.Examples for the above method are provided below:Example 1:  
var str = 'It is a great day.'
print(str.substr(5));
Output:  
 a great day.
In this example the method substr() creates a substring starting from index 5 till the end of the string.Example 2:  
var str = 'It is a great day.'
print(str.substr(5,6));
Output:  
 a gre
In this example the method substr() extracts the substring starting at index 5 and length of string is 6.Example 3:  
var str = 'It is a great day.'
print(str.substr(5,-7));
Output:  
 
In this example since the length of the string to be extracted is negative therefore the method returns an empty string.Codes for the above method are provided below:Program 1: 
JavaScript
<script>// JavaScript to illustrate substr() function function func() {     // Original string    var str = 'It is a great day.';    var sub_str = str.substr(5);    document.write(sub_str);} func();</script>
Output:  
 a great day.
Program 2: 
JavaScript
<script>// JavaScript to illustrate substr() function function func() {     // Original string    var str = 'It is a great day.';     var sub_str = str.substr(5,6);    document.write(sub_str);} func();</script>
Output:  
 a gre
Program 3: 
JavaScript
<script>// JavaScript to illustrate substr() function function func() {     // Original string    var str = 'It is a great day.';     var sub_str = str.substr(5,-7);    document.write(sub_str);}func();</script>
Output:  
 
 
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
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
Difference Between PUT and PATCH Request
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?
How to draw a rounded Rectangle on HTML Canvas?

To draw a rectangle in HTML, use the canvas element. With canvas, use the rect() method to draw a rectangle. But, for creating a rounded rectangle, using the rect() method won’t work. We will be using the lineTo() and quadraticCurveTo() method to create a rounded rectangle.
This is how you can create a canvas in HTML5 −
You can learn how to create a rounded rectangle in canvas
<!DOCTYPE HTML>
<html>
   <head>
      <title>HTML5 Canvas Tag</title>
   </head>
   <body>
      <canvas id="newCanvas" width="300" height="150"></canvas>
      <script>
         var canvas = document.getElementById('newCanvas');
         var ctx = canvas.getContext('2d');
         ctx.beginPath();
         ctx.moveTo(20, 10);
         ctx.lineTo(80, 10);
         ctx.quadraticCurveTo(90, 10, 90, 20);
         ctx.lineTo(90, 80);
         ctx.quadraticCurveTo(90, 90, 80, 90);
         ctx.lineTo(20, 90);
         ctx.quadraticCurveTo(10, 90, 10, 80);
         ctx.lineTo(10, 20);
         ctx.quadraticCurveTo(10, 10, 20, 10);
         ctx.stroke();
      </script>
   </body>
</html>
Does it make sense to use “LIMIT 1” in a query “SELECT 1 ...”?

Yes, you can use LIMIT 1 with SELECT1.
Suppose, you are using SELECT 1 and your table has billions of records. In this case, it will print 1 billion times.
The syntax of SELECT 1 is as follows −
SELECT 1 FROM yourTableName;
Suppose, you are using LIMIT 1 and your table has billions of records. This case, it will print 1 only once.
The syntax of SELECT 1 with LIMIT 1 is as follows −
SELECT 1 FROM yourTableName LIMIT 1;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Select1AndLimit1Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.99 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into Select1AndLimit1Demo(Name) values('John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('David');
Query OK, 1 row affected (0.14 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('Mike');
Query OK, 1 row affected (0.20 sec)
mysql> insert into Select1AndLimit1Demo(Name) values('Maxwell');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from Select1AndLimit1Demo;
+----+---------+
| Id | Name    |
+----+---------+
|  1 | John    |
|  2 | Carol   |
|  3 | Sam     |
|  4 | Bob     |
|  5 | David   |
|  6 | Mike    |
|  7 | Maxwell |
+----+---------+
7 rows in set (0.00 sec)
Here is the case of SELECT 1. The query is as follows −
mysql> select 1 from Select1AndLimit1Demo;
+---+
| 1 |
+---+
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
+---+
7 rows in set (0.00 sec)
Above, we have a table with 7 records. Therefore, the output is 7 times 1.
Let us now see the case of SELECT 1 with LIMIT 1. The query is as follows −
mysql> select 1 from Select1AndLimit1Demo limit 1;
The following is the output displaying the value 1 only once −
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
Above, our table has 7 records. We are getting 1 times 1 because we have used LIMIT 1.
How to convert Dictionary to Hashtable in PowerShell?

Like any other data type conversion in PowerShell, we can convert Dictionary to hashtable in a similar way.  We have a below Dictionary for the example called $CityData.
Key     Value
---     -----
India      91
Austria    43
Its datatype is Dictionary,
PS C:\> $citydata.GetType() | ft -AutoSize
IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Dictionary`2 System.Object
To convert it to the hashtable,
$hash = [Hashtable]$citydata
Or
$hash = [System.Collections.Hashtable]$CityData
Datatype:
PS C:\> $hash | ft -AutoSize
Name    Value
----    -----
Austria 43
India   91
How to create and populate two-dimension Java array?

A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns −
 Live Demo
public class Creating2DArray {

public static void main(String args[]) {
int[][] myArray = new int[3][3];
myArray[0][0] = 21;
myArray[0][1] = 22;
myArray[0][2] = 23;
myArray[1][0] = 24;
myArray[1][1] = 25;
myArray[1][2] = 26;
myArray[2][0] = 27;
myArray[2][1] = 28;
myArray[2][2] = 29;

for(int i=0; i<myArray.length; i++ ) {
for(int j=0;j<myArray.length; j++) {
System.out.println(myArray[i][j]);
}
}
}
}
21
22
23
24
25
26
27
28
29
Convert Unicode to ASCII in Python - GeeksforGeeks

05 Aug, 2021
Unicode is the universal character set and a standard to support all the world’s languages. It contains 140,000+ characters used by 150+ scripts along with various symbols. ASCII on the other hand is a subset of Unicode and the most compatible character set, consisting of 128 letters made of English letters, digits, and punctuation, with the remaining being control characters. This article deals with the conversion of a wide range of Unicode characters to a simpler ASCII representation using the Python library anyascii.
The text is converted from character to character. The mappings for each script are based on conventional schemes. Symbolic characters are converted based on their meaning or appearance. If the input contains ASCII characters, they are untouched, the rest are all tried to be converted to ASCII. Unknown characters are removed.
To install this module type the below command in the terminal.
pip install anyascii
Example 1: Working with Several languages
In this, various different languages like Unicode are set as input, and output is given as converted ASCII characters. 
Python3
from anyascii import anyascii  # checking for Hindi scripthindi_uni = anyascii('नमस्ते विद्यार्थी')  print("The translation from hindi Script : "      + str(hindi_uni))  # checking for Punjabi scriptpun_uni = anyascii('ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ')  print("The translation from Punjabi Script : "      + str(pun_uni))
Output : 
The translation from hindi Script : nmste vidyarthi
The translation from Punjabi Script : sti sri akal
Example 2: Working with Unicode Emojis and Symbols
This library also handles working with emojis and symbols, which are generally Unicode representations. 
from anyascii import anyascii

# working with emoji example
emoji_uni = anyascii('  ')

print("The ASCII from emojis : "
      + str(emoji_uni))

# checking for Symbols
sym_uni = anyascii(' ☆ M')

print("The ASCII from Symbols : "
      + str(sym_uni))
Output:
The ASCII from emojis : :sunglasses: :crown: :apple:
The ASCII from Symbols : :heavy_plus_sign: * M
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
How to convert a JavaScript date to UTC? - GeeksforGeeks

22 Apr, 2019
The Javascript date can be converted to UTC by using functions present in Javascript Date object.The toUTCString() method is used to convert a Date object into a string, according to universal time.The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone.
By default, JavaScript uses the browser’s time zone and display a date as a full-text string:Fri Apr 12 2019 10:32:15 GMT+0530 (India Standard Time).To create a new Date object we use javascript Date() constructor.
Syntax:
dateObj.toUTCString()
Example-1:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width,                    initial-scale=1.0">    <meta http-equiv="X-UA-Compatible"           content="ie=edge">    <title>      Document  </title></head>  <body>    <div id="date">      </div></body><script>    var d = new Date();    var n = d.toUTCString();    var e = document.querySelector("#date");    e.innerHTML = n;</script>  </html>
Output:
Fri, 12 Apr 2019 05:14:31 GMT
Example-2:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width,                   initial-scale=1.0">        <meta http-equiv="X-UA-Compatible"           content="ie=edge">    <title>      Document  </title></head>  <body>    <div id="date">      </div></body><script>    var d = new Date();    var e = document.querySelector("#date");    e.innerHTML = d.toGMTString();</script>  </html>
Output:
Fri, 12 Apr 2019 05:39:32 GMT
ReferencesJavascript Date Object
javascript-date
Picked
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 append HTML code to a div using 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?
How to get the n-largest values of an array using NumPy? - GeeksforGeeks

29 Aug, 2020
Let’s see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing.
Syntax: numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None)
Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr.
Let’s see an example:
Example 1: Getting the 1st largest value from a NumPy array.
Python3
# import libraryimport numpy as np  # create numpy 1d-arrayarr = np.array([2, 0,  1, 5,                4, 1, 9])  print("Given array:", arr)  # sort an array in# ascending order  # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr)  # sorted arraysorted_array = arr[sorted_index_array]  print("Sorted array:", sorted_array)  # we want 1 largest valuen = 1  # we are using negative# indexing concept  # take n largest valuerslt = sorted_array[-n : ]  # show the outputprint("{} largest value:".format(n),      rslt[0])
Output:
Given array: [2 0 1 5 4 1 9]
Sorted array: [0 1 1 2 4 5 9]
1 largest value: 9

Example 2: Getting the 3-largest values from a NumPy array.
Python3
# import libraryimport numpy as np  # create numpy 1d-arrayarr = np.array([2, 0,  1, 5,                4, 1, 9])  print("Given array:", arr)  # sort an array in# ascending order  # np.argsort() return# array of indices for# sorted arraysorted_index_array = np.argsort(arr)  # sorted arraysorted_array = arr[sorted_index_array]  print("Sorted array:", sorted_array)  # we want 3 largest valuen = 3  # we are using negative# indexing concept  # find n largest valuerslt = sorted_array[-n : ]  # show the outputprint("{} largest value:".format(n),      rslt)
Output:
Given array: [2 0 1 5 4 1 9]
Sorted array: [0 1 1 2 4 5 9]
3 largest value: [4 5 9]

Python numpy-Mathematical Function
Python numpy-program
Python-numpy
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()
C++ Library - <basic_istream>

It is used for Input stream objects can read and interpret input from sequences of characters. Specific members are provided to perform these input operations.
The standard objects cin and wcin use particular instantiations of this class template.
Below is definition of std::basic_istream.
template <class charT, class traits = char_traits<charT>>
   class basic_istream;
charT − Character type.
charT − Character type.
traits − Character traits class that defines essential properties of the characters used by stream objects.
traits − Character traits class that defines essential properties of the characters used by stream objects.
 Print
 Add Notes
 Bookmark this page
How to get current day, month and year in Java 8?

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.
This class also provides various other useful methods among them −
The getYear() method returns an integer representing the year filed in the current LocalDate object.
The getMonth() method returns an object of the java.timeMonth class representing the month in the LocalDate object.
The getDaYofMonth() method returns an integer representing the day in the LocalDate object.
Following Java example retrieves the current date and prints the day, year and, month separately using the above specified methods.
import java.time.LocalDate;
import java.time.Month;
public class LocalDateJava8 {
   public static void main(String args[]) {
      //Getting the current date value
      LocalDate currentdate = LocalDate.now();
      System.out.println("Current date: "+currentdate);
      //Getting the current day
      int currentDay = currentdate.getDayOfMonth();
      System.out.println("Current day: "+currentDay);
      //Getting the current month
      Month currentMonth = currentdate.getMonth();
      System.out.println("Current month: "+currentMonth);
      //getting the current year
      int currentYear = currentdate.getYear();
      System.out.println("Current month: "+currentYear);
   }
}
Current date: 2019-07-24
Current day: 24
Current month: JULY
Current month: 2019
Joining DataFrames matching by substring with Python Pandas | by Cristian Saavedra Desmoineaux | Towards Data Science

The next Python Pandas code made it for Jupyter Notebook is available in GitHub, and It answers the question: “Which tasks don’t match?”
The first part of the code creates two DataFrames: df1 and df2.
The df1 DataFrame has the complete name of the tasks in the task_name column.
And the df2 DataFrame has a substring in the partial_task_name column.
Look that the value BC in partial_task_name is a substring of ABC and BCD, the expected result must produce many rows for this case, but how can we get many rows? The answer is using a Cartesian Product or Cross Join.
To do a Cartesian Product in Pandas, do the following steps:
Add a dummy column with the same value en each of the DataFramesDo a join by the new columnRemove the new column in each DataFrame
Add a dummy column with the same value en each of the DataFrames
Do a join by the new column
Remove the new column in each DataFrame
df1['join'] = 1df2['join'] = 1dfFull = df1.merge(df2, on='join').drop('join', axis=1)df2.drop('join', axis=1, inplace=True)
The next step is to add a new column in the result DataFrame returning if the partial_task_name column is in the task_name column. We are going to use a lambda and “find” function where the result is ≥ 0
dfFull['match'] = dfFull.apply(lambda x: x.task_name.find(x.partial_task_name), axis=1).ge(0)
The product is the dfFull DataFrame
We do a group by task_name, pipeline_name, and get the match's maximum to filter.
To know which tasks don’t exist in the df2 DataFrame we do a negative filter by the match column:
If we don't use the Cartesian Product and instead we try adding the first match in df2 DataFrame and then do a left join with df1 DataFrame
We are making a common mistake that it gives us the wrong answer BCD.
Because when we used the first match, ABC matched with BC instead of BCD.
There is a more generic technique called Approximate string matching or colloquially know it as Fuzzy Lookup that tries to solve similar or partial non-consecutive substrings too. If It is your case, you can try with fuzzywuzzy.
Thank you to Charles Romestant to giving me the inspiration for this post
C# String.PadLeft Method

Pad the beginning of the string with spaces using the PadLeft() method. You can also pad it with a Unicode character.
Let’s say the following is our string.
string myStr = "DemoOne";
To set a padding at the beginning of the above string, use the PadLeft method.
myStr.PadLeft(10);
Here is the complete example.
 Live Demo
using System;
class Demo {
   static void Main() {
      string myStr = "DemoOne";
      // set padding at the beginning
      Console.WriteLine(myStr.PadLeft(10));
      myStr = "DemoTWO";
      // set padding at the beginning
      Console.Write(myStr.PadLeft(15));
   }
}
DemoOne
DemoTWO
How to get all options in a drop-down list by Selenium WebDriver using C#?

We can get all options in a drop−down list by Selenium Webdriver in C#. The static drop−down in an html code is identified with a select tag. All the options for a drop−down have the option tag.
To obtain all the options in the form of a list, we shall first identify that element with the help of any of the locators like id, xpath, name, and so on. Then we must create an object of the SelectElement class and apply Options method on it.
Let us investigate the html code of drop−down.
For implementation we shall be using the NUnit framework.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NUnitTestProject1{
   public class Tests{
      String u = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate()
         .GoToUrl(u);
         //identify dropdown
         IWebElement l = d.FindElement(By.Name("continents"));
         //object of SelectElement
         SelectElement s = new SelectElement(l);
         //Options method to get all options
         IList<IWebElement> els = s.Options;
         //count options
         int e = els.Count;
         for (int j = 0; j < e; j++){
            Console.WriteLine("Option at " + j + " is: " + els.ElementAt(j).Text);
         }
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}
Click on Run All Tests −
Click on Open additional output for this result link −
We should get the Test Outcome and Standard Output.
Possibility of moving out of maze in C++

In this problem, we are given a maze of n integers, each integer indicates the number of moves to be done. Along with the direction indicated using ‘>’ and ‘<’. Our task is to find whether it is possible to move out of the maze or not if the starting point is the position at 0 indexes.
Let’s take an example to understand the problem
Input −
3
2 1 1 4
> < > >
Output − YES
Explanation − moving from start, we will move 2 positions ahead, then 1 position ahead, then 4 positions ahead. This will move our of the maze.
To solve this problem, we will check whether moving out of the maze is possible or not. For this either we need to go below 0 or above n. Starting from 0, we will process the direction based on the sign by given integer places. And check if the end is reached.
One more condition that can arise is an infinite loop, i.e. the condition when the user never breaks out of the maze, this is when we come back to a visiting position. So, to check this condition we will mark all visited places.
Program to show the implementation of our solution
 Live Demo
#include <iostream>
using namespace std;
void isMazeSolvable (int a[], int n, string s){
   int mark[n] = {0};
   int start = 0;
   int possible = 1;
   while (start >= 0 && start < n){
      if (s == "<"){
         if (mark[start] == 0){
            mark[start] = 1;
            start -= a[start];
         } else {
            possible = 0;
            break;
         }
      } else {
         if (mark[start] == 0){
            mark[start] = 1;
            start += a[start];
         } else {
            possible = 0;
            break;
         }
      }
   }
   if (possible == 0)
      cout << "It stays inside the maze forever";
   else
      cout << "It will come out of the maze";
}
int main (){
   int n = 3;
   string s = ">><";
   int a[] = { 1, 2, 4 };
   isMazeSolvable (a, n, s);
}
It will come out of the maze
Largest Values From Labels in Python

Suppose we have a set of items: the i-th item has value values[i] and label labels[i]. Then, we will take a subset S of these items, such that −
|S| <= num_wanted
For every label L, the number of items present in S with label L is <= use_limit.
We have to find the largest possible sum of the subset S.
For example, if the input is like values = [5,4,3,2,1] and labels are [1,1,2,2,3], num_wanted = 3, use_limit = 1, then the output will be 9. This is because the subset chosen in the first, third and fifth item.
To solve this, we will follow these steps −
make one array v
for i in range 0 to length of valuesinsert [values[i], labels[i]] into v
insert [values[i], labels[i]] into v
sort the v array
ans := 0, use := empty map, and i := 0
while num_wanted and i < length of vif v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1increase i by 1
if v[i, 1] is not present in use mapdecrease num_wanted by 1ans := ans + v[i, 0]use[v[i, 1]] := 1
decrease num_wanted by 1
ans := ans + v[i, 0]
use[v[i, 1]] := 1
else use[v[i, 1]] < use_limitdecrease num_wanted by 1ans := ans + v[i, 0]increase use[v[i, 1]] by 1
decrease num_wanted by 1
ans := ans + v[i, 0]
increase use[v[i, 1]] by 1
increase i by 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def largestValsFromLabels(self, values, labels, num_wanted, use_limit):
      v = []
      for i in range(len(values)):
         v.append([values[i],labels[i]])
      v = sorted(v,key = lambda v:v[0],reverse=True)
      ans = 0
      use = {}
      i = 0
      while num_wanted and i < len(v):
         if v[i][1] not in use:
            num_wanted -=1
            ans+=v[i][0]
            use[v[i][1]] = 1
         elif use[v[i][1]]<use_limit:
            num_wanted -=1
            ans+=v[i][0]
            use[v[i][1]]+=1
         i+=1
      return ans
ob = Solution()
print(ob.largestValsFromLabels([5,4,3,2,1],[1,1,2,2,3],3,1))
[5,4,3,2,1]
[1,1,2,2,3]
3
1
9
AngularJS | angular.isDefined() Function - GeeksforGeeks

12 Apr, 2019
The angular.isDefined() function in AngularJS is used to determine the value inside isDefined function is defined or not. It returns true if the reference is a defined otherwise returns false.
Syntax:
angular.isDefined( value )
Return Value: It returns true if the passed value is defined otherwise returns false.
Example: This example uses angular.isDefined() function to determine the value inside isDefined function is defined or not.
<!DOCTYPE html><html>    <head>        <title>angular.isDefined()</title>                  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">        </script>    </head>      <body ng-app="app" style="text-align:center">        <h1 style="color:green">GeeksforGeeks</h1>        <h2>angular.isDefined()</h2>                  <div ng-controller="geek">            <b>Date:</b> {{date}}<br><br>            {{isDefined}}        </div>                  <!-- Script to uses angular.isDefined() function -->        <script>            var app = angular.module("app", []);            app.controller('geek', ['$scope', function ($scope) {            $scope.date;                          $scope.isDefined = angular.isDefined($scope.date)                    == true ? "$scope.date is defined."                    : "$scope.date is undefined.";            }]);        </script>    </body></html>                    
Output:
Date not Defined:
If Date is defined and its value is “2019-04-07T23:46:20.586”:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular | keyup event
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Auth Guards in Angular 9/10/11
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?
Tryit Editor v3.7

CSS Style Images
Tryit: Different filters on image
Tryit Editor v3.7

Tryit: HTML link to same folder
Java Examples - Getting Thread Name

How to get the name of a running thread?
Following example shows how to get the name of a running thread.
public class TwoThreadGetName extends Thread {
   public void run() {
      for (int i = 0; i < 10; i++) {
         printMsg();
      }
   }
   public void printMsg() {
      Thread t = Thread.currentThread();
      String name = t.getName();
      System.out.println("name=" + name);
   } 
   public static void main(String[] args) {
      TwoThreadGetName tt = new TwoThreadGetName();
      tt.start();
      for (int i = 0; i < 10; i++) {
         tt.printMsg();
      }
   }
}
The above code sample will produce the following result.
name = main
name = main
name = main
name = main
name = main
name = thread
name = thread
name = thread
name = thread

 Print
 Add Notes
 Bookmark this page
Disable Exit (or [ X ]) in Tkinter Window

The window manager implements the Tkinter window control icons. To hide and show the Tkinter window control icons, we can use the built-in function, which describes whether we want to disable control icons’ functionality.
To disable the Exit or [X] control icon, we have to define the protocol() method. We can limit the control icon definition by specifying an empty function for disabling the state of the control icon.
#Import the tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry of the function
win.geometry("750x250")
def close_win():
   win.destroy()
def disable_event():
   pass
#Create a button to close the window
btn = ttk.Button(win, text ="Click here to Close",command=close_win)
btn.pack()
#Disable the Close Window Control Icon
win.protocol("WM_DELETE_WINDOW", disable_event)
win.mainloop()
The above code will display a window that has a disabled [X] window close control.
To close the window, click the button "Click here to Close."
C++ String Library - append

It extends the string by appending additional characters at the end of its current value.
Following is the declaration for std::string::append.
string& append (const string& str);
string& append (const string& str);
string& append (const string& str);
str − It is a string object.
str − It is a string object.
c − It is a character object.
c − It is a character object.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::append.
#include <iostream>
#include <string>

int main () {
   std::string str;
   std::string str2="Writing ";
   std::string str3="print 10 and then 5 more";

   str.append(str2);
   str.append(str3,6,3);
   str.append("dots are cool",5);
   str.append("here: ");
   str.append(10u,'.');
   str.append(str3.begin()+8,str3.end());
   str.append<int>(5,0x2E);
   std::cout << str << '\n';
   return 0;
}
Writing 10 dots here: .......... and then 5 more.....

 Print
 Add Notes
 Bookmark this page
How to delete all users from specific OU using PowerShell?

To remove all users from the specific OU, we need to first retrieve the users from that OU. For example, we have 3 users in the OU called LABDOMAIN and we need to delete them all.
Get-ADUser -SearchBase "OU=LabUsers,DC=labdomain,DC=local" -Filter *
The above command will retrieve users from the specific OU and then we can use the Remove-ADUser command to delete them all.
Get-ADUser -SearchBase "OU=LabUsers,DC=labdomain,DC=local" -Filter * | Remove-ADUser -Confirm:$false -Verbose
-Confirm switch has been added to bypass the confirmation for all the users. The default confirmation is true.
VERBOSE: Performing the operation "Remove" on target "CN=JensonA,OU=LabUsers,DC=labdomain,DC=local". VERBOSE: Performing the operation "Remove" on target "CN=ChrisT,OU=LabUsers,DC=labdomain,DC=local". VERBOSE: Performing the operation "Remove" on target "CN=ChiragN,OU=LabUsers,DC=labdomain,DC=local".