code-rag-bench/online-tutorials huggingface dataset:
How to Fix: Invalid value encountered in true_divide - GeeksforGeeks

22 Nov, 2021
In this article, we are going to fix, invalid values encountered in true_divide in Python. Invalid value encountered in true_divide is a Runtime Warning occurs when we perform an invalid division operation between elements of NumPy arrays.  One of the examples of Invalid division is 0/0. 
Note: As it is just a Warning the code won’t stop from its execution and return a Not a Number value i.e. nan (or) inf (infinity).
The division operation between NumPy arrays can be done using divide() which is present in NumPy package allows division operation between corresponding elements of 2 arrays. 
Python3
# import necessary packagesimport numpy as np  # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0])  # divide the values in Array1 by the# values in Array2np.divide(Array1, Array2)
Output:
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in true_divide
  if __name__ == ‘__main__’:
Result-array([ 2.,  1., nan]) 
Here we are dividing the elements of Array1 by the elements of Array2. So it returns the quotient value.
6/3=2  (Valid Operation)
2/2=1  (Valid Operation)
0/0    which is an invalid operation so a Warning is thrown and returns the result as Not a Number (nan).
We can fix this Runtime Warning by using seterr method which takes invalid as a parameter and assign ignore as a value to it. By that, it can hide the warning message which contains invalid in that.
Syntax: numpy.seterr(invalid=’ignore’)
Python3
# import necessary packagesimport numpy as np  # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0])  # Supress/hide the warningnp.seterr(invalid='ignore')  # divide the values in Array1 by the # values in Array2np.divide(Array1, Array2)
Output:
array([ 2.,  1., nan])
Picked
Python How-to-fix
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
jQuery - add( selector ) Method

The add( selector ) method adds more elements, matched by the given selector, to the set of matched elements.
Here is the simple syntax to use this method −
selector.add( selector )

Here is the description of all the parameters used by this method −
selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(".class1, .class2")).
selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(".class1, .class2")).
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $(".top").add(".middle").addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li class = "above">list item 0</li>
            <li class = "top">list item 1</li>
            <li class = "top">list item 2</li>
            <li class = "middle">list item 3</li>
            <li class = "middle">list item 4</li>
            <li class = "bottom">list item 5</li>
            <li class = "bottom">list item 6</li>
            <li class = "below">list item 7</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 0
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
list item 7
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $(".top").add(".middle").addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li class = "above">list item 0</li>
            <li class = "selected">list item 1</li>
            <li class = "selected">list item 2</li>
            <li class = "selected">list item 3</li>
            <li class = "selected">list item 4</li>
            <li class = "bottom">list item 5</li>
            <li class = "bottom">list item 6</li>
            <li class = "below">list item 7</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 0
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
list item 7

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Python 3 - String index() Method

The index() method determines if the string str occurs in string or in a substring of string, if the starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found.
Following is the syntax for index() method −
str.index(str, beg = 0 end = len(string))

str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
end − This is the ending index, by default its equal to the length of the string.
Index if found otherwise raises an exception if str is not found.
#!/usr/bin/python3

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))
When we run above program, it produces the following result −
15
15
Traceback (most recent call last):
   File "test.py", line 7, in <module>
      print (str1.index(str2, 40))
ValueError: substring not found
shell returned 1


    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
GATE | GATE-CS-2014-(Set-2) | Question 60 - GeeksforGeeks

28 Jun, 2021
Consider the following relation on subsets of the set S of integers between 1 and 2014. For two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U.
Consider the following two statements:
S1: There is a subset of S that is larger than every other subset.
S2: There is a subset of S that is smaller than every other subset. 
Which one of the following is CORRECT?(A) Both S1 and S2 are true(B) S1 is true and S2 is false(C) S2 is true and S1 is false(D) Neither S1 nor S2 is true
Explanation –As question defined that “for two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U".Given, S = {1, 2, 3, ...., 2014}.Therefore,Subsets {1, 2, 3, ...., 2014} and {Ø} of S, so {1, 2, 3, ...., 2014} < {Ø} because the minimum element in the symmetric difference (i.e., {1, 2, 3, ...., 2014}) of the two sets is in set {1, 2, 3, ...., 2014}.Hence, {Ø} is a subset of S that is larger than every other subset.And, {1, 2, 3, ...., 2014} is a subset of S that is smaller than every other subset.Option (A) is correct.
 Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47
Set.size Property in JavaScript

The size property of the Set object returns number representing the number of elements in the current set object.
Its Syntax is as follows
Obj.size();
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      const setObj = new Set();
      setObj.add('Java');
      setObj.add('JavaFX');
      setObj.add('JavaScript');
      setObj.add('HBase');
      document.write("Size of the Set object: "+setObj.size);
   </script>
</body>
</html>
Size of the Set object: 4
SaltStack - Creating a Simple Environment

In this chapter, we will create a simple SaltStack environment, one salt master and two salt minions. This environment will help us to learn the salt concept in the upcoming chapters.
Let us adhere to the following steps to create the SaltStack environment.
VirtualBox is a cross-platform virtualization application. VirtualBox allows you to run more than one operating system at a time. VirtualBox runs on Windows, Linux, Macintosh and Solaris. It hosts and supports a large number of Guest Operating Systems.
You can download and install VirtualBox by visiting the following link − https://www.virtualbox.org/wiki/Downloads
We will create three virtual machines and run it using the VirtualBox.
Vagrant provides easy to configure, reproducible and portable work environments.
You can download and install the Vagrant by visiting the following link − https://www.vagrantup.com
After the successful installation of Vagrant, you need to configure it. Create a single file named as Vagrantfile in a folder and describe the type of machine and its properties.
Run Vagrant − To run the Vagrant, issue the following command −
vagrant up

After you run vagrant up, Vagrant creates and starts those machines, which are defined in the Vagrantfile using the VirtualBox in the background. These machines will be running until you close them.
Stop Vagrant − To stop all the running machines in the VirtualBox, type the following command −
vagrant halt

SaltStack provides a simple demo environment as Vagrant setup and it is hosted in the github. Let us download the setup using the following command −
cd /cd/to/path

git clone https://github.com/UtahDave/salt-vagrant-demo

Now, start the demo environment using the following command −
cd /cd/to/path/salt-vagrant-demo
vagrant up

After this command, you will see the following response −
result

Now, three servers are running, one with the salt master configured and two with the salt minion configured.
Login to the Salt master using the following command −
vagrant ssh master

Now, move to the root user using the command below −
sudo su

Now we have successfully connected to the Salt master.
Let us now go through some of the basic commands in SaltStack.
The following command is to verify the Salt minion connections and view whether the connection is accepted, rejected or pending.
salt-key —list-all
It will produce the following output −
Accepted Keys:
minion1
minion2
Denied Keys:

Unaccepted Keys:
Rejected Keys:

Now, we have accepted all the keys, you can send a command from Salt master to check whether Salt minions are listening or not,
salt '*' test.ping

It will produce the following output −
minion1:
   True
minion2:
   True

From the above result, list out minion 1 and minion 2, which means minions are listening properly, otherwise minions might now respond properly.
 Print
 Add Notes
 Bookmark this page
C# program to determine if a string has all unique characters

Use the substring() method in C# to check each and every substring for unique characters. Loop it until the length of the string.
If any one the substring matches another, then it would mean that the string do not have unique characters.
You can try to run the following code to determine if a string has all unique characters.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Demo {
   public bool CheckUnique(string str) {
      string one = "";
      string two = "";
      for (int i = 0; i < str.Length; i++) {
         one = str.Substring(i, 1);
         for (int j = 0; j < str.Length; j++) {
            two = str.Substring(j, 1);
            if ((one == two) && (i != j))
            return false;
         }
      }
      return true;
   }
   static void Main(string[] args) {
      Demo d = new Demo();
      bool b = d.CheckUnique("amit");
      Console.WriteLine(b);
      Console.ReadKey();
   }
}
True
How can I set an ImageView's width and height programmatically in Android?

This example demonstrates about How can I set an ImageView's width and height programmatically in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:id="@+id/rlMain"
   android:layout_height="match_parent"
   android:layout_margin="16dp" />
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      RelativeLayout rlMain = findViewById(R.id.rlMain);
      ImageView imageView = new ImageView(this);
      imageView.setImageResource(R.drawable.ic_launcher_background);
      RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
         RelativeLayout.LayoutParams.MATCH_PARENT,
         RelativeLayout.LayoutParams.MATCH_PARENT
      );
      imageView.setLayoutParams(params);
      rlMain.addView(imageView);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Arduino - millis () function

This function is used to return the number of milliseconds at the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 50 days.
millis () ;

This function returns milliseconds from the start of the program.
unsigned long time; void setup() { 
   Serial.begin(9600); 
} 

void loop() { 
   Serial.print("Time:"); time = millis();
   //prints time since program started
   Serial.println(time); 
   // wait a second so as not to send massive amounts of data
   delay(1000); 
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Plot a circle with an edgecolor in Matplotlib

To plot a circle with an edgecolor in matplotlib, we can take the following Steps −
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add a subplot method to the current axis.
Add a subplot method to the current axis.
Create a circle instance using Circle() class with an edgecolor and linewidth of the edge.
Create a circle instance using Circle() class with an edgecolor and linewidth of the edge.
Add a circle path on the plot.
Add a circle path on the plot.
To place the text in the circle, we can use text() method.
To place the text in the circle, we can use text() method.
Scale the X and Y axes using xlim() and ylim() methods.
Scale the X and Y axes using xlim() and ylim() methods.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib
from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
circle = matplotlib.patches.Circle((0, 0), radius=1, edgecolor="orange", linewidth=7)
ax.add_patch(circle)
plt.text(-.25, 0, "Circle")
plt.xlim([-4, 4])
plt.ylim([-4, 4])
plt.axis('equal')
plt.show()
How to draw a filled circle in OpenCV using Java?

The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. This class provides a method named circle(), using this you can draw a
circle on an image. This method provides the following parameters −
A Mat object representing the image on which the circle is to be drawn.
A Mat object representing the image on which the circle is to be drawn.
A Point object representing the center of the circle.
A Point object representing the center of the circle.
An integer variable representing the radius of the circle.
An integer variable representing the radius of the circle.
A Scalar object representing the color of the circle(BGR).
A Scalar object representing the color of the circle(BGR).
An integer representing the thickness of the circle(default 1).
An integer representing the thickness of the circle(default 1).
If you pass Imgproc.FILLEDas line type, this method generates/draws a filled circle.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingFilledCircle {
   public static void main(String args[]) {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the source image in to a Mat object
      Mat src = Imgcodecs.imread("D:\\images\\blank.jpg");
      //Drawing a Circle
      Point center = new Point(300, 200);
      int radius =100;
      Scalar color = new Scalar(64, 64, 64);
      int thickness = Imgproc.FILLED;
      Imgproc.circle (src, center, radius, color, thickness);
      //Saving and displaying the image
      Imgcodecs.imwrite("arrowed_line.jpg", src);
      HighGui.imshow("Drawing a circle", src);
      HighGui.waitKey();
   }
}
On executing, the above program generates the following window −
How to write a MySQL stored function that inserts values in a table?

As we know that function is best used when we want to return a result. Hence, when we will create stored functions for manipulating tables like to Insert or Update values then it would be more or less like stored procedures.
In the following example we are creating a stored function named ‘tbl_insert’ which will insert the values in a table named ‘student_marks’.
mysql> Create Function tbl_insert(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT)
    -> RETURNS INT
    -> DETERMINISTIC
    -> BEGIN
    -> INSERT INTO student_marks values(S_name,M1,M2,M3,M4);
    -> RETURN 1;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> Select tbl_insert('Saurabh',85,79,65,71);
+------------------------------+
| tbl_insert('RR',58,25,65,32) |
+------------------------------+
|                            1 |
+------------------------------+
1 row in set (0.07 sec)

mysql> Select * from student_marks;
+---------+------+---------+---------+---------+
| Name    | Math | English | Science | History |
+---------+------+---------+---------+---------+
| Raman   |   95 |      89 |      85 |      81 |
| Rahul   |   90 |      87 |      86 |      81 |
| Mohit   |   90 |    NULL |      86 |      81 |
| Saurabh |   85 |      79 |      65 |      71 |
+---------+------+---------+---------+---------+
4 rows in set (0.00 sec)
Python Bokeh - Plotting Triangles on a Graph - GeeksforGeeks

10 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
Bokeh can be used to plot triangles on a graph. Plotting triangles on a graph can be done using the triangle() method of the plotting module.
Syntax : triangle(parameters)
Parameters :
x : x-coordinates of the center of the triangle markers
y : y-coordinates of the center of the triangle markers
Returns : an object of class GlyphRenderer
Example 1 : In this example we will be using the default values for plotting the graph.
# importing the modulesfrom bokeh.plotting import figure, output_file, show         # file to save the modeloutput_file("gfg.html")         # instantiating the figure objectgraph = figure(title = "Bokeh Triangle Graph")       # the points to be plottedx = 0y = 0      # plotting the graphgraph.triangle(x, y, size = 30)       # displaying the modelshow(graph) 
Output :
Example 2 : In this example we will be plotting multiple triangles with various other parameters.
# importing the modules from bokeh.plotting import figure, output_file, show    # file to save the model output_file("gfg.html")         # instantiating the figure object graph = figure(title = "Bokeh Triangle Graph")    # name of the x-axis graph.xaxis.axis_label = "x-axis"        # name of the y-axis graph.yaxis.axis_label = "y-axis"   # points to be plottedx = [3, 3, 5]y = [3, 1, 3]size = [130, 100, 60]   # color value of the trianglescolor = ["yellow", "red", "purple"]   # fill alpha value of the trianglesfill_alpha = [0.9, 0.7, 0.5]   # plotting the graph graph.triangle(x, y,               size = size,               color = color,               fill_alpha = fill_alpha)         # displaying the model show(graph)
Output :
Data Visualization
Python Bokeh-plotting-figure-class
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
How to catch ArithmeticError Exception in Python?

ArithmeticError Exception is the base class for all errors that occur for numeric calculations. It is the base class for those built-in exceptions like: OverflowError, ZeroDivisionError, FloatingPointError
We can catch the exception in given code as follows
import sys
try:
7/0
except ArithmeticError as e:
print e
print sys.exc_type
print 'This is an example of catching ArithmeticError'
integer division or modulo by zero
<type 'exceptions.ZeroDivisionError'>
This is an example of catching ArithmeticError
How to find distinct values of multiple columns in PySpark ? - GeeksforGeeks

04 Jul, 2021
In this article, we will discuss how to find distinct values of multiple columns in PySpark dataframe.
Let’s create a sample dataframe for demonstration:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of employee datadata = [["1", "Tezas", "Google"],        ["2", "Mohit Rawat", "Rakuten"],        ["3", "rohith", "Geeksforgeeks"],        ["4", "Nancy", "IBM"],        ["1", "Raghav", "Wipro"],        ["4", "Komal", "Amazon"]]  # specify column namescolumns = ['ID', 'NAME', 'Company']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  dataframe.show()
Output:
Method 1: Using distinct() method
The distinct() method is utilized to drop/remove the duplicate elements from the DataFrame.
Syntax: df.distinct(column)
Example 1: Get a distinct Row of all Dataframe.
Python3
dataframe.distinct().show()
Output:
Example 2: Get distinct Value of single Columns.
It can be done by passing a single column name with dataframe.
Python3
dataframe.select('NAME').distinct().show()
Output:
Example 3: Get distinct Value of Multiple Columns.
It can be done by passing multiple column names as a form of a list with dataframe.
Python3
dataframe.select('ID',"NAME").distinct().show()
Method 2: Using dropDuplicates() method.
The dropDuplicates() used to remove rows that have the same values on multiple selected columns.
Syntax: df.dropDuplicates()
Example 1: Get a distinct Row of all Dataframe.
Python3
dataframe.dropDuplicates().show()
Output:
Example 2: Get distinct Value of single Columns.
It can be done by passing a single column name with dataframe.
Python3
dataframe.select("NAME").dropDuplicates().show()
Output:
Example 3: Get distinct Value of multiple Columns.
It can be done by passing multiple column names as a form of a list with dataframe.
Python3
dataframe.dropDuplicates(["NAME","ID"]).select(["ID","NAME"]).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Can we execute a java program without a main method?


Yes, we can execute a java program without a main method by using a static block. 
Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block. Static initialization block is going directly into the stack memory.
class StaticInitializationBlock{
   static{
      System.out.println("class without a main method");
      System.exit(0);
   }
}
In the above example, we can execute a java program without a main method (works until Java 1.6 version). Java 7 and newer versions don’t allow this because JVM checks the presence of the main method before initializing the class.
class without a main method.
Creating a Simple Web Application

This chapter explains how to create a simple application in Symfony framework. As discussed earlier, you know how to create a new project in Symfony.
We can take an example of “student” details. Let’s start by creating a project named “student” using the following command.
symfony new student

After executing the command, an empty project is created.
Symfony is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. Controller plays an important role in the Symfony Framework. All the webpages in an application need to be handled by a controller.
DefaultController class is located at “src/AppBundle/Controller”. You can create your own Controller class there.
Move to the location “src/AppBundle/Controller” and create a new StudentController class.
Following is the basic syntax for StudentController class.
namespace AppBundle\Controller; 
use Symfony\Component\HttpFoundation\Response;  
class StudentController { 
} 

Now, you have created a StudentController. In the next chapter, we will discuss more about the Controller in detail.
Once the Controller has been created, we need to route for a specific page. Routing maps request URI to a specific controller's method.
Following is the basic syntax for routing.
namespace AppBundle\Controller;  
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;  

class StudentController { 
   /** 
      * @Route("/student/home") 
   */ 
   public function homeAction() { 
      return new Response('Student details application!'); 
   } 
}
In the above syntax, @Route(“/student/home”) is the route. It defines the URL pattern for the page.
homeAction() is the action method, where you can build the page and return a Response object.
We will cover routing in detail in the upcoming chapter. Now, request the url “http://localhost:8000/student/home” and it produces the following result.
 Print
 Add Notes
 Bookmark this page
Node.js External HTTP call

Theory of Computation
It is often necessary for a network application to make external HTTP calls. HTTP servers are also often called upon to perform HTTP services for clients making requests. Node provides an easy interface for making external HTTP calls. For example, the following code will fetch the front page of google.com.
var http = require('http');
http.request({
host: 'www.google.com',
method: 'GET',
path: "/"
}, function(response) {
response.setEncoding("utf8");
response.on("readable", function() {
How to add time in minutes in datetime string PHP?

For this, you can use the strtotime() method.
The syntax is as follows −
$anyVariableName= strtotime('anyDateValue + X minute');
You can put the integer value in place of X.
The PHP code is as follows
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$addingFiveMinutes= strtotime('2020-10-30 10:10:20 + 5 minute');
echo date('Y-m-d H:i:s', $addingFiveMinutes);
?>
</body>
</html>
This will produce the following output
2020-10-30 10:15:20
Turn an Array into a Column Vector in MATLAB

04 Jul, 2021
 Conversion of an Array into a Column Vector. This conversion can be done using a(:) operation. A(:) reshapes all elements of A into a single column vector. This has no effect if A is already a column vector.
Example 1 
Matlab
% MATLAB code for Conversion of an array % into a column vectora = [2 4 6 8] % Initializing an array of some elements  % Converting above array into a column % vector using a(:) operationColumn_Vector = a(:)
Output:
Example 2
Matlab
% MATLAB code for Conversion of an % array matrix into a column vector.a = [1 2; 3 4; 5 6] % Initializing an array  % Converting above array matrix into a column % vector matrix using a(:) operationColumn_Vector_matrix = a(:)
Output:
MATLAB
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select and order multiple columns in Pyspark DataFrame ?

06 Jun, 2021
In this article, we will discuss how to select and order multiple columns from a dataframe using pyspark in Python. For this, we are using sort() and orderBy() functions along with select() function.
Select(): This method is used to select the part of dataframe columns and return a copy of that newly selected dataframe.
Syntax: dataframe.select([‘column1′,’column2′,’column n’].show()
sort(): This method is used to sort the data of the dataframe and return a copy of that newly sorted dataframe. This sorts the dataframe in ascending by default.
Syntax: dataframe.sort([‘column1′,’column2′,’column n’], ascending=True).show()
oderBy(): This method is similar to sort which is also used to sort the dataframe.This sorts the dataframe in ascending by default.
Syntax: dataframe.orderBy([‘column1′,’column2′,’column n’], ascending=True).show()
Let’s create a sample dataframe
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  datadata = [["1", "sravan", "vignan"], ["2", "ojaswi", "vvit"],        ["3", "rohith", "vvit"], ["4", "sridevi", "vignan"],        ["1", "sravan", "vignan"], ["5", "gnanesh", "iit"]]  # specify column namescolumns = ['student ID', 'student NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  print("Actual data in dataframe")# show dataframedataframe.show()
Output:
Selecting multiple columns and order by using sort() method
Python3
# show dataframe by sorting the dataframe# based on two columns in ascending# order using sort() functiondataframe.select(['student ID', 'student NAME']                ).sort(['student ID', 'student NAME'],                        ascending=True).show()
Output:
Python3
# show dataframe by sorting the dataframe# based on three columns in desc order# using sort() functiondataframe.select(['student ID', 'student NAME', 'college']                ).sort(['student ID', 'student NAME', 'college'],                       ascending=False).show()
Output:
Selecting multiple columns and order by using orderBy() method
Python3
# show dataframe by sorting the dataframe# based on three columns in desc# order using orderBy() functiondataframe.select(['student ID', 'student NAME', 'college']                ).orderBy(['student ID', 'student NAME', 'college'],                          ascending=False).show()
Output:
Python3
# show dataframe by sorting the dataframe# based on two columns in asc# order using orderBy() functiondataframe.select(['student NAME', 'college']                ).orderBy(['student NAME', 'college'],                          ascending=True).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Random rand() function

17 Dec, 2019
Random#rand() : rand() is a Random class method which generates a random value.
Syntax: Random.rand()
Parameter: Random values
Return: generates a random value.
Example #1 :
# Ruby code for Random.rand() method  # declaring Random valuedate_a = Random.rand()  # new arbitrary random valueputs "Random form : #{date_a}\n\n"
Output :
Random form : 0.19492446216402715


Example #2 :
# Ruby code for Random.rand() method  # declaring Random valuedate_b = Random.rand()  date_a = Random.rand(10)  # new arbitrary random valueputs "Random form : #{date_b}\n\n"  puts "Random form : #{date_a}\n\n"
Output :
Random form : 0.175729980681539

Random form : 1


Ruby Random-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby on Rails Introduction
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | String concat Method
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | Array shift() function
Ruby | Types of Variables
Ruby | Exception handling
How to check an array is multidimensional or not in PHP ?

12 Jul, 2019
Given an array (single-dimensional or multi-dimensional) and the task is to check the given array is multi-dimensional or not. There are few methods to check an array is multi-dimensional or not. The function count() and count_recursive() will give wrong result if the array containing a sub-array which is empty, and the other one is using the rsort() function. This function sorts all the sub-arrays towards the beginning of the parent array and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of the parent array (at index 0) will always be an array. Checking for the element at index 0, we can tell whether the array is multidimensional or not.
Syntax:
rsort( $array )
Parameters: The rsort() function accepts one parameter.
$array: This is the object you want to pass to the function.
Example 1: PHP program to check an array is multidimensional or not using rsort function.
<?php$myarray = array(           // Default key for each will     // start from 0     array("Geeks", "For", "Geeks"),     array("Hello", "World") );   // Function to check array is// multi-dimensional or notfunction is_multi_array( $arr ) {    rsort( $arr );    return isset( $arr[0] ) && is_array( $arr[0] );}  // Display resultvar_dump( is_multi_array( $myarray ) );?>
bool(true)

Example 2: Another PHP program to check an array is multidimensional or not using count function.
<?php// Declare an array$geeks = array(1 => 'a', 2 => 'b', 3 => array("Learn", "Contribute", "Explore"));$gfg = array(1 => 'a', 2 => 'b');  // Function to check array is// multi-dimensional or notfunction is_multi($geeks) {          $rv = array_filter($geeks, 'is_array');          if(count($rv)>0) return true;          return false;}  // Display resultvar_dump(is_multi($geeks));var_dump(is_multi($gfg));?>
bool(true)
bool(false)

Note: Try to avoid use count and count_recursive to check that the array is multi-dimension or not cause you may don’t know to weather the array containing a sub-array or not which is empty.
PHP-array
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Array Reverse Sort Functions for Integer and Strings in Golang?

17 May, 2020
Go language provides inbuilt support implementation of basic constants and run-time reflection to operate sort package. Golang is the ability for functions to run independently of each other. With the help of this function we can easily sort integer and string by importing “sort” package. Basically, this will sort the Integer and Strings in Reverse order.
Syntax:
func Reverse(data Interface) Interface
Return Value: This function returns the value of IntSlice and StringSlice value.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to show the uses of// Integer Reverse Sort Function  package main  import (    "fmt"    "sort")  func main() {      fmt.Println("Example For Integer Reverse Sort")      num := []int{70, 80, 20, 50, 10}      // using the function    sort.Sort(sort.Reverse(sort.IntSlice(num)))    fmt.Println(num)  }
Output:
Example For Integer Reverse Sort
[80 70 50 20 10]

Example 2:
// Golang program to show the uses of// String Reverse Sort Function  package main  import (    "fmt"    "sort")  func main() {      fmt.Println("Example For String Reverse Sort")      str:= []string{"GFG","Rank","India","Amid","Covid19"}      // using the function    sort.Sort(sort.Reverse(sort.StringSlice(str)))    fmt.Println(str)  }
Output:
Example For String Reverse Sort
[Rank India GFG Covid19 Amid]

Golang-Program
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Go Variables
Loops in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Golang | Goroutine vs Thread
How to find the sum of non-missing values in an R data frame column?

To find the sum of non-missing values in an R data frame column, we can simply use sum function and set the na.rm to TRUE. For example, if we have a data frame called df that contains a column say x which has some missing values then the sum of the non-missing values can be found by using the command sum(df$x,na.rm=TRUE).
Consider the below data frame −
 Live Demo
x1<-sample(c(NA,2,3),20,replace=TRUE)
x2<-sample(c(NA,5),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
   x1  x2
1  3   5
2  2   NA
3  3   5
4  NA  5
5  NA  NA
6  3   NA
7  3   5
8  3   NA
9  NA  5
10 3   NA
11 3   NA
12 2   NA
13 2   5
14 2   5
15 3   NA
16 2   NA
17 3   5
18 NA  5
19 3   5
20 3   5
Finding the sum of non-missing values in columns x1 and x2 −
sum(df1$x1,na.rm=TRUE)
[1] 43
sum(df1$x2,na.rm=TRUE)
[1] 55
 Live Demo
y1<-sample(c(NA,rpois(1,2)),20,replace=TRUE)
y2<-sample(c(NA,rpois(2,8)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
   y1  y2
1  NA  NA
2  3   NA
3  3   4
4  3   4
5  NA  6
6  3   NA
7  3   4
8  3   4
9  3   NA
10 3   4
11 NA  6
12 3   6
13 NA  6
14 NA  NA
15 3   NA
16 NA  4
17 3   6
18 3   6
19 NA  NA
20 3   6
Finding the sum of non-missing values in columns y1 and y2 −
sum(df2$y1,na.rm=TRUE)
[1] 39
sum(df2$y2,na.rm=TRUE)
[1] 66
React.js displayName

31 Mar, 2021
The displayName string is used in debugging messages. It’s usually not necessary to set it explicitly because the name of the function or class that describes the component infers it. If you wish to show a different name for debugging purposes or when you build a higher-order component, you may want to set it specifically.
The displayName given by React is a highly recommended feature that greatly aids in unit testing and debugging. It also comes in handy when inspecting a part with React dev tools.
Creating React Application:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example:Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import ReactDOM from 'react-dom';  const child_class = class Myclass {  render() {    return (      <div></div>    )  }}  child_class.displayName = "Kapil";class App extends React.Component {    render() {    return (      <div>        <p>             displayName of child class is:             {child_class.displayName}        </p>      </div>    )  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to do crud operations in ReactJS ?
How to create a multi-page website using React.js ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
Python: Inplace Editing using FileInput

19 Feb, 2020
Python3’s fileinput provides many useful features that can be used to do many things without lots of code. It comes handy in many places but in this article, we’ll use the fileinput to do in-place editing in a text file. Basically we’ll be changing the text in a text file without creating any other file or overheads.
Syntax:
FileInput(filename, inplace=True, backup='.bak')

Note: The backup is extension for the backup file created before editing.
Example 1:Changing only the first line of file
Text file:
# Python code to change only first line of fileimport fileinput  filename = "GFG.txt"  with fileinput.FileInput(filename,                          inplace = True, backup ='.bak') as f:      for line in f:        if f.isfirstline():            print("changing only first line", end ='\n')        else:            print(line, end ='')
Output:
Example 2:Search and replace line with other line in file
Text file:
# python3 code to search and # replace line with other line in fileimport fileinput  filename = "GFG.txt"  with fileinput.FileInput(filename,                         inplace = True, backup ='.bak') as f:          for line in f:        if "search this line and change it\n" == line:            print("changing the matched line with this line",                  end ='\n')        else:            print(line, end ='')
Output:
Example 3:Search text inline and replace that line with another line in the file.
Text file:
# python3 code to search text in # line and replace that line with # other line in fileimport fileinput  filename = "GFG.txt"  with fileinput.FileInput(filename,                         inplace = True, backup ='.bak') as f:    for line in f:        if "searchtext" in line:            print("changing this line with line that contains searched text",                  end ='\n')        else:            print(line, end ='')
Output:
Example 4:Search text and replace that text in file.
Text file:
# python code to search# text and replace that text# in file  import fileinput  filename = "GFG.txt"  with fileinput.FileInput(filename,                          inplace = True, backup ='.bak') as f:          for line in f:        if "replace text" in line:            print(line.replace("replace text",                               "changed text"), end ='')        else:            print(line, end ='')
Output:
python-file-handling
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.