code-rag-bench/online-tutorials huggingface dataset:
Max and Min Products | Practice | GeeksforGeeks

Given a set, we need to find the maximum and minimum possible product among all subsets of the set.

Example 1:
Input : 
arr[] = {1, 2, 3};
Output : 
Maximum product = 6
Minimum product = 1
Explanation :
Maximum product is obtained by multiplying
2, 3
Minimum product is obtained by multiplying
1
 
Example 2:
Input :
arr[] = {4, -2, 5};
Output : 
Maximum product = 20
Minimum product = -40
Explanation :
Maximum product is obtained by multiplying
4 5
Minimum product is obtained by multiplying
4, -2, 5
 
Example 3:
Input :
arr[] = {-4, -2, 3, 7, 5, 0, 1};
Output : 
Maximum product = 840
Minimum product = -420
Explanation :
Maximum product is obtained by multiplying
-4, -2, 3, 7, 5
Minimum product is obtained by multiplying
-4, 3, 7


Your Task:  
You don't need to read input or print anything. Your task is to complete the function getMaxandMinProduct() which takes the array arr[] and its size N as inputs and returns the maximum product and minimum subset product in an vector/array/list of size 2.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 20
-9 ≤ A[i] ≤ 9
0
Debarshi Maitra1 year ago
Debarshi Maitra
Greedy Solution : https://ide.geeksforgeeks.o...Time Complexity : O(N)Auxiliary Space : O(1)
0
Mahima Mahendru2 years ago
Mahima Mahendru
hard work paid off!!https://ide.geeksforgeeks.o...
0
Sanjib Giri3 years ago
Sanjib Giri
Another approach to Solution
https://ide.geeksforgeeks.o...
0
Sanjib Giri
This comment was deleted.
0
Gyan5 years ago
Gyan
Can this input array contain repeating digits and zeros?
0
Siddharth Agarwal5 years ago
Siddharth Agarwal
Wrong !! The first test case where your code failed:
Input:41 2 3 4
Its Correct output is:24 1
And Your Output is:24 24But my code is generating 24 1Here's the link of my code:http://code.geeksforgeeks.o...What should I do?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
\iff - Tex Command

\iff - Used to draw if and only if symbol.
{ \iff }
\iff command draws if and only if symbol.

\iff

⟺



\iff

⟺


\iff

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Create Inverted Navbar in Bootstrap

To create an inverted navbar with a black background and with white text, simply add the .navbar-inverse class to the .navbar class.
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
      <script src="/scripts/jquery.min.js"></script>
      <script src="/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class = "navbar navbar-inverse" role = "navigation">
         <div class = "navbar-header">
            <a class = "navbar-brand" href = "#">TutorialsPoint</a>
            <div>
               <div>
                  <ul class = "nav navbar-nav">
                     <li class = "active"><a href = "#">iOS</a></li>
                     <li><a href = "#">SVN</a></li>
                     <li class = "dropdown">
                        <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown">
                           Java
                           <b class = "caret"></b>
                        </a>
                        <ul class = "dropdown-menu">
                           <li><a href = "#">jmeter</a></li>
                           <li><a href = "#">EJB</a></li>
                           <li><a href = "#">Jasper Report</a></li>
                        </ul>
                     </li>
                  </ul>
               </div>
         </nav>
   </body>
</html>
How to compare pointers in C/C++?

We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can’t be multiplied or divided.
 Live Demo
#include <stdio.h>
int main() {
   int *p2;
   int *p1;
   p2 = (int *)300;
   p1 = (int *)200;
   if(p1 > p2) {
      printf("P1 is greater than p2");
   } else {
      printf("P2 is greater than p1");
   }
   return(0);
}
P2 is greater than p1
#include <iostream>
using namespace std;
int main() {
   int *p2;
   int *p1;
   p2 = (int *)300;
   p1 = (int *)200;
   if(p1>p2) {
      cout<<"P1 is greater than p2";
   } else {
      cout<<"P2 is greater than p1";
   }
   return(0);
}
P2 is greater than p1
Some Key points about pointer comparison −
p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null.
p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null.
p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null.
p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null.
If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified.
If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified.
the result is unspecified, if two pointers point to non-static data members of the same object with different access control.
the result is unspecified, if two pointers point to non-static data members of the same object with different access control.
Matplotlib - Anaconda distribution

Anaconda is a free and open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing. The distribution makes package management and deployment simple and easy. Matplotlib and lots of other useful (data) science tools form part of the distribution. Package versions are managed by the package management system Conda. The advantage of Anaconda is that you have access to over 720 packages that can easily be installed with Anaconda's Conda, a package, dependency, and environment manager.
Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available −
https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86.exe
https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86_64.exe
Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python.
For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page −
https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86.sh
https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh
Now, run the following command from the Linux terminal −
$ bash Anaconda3-5.0.1-Linux-x86_64.sh

Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython.

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to make a text bold and italic in JavaFX?

You can set the desired font to the text node in JavaFX using the setFont() method. This method accepts an object of the class javafx.scene.text.Font.
The Font class represents the fonts in JavaFX, this class provides several variants of a method named font() as shown below −
font(double size)
font(String family)
font(String family, double size)
font(String family, FontPosture posture, double size)
font(String family, FontWeight weight, double size)
font(String family, FontWeight weight, FontPosture posture, double size)
Where,
size (double) represents the size of the font.
size (double) represents the size of the font.
family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method.
family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method.
weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN).
weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN).
posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC).
posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC).
To make a text bold create a font bypassing FontWeight.BOLD or, FontWeight.EXTRA_BOLD as the value of the parameter weight and, to make a text italic pass FontPosture.ITALIC as the value of the parameter posture.
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class Bold_Italic extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //Setting the font bold and italic
      Font font = Font.font("Verdana", FontWeight.BOLD, FontPosture.ITALIC, 35);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.DARKCYAN);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Bold And Italic");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
groupdel command in Linux with examples - GeeksforGeeks

20 May, 2019
groupdel command is used to delete a existing group. It will delete all entry that refers to the group, modifies the system account files, and it is handled by superuser or root user.
Syntax:
groupdel [options] GROUP
Files:
/etc/group : It contains the account information of the Group.
/etc/gshadow : It contains the secure group account information.
Exit values: This command exits with the following values.
0: Success
2: Invalid Command Syntax.
6: Specified group doesn’t exist.
8: Can’t remove users primary group.
10: Can’t update group file.
Options:
-f –force: It used to delete a group even if it is the primary group of a user.
-h –help: It displays the help message and exit.
-R –root: It apply the changes in the CHROOT_DIR directory. Also, it uses the configuration files from the CHROOT_DIR directory.My Personal Notes
arrow_drop_upSave
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
Thread functions in C/C++
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
Linux Admin - MySQL Setup On CentOS 7

As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository.
One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability.
So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me?
Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB.
The biggest reasons for favoring Maria on CentOS are −
Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria.
Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria.
CentOS is designed to run with Maria. Hence, Maria will offer better stability.
CentOS is designed to run with Maria. Hence, Maria will offer better stability.
Maria is officially supported for CentOS.
Maria is officially supported for CentOS.
We will want to download and install the MySQL repository from −
http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
Step 1 − Download the Repository.
The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget −
[root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm
   --2017-02-26 03:18:36--  http://repo.mysql.com/mysql-community-release-el75.noarch.rpm
   Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130

Step 2 − Install MySQL From YUM.
We can now use the yum package manager to install MySQL −
[root@centos]# yum -y install mysql-server

Step 3 − Start and Enable the MySQL Daemon Service.
[root@centos]# systemctl start mysql 
[root@centos]# systemctl enable  mysql

Step 4 − Make sure our MySQL service is up and running.
[root@centos]# netstat -antup | grep 3306 
tcp6       0       0 :::3306       :::*       LISTEN       6572/mysqld
[root@centos]#

Note − We will not allow any firewall rules through. It's common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software.

    57 Lectures 
     7.5 hours 

 Mamta Tripathi

    25 Lectures 
     3 hours 

 Lets Kode It

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    58 Lectures 
     2.5 hours 

 Frahaan Hussain

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    23 Lectures 
     5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Autorun a Python script on windows startup - GeeksforGeeks

14 Sep, 2021
Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process –
Step #1: Adding script to windows Startup folder After the windows boots up it runs (equivalent to double-clicking) all the application present in its startup directory. 
Address: 
C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\  
By default the AppData folder under the current_user is hidden so enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Also the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing.   Step #2: Adding script to windows Registry This process can be risky if not done properly, it involves editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry contains the list of programs that must run once the user Login. just like few application which pops up when windows starts because the cause change in registry and add their application path to it.
Registry Path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
Below is the Python code : 
Python3
# Python code to add current script to the registry # module to edit the windows registryimport winreg as regimport os             def AddToRegistry():     # in python __file__ is the instant of    # file path where it was executed    # so if it was executed from desktop,    # then __file__ will be    # c:\users\current_user\desktop    pth = os.path.dirname(os.path.realpath(__file__))         # name of the python file with extension    s_name="mYscript.py"             # joins the file name to end of path address    address=os.join(pth,s_name)         # key we want to change is HKEY_CURRENT_USER    # key value is Software\Microsoft\Windows\CurrentVersion\Run    key = HKEY_CURRENT_USER    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"         # open the key to make changes to    open = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)         # modify the opened key    reg.SetValueEx(open,"any_name",0,reg.REG_SZ,address)         # now close the opened key    reg.CloseKey(open) # Driver Codeif __name__=="__main__":    AddToRegistry()
Note: Further codes can be added to this script for the task to be performed at every startup and the script must be run as Administrator for the first time. 
sagartomar9927
python-utility
Python
TechTips
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
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
How to Run a Python Script using Docker?
Running Python script on GPU.
Top Programming Languages for Android App Development
How to Strip Outputs and Execute Interactive Code in a Python Script | by Khuyen Tran | Towards Data Science

Have you ever seen a tutorial with an interactive Python code like this:
...and wished to get only the code that can be executed like below?
It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. Is there a way that you can get the clean inputs like above in one line of code?
That is why I created a package called strip-interactive. In this article, I will show you how to use this package to do exactly that.
To install strip-interactive, type:
pip install strip-interactive
Let’s use strip-interactive to extract clean inputs from interactive Python code:
Output:
import numpy as npprint(np.array([1,2,3]))print(np.array([4,5,6]))
Cool! Now, these clean inputs are ready to be executed.
To execute the inputs we have just got from get_clean_code , use theexec method:
[1 2 3][4 5 6]
If you prefer to execute interactive Python code in one step, use therun_interactive method:
Output:
[1 2 3][4 5 6]
Awesome! Using therun_interactive method gives us the same outputs as using theget_clean_code and the exec methods.
I believe yes, but it is better to test it out.
Outputs:
[1 2 3]
Great, it works!
Note that there will be no outputs if you use run_interactive for the code like below:
So make sure to addprint to np.array([1,2,3]) to see the outputs:
Output:
[1 2 3]
Congratulations! You have just learned how to execute interactive Python code in your Python script in one line of code using strip-interactive. This will come in handy when you want to quickly try out the interactive Python code in an article or documentation.
The code of this article could be found here. If you see how this package can be improved, feel free to contribute or submit an issue here.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
Plotting regression and residual plot in Matplotlib

To establish a simple relationship between the observations of a given joint distribution of a variable, we can create the plot for the regression model using Seaborn.
To fit the dataset using the regression model, we have to first import the necessary libraries in Python.
We will create plots for each regression model, (a) Linear Regression, (b) Polynomial Regression, and (c) Logistic Regression.
In this example, we will use the wine
quality
dataset which can be accessed from here, https://archive.ics.uci.edu/ml/datasets/wine+quality
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import pearsonr
sns.set(style="dark", color_codes=True)

#import the dataset
wine_quality = pd.read_csv('winequality-red.csv', delimiter=';')

#Plotting Linear Regression
R, p = pearsonr(wine_quality['fixed acidity'], wine_quality.pH)
g1 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, truncate=True, ci=99,
marker='D', scatter_kws={'color': 'r'});
textstr = '$\mathrm{pearson}\hspace{0.5}\mathrm{R}^2=%.2f$\n$\mathrm{pval}=%.2e$ '% (R**2, p)
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
g1.text(0.55, 0.95, textstr, fontsize=14, va='top', bbox=props)
plt.title('1. Linear Regression', size=15, color='b', weight='bold')

#Let us Plot the Polynomial Regression plot for the wine dataset
g2 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, order=2, ci=None,
   marker='s', scatter_kws={'color': 'skyblue'},
   line_kws={'color': 'red'});
plt.title('2. Polynomial Regression', size=15, color='r', weight='bold')

#Now plotting the Logistic Regression
wine_quality['Q'] = wine_quality['quality'].map({'Low': 0, 'Med': 0, 'High':1})
g2 = sns.regplot(x='fixed acidity', y='Q', logistic=True,
   n_boot=750, y_jitter=.03, data=wine_quality,
   line_kws={'color': 'r'})
plt.show();

#Now plot the residual plot
g3 = sns.residplot(x='fixed acidity', y='density', order=2,
   data=wine_quality, scatter_kws={'color': 'r',
   'alpha': 0.5});
plt.show();
Running the above code will generate the output as,
Count the NaN values in one or more columns in Pandas DataFrame - GeeksforGeeks

17 Aug, 2020
Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value.
Consider the following DataFrame.
# importing the modulesimport numpy as npimport pandas as pd   # creating the DataFramedictionary = {'Names': ['Simon', 'Josh', 'Amen',                         'Habby', 'Jonathan', 'Nick', 'Jake'],              'Capitals': ['VIENNA', np.nan, 'BRASILIA',                            np.nan, 'PARIS', 'DELHI', 'BERLIN'],              'Countries': ['AUSTRIA', 'BELGIUM', 'BRAZIL',                             np.nan, np.nan, 'INDIA', np.nan]}table = pd.DataFrame(dictionary, columns = ['Names',                                            'Capitals',                                            'Countries'])  # displaying the DataFramedisplay(table)
Output :
Example 1 : Counting the NaN values in a single column.
print("Number of null values in column 1 : " +        str(table.iloc[:, 1].isnull().sum()))print("Number of null values in column 2 : " +        str(table.iloc[:, 2].isnull().sum()))
Output :
Number of null values in column 1 : 2
Number of null values in column 2 : 3

Example 2 : Counting the NaN values in a single row.
print("Number of null values in row 0 : " +        str(table.iloc[0, ].isnull().sum()))print("Number of null values in row 1 : " +        str(table.iloc[1, ].isnull().sum()))print("Number of null values in row 3 : " +        str(table.iloc[3, ].isnull().sum()))
Output :
Number of null values in row 0 : 0
Number of null values in row 1 : 1
Number of null values in row 3 : 2

Example 3 : Counting the total NaN values in the DataFrame.
print("Total Number of null values in the DataFrame : " +        str(table.isnull().sum().sum()))
Output :
Total Number of null values in the DataFrame : 5

Example 4 : Counting the NaN values in all the columns.
display(table.isnull().sum())
Output :
Python pandas-dataFrame
Python-pandas
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?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Get Absolute path of a file in Java

The method java.io.File.getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
      System.out.println("The absolute path name is: " + file.getAbsolutePath());
   }
}
The output of the above program is as follows −
The absolute path name is:/C:/jdk11.0.2/demo1.java
Now let us understand the above program.
The absolute pathname of the file is obtained using the method java.io.File.getAbsolutePath() in the form of a string and is printed. A code snippet that demonstrates this is given as follows −
File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("The absolute path name is: " + file.getAbsolutePath());
Can we declare interface members as private or protected in java8?

Interface in Java is similar to a class but, it contains only abstract methods and fields which are final and static.
Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods in it.
If the members of the interface are private you cannot provide implementation to the methods or, cannot access the fields of it in the implementing class.
Therefore, the members of an interface cannot be private. If you try to declare the members of an interface private, a compile-time error is generated saying “modifier private not allowed here”.
In the following Java example, we are trying to declare the field and method of an interface private.
public interface MyInterface {
   private static final int num = 10;
   private abstract void demo();
}
On compiling, the above program generates the following error.
MyInterface.java:2: error: modifier private not allowed here
   private static final int num = 10;
                        ^
MyInterface.java:3: error: modifier private not allowed here
   private abstract void demo();
                             ^
2 errors
In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it.
Therefore, the members of an interface cannot be protected. If you try to declare the members of an interface protected, a compile-time error is generated saying “modifier protected not allowed here”.
In the following Java example, we are trying to declare the field and method of an interface protected.
public interface MyInterface{
   protected static final int num = 10;
   protected abstract void demo();
}
On compiling, the above program generates the following error.
MyInterface.java:2: error: modifier protected not allowed here
protected static final int num = 10;
^
MyInterface.java:3: error: modifier protected not allowed here
protected abstract void demo();
^
2 errors
GATE | GATE CS 1997 | Question 14

19 Nov, 2018
The correct matching for the following pairs is
(A) DMA I/O                    (1) High speed RAM
(B) Cache                      (2) Disk
(C) Interrupt I/O              (3) Printer
(D) Condition Code Register    (4) ALU

Codes:
    A   B   C   D 
a   4   3   1   2
b   2   1   3   4
c   4   3   2   1
d   2   3   4   1

(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Math pow( ) Method

09 Feb, 2022
Below is the example of the Math pow() Method.
Example:<script type="text/javascript">    document.write(Math.pow(3, 4));</script>
<script type="text/javascript">    document.write(Math.pow(3, 4));</script>
Output:81
81
The Math.pow() method is used to power of a number i.e., the value of number raised to some exponent. Since the Math.pow() is a static method of Math and therefore it is always used as Math.pow() and not as a method of an object created of Math class.
Syntax:
Math.pow(base, exponent)
Parameters: This method accepts two parameters as mentioned above and described below:
base:It is the base number which is to be raised.
exponent:It is the value used to raise the base.
Return Value: The Math.pow() method returns a number representing the given base raised to the power of the given exponent.
More codes for the above method are as follows:
Program 1: When both base and exponent are passed as positive numbers in parameters:
<script type="text/javascript">    document.write(Math.pow(9, 3));</script>
Output:
729
Program 2: When the base value is negative and the exponent is positive:
<script type="text/javascript">    document.write(Math.pow(-9, 3));</script>
Output:
-729
Program 3: When the base value is positive and the exponent is negative:
<script type="text/javascript">    document.write(Math.pow(9, -3));</script>
Output:
0.0013717421124828531
Program 4: When the base value is negative and the exponent has decimal point:
<script type="text/javascript">    document.write(Math.pow(-9, 0.5));</script>
Output:
NaN
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
shubham_singh
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
seaborn.lineplot() method in Python

17 Jul, 2020
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well.
Draw a line plot with the possibility of several semantic groupings. The relationship between x and y can be shown for different subsets of the data using the hue, size, and style parameters. These parameters control what visual semantics are used to identify the different subsets. It is possible to show up to three dimensions independently by using all three semantic types, but this style of plot can be hard to interpret and is often ineffective. Using redundant semantics (i.e. both hue and style for the same variable) can be helpful for making graphics more accessible.
Syntax : sns.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs,)
Parameters:
x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data.
hue: Grouping variable that will produce lines with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case.
style: Grouping variable that will produce lines with different dashes and/or markers. Can have a numeric dtype but will always be treated as categorical.
data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation. 
markers: Object determining how to draw the markers for different levels of the style variable.
legend: How to draw the legend. If “brief”, numeric “hue“ and “size“ variables will be represented with a sample of evenly spaced values.
Below is the implementation of above method with some examples :
Example 1:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("iris")  # draw lineplotsns.lineplot(x="sepal_length", y="sepal_width", data=data)plt.show()
Output :
Example 2 :
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("tips")  # draw lineplot# hue by sex# style to huesns.lineplot(x="total_bill", y="size",             hue="sex", style="sex",             data=data)  plt.show()
Output :
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
What is the AddSingleton vs AddScoped vs Add Transient C# Asp.net Core?

There are three ways by which dependencies can be registered in Startup.cs. i.e.
AddSingleton, AddScoped and AddTransient.
When we register a type as singleton, only one instance is available throughout the
application and for every request.
It is similar to having a static object.
The instance is created for the first request and the same is available throughout the
application and for each subsequent requests.
public void ConfigureServices(IServiceCollection services){
   services.AddSingleton<ILog,Logger>()
}
When we register a type as Scoped, one instance is available throughout the
application per request. When a new request comes in,
the new instance is created. Add scoped specifies that a single object is available per
request.
public void ConfigureServices(IServiceCollection services){
   services.AddScoped<ILog,Logger>()
}
When we register a type as Transient, every time a new instance is created. Transient
creates new instance for every service/ controller as well as for every request and
every user.
public void ConfigureServices(IServiceCollection services){
   services.AddTransient<ILog,Logger>()
}
Python – Consecutive Row summation in Matrix

29 Dec, 2019
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + abs() + zip() + list comprehensionThis particular problem can also be solved using the combination of the above 4 operations. Here zip function does the dual task of pairing the list and also pairing the like indices for sum, to be computed by abs function and then sum is found using sum function, all bounded by list comprehension.
# Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + abs() + zip() + list comprehension  # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]  # printing original list print("The original list : " + str(test_list))  # using sum() + abs() + zip() + list comprehension# Consecutive Row summation in Matrixres = [sum(abs(i + j) for i, j in zip(*ele)) for ele in zip(test_list, test_list[1:])]  # print resultprint("The row summation sublist : " + str(res))
The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]
The row summation sublist : [30, 30, 32]

 
Method #2 : Using sum() + map() + abs + zip()This task can also be achieved using the combination of above functions, the addition is map function that performs the task of binding of abs operation to the whole list.
# Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + map() + abs + zip()  # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]  # printing original list print("The original list : " + str(test_list))  # using sum() + map() + abs + zip()# Consecutive Row summation in Matrixres = [sum(map(abs, (i + j for i, j in zip(x, y)))) for x, y in zip(test_list, test_list[1:])]  # print resultprint("The row summation sublist : " + str(res))
The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]
The row summation sublist : [30, 30, 32]

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | Remove spaces from dictionary keys

18 Dec, 2018
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key.
Let’s see how to remove spaces from dictionary keys in Python.
Method #1:Using translate() function here we visit each key one by one and remove space with the none. Here translate function takes parameter 32, none where 32 is ASCII value of space ‘ ‘ and replaces it with none.
# Python program to remove space from keys  # creating a dictionary of type string  Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS',                'P 0 3 ': 'Soft Computing'}  # removing spaces from keys# storing them in sam dictionaryProduct_list = { x.translate({32:None}) : y                  for x, y in Product_list.items()}  # printing new dictionaryprint (" New dictionary : ", Product_list)
New dictionary :  {'P01': 'DBMS', 'P03': 'Soft Computing', 'P02': 'OS'}

 Method #2:Using replace() function. In this method, we visit each key in dictionary one by one and replace all spaces in key with no space. This function takes as argument space and second non-space.
# Python program to remove space from keys  # creating a dictionary of type string  Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS',                'P 0 3 ': 'Soft Computing'};  # removing spaces from keys# storing them in sam dictionaryProduct_list = {x.replace(' ', ''): v      for x, v in Product_list.items()}  # printing new dictionaryprint (" New dictionary : ", Product_list)
New dictionary :  {'P03': 'Soft Computing', 'P01': 'DBMS', 'P02': 'OS'}

Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
How can we add a FOREIGN KEY constraint to the field of an existing MySQL table?

We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.
ALTER TABLE table_name ADD FOREIGN KEY (colum_name) REFERENCES table having Primary Key(column_name);
Suppose we want to add a FOREIGN KEY constraint on the table ‘Orders1’ referencing to the table ‘Customer’ which have column ‘Cust_Id’ as the Primary Key. It can be done with the help of the following query −
mysql> Alter table orders1 add FOREIGN KEY(Cust_id) REFERENCES Customer(Cust_id);
Query OK, 0 rows affected (0.21 sec)
Records: 0  Duplicates: 0  Warnings: 0  

mysql> Describe ORDERS1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.05 sec)
PHP | compact() Function - GeeksforGeeks

29 Nov, 2019
The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.
Syntax:
array compact("variable 1", "variable 2"...)

Parameters: This function accepts a variable number of arguments separated by comma operator (‘,’). These arguments are of string data type and specify the name of variables which we want to use to create the array. We can also pass an array as an argument to this function, in that case, all of the elements in the array passed as a parameter will be added to the output array.
Return Value: This function returns an array with all the variables added to it.
Note: Any string passed as a parameter which does not match with a valid variable name will be skipped and will not be added to the array.
Examples:
Input : $AS="ASSAM", $OR="ORISSA", $KR="KERELA"
        compact("AS", "OR", "KR");
Output :
Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERELA
)

Below program illustrate the working of compact() function in PHP:
Example-1:
<?php// PHP program to illustrate compact() // Function      $AS = "ASSAM";$OR = "ORISSA";$KR = "KERELA";      $stats = compact("AS", "OR", "KR");  print_r($states);  ?>
Output:
Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERELA
)

Example-2:
<?php// PHP program to illustrate compact() // function when an array is passed as// a parameter  $username = "max";$password = "many";$age = "31";  $NAME = array("username", "password");  $result = compact($NAME, "age");      print_r($result);  ?>
Output:
Array
(
    [username] => max
    [password] => many
    [age] => 31
)

Reference:http://php.net/manual/en/function.compact.php
Akanksha_Rai
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Apache Commons IO - FileUtils

Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
Following is the declaration for org.apache.commons.io.FileUtils Class −
public class FileUtils
   extends Object
The features of FileUtils are stated below −
Methods to write to a file.
Methods to read from a file.
Methods to make a directory including parent directories.
Methods to copy files and directories.
Methods to delete files and directories.
Methods to convert to and from a URL.
Methods to list files and directories by filter and extension.
Methods to compare file content.
Methods to file last changed date.
Methods to calculating a checksum.
Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;

public class IOTester {
   public static void main(String[] args) {
      try {
         //Using FileUtils
         usingFileUtils();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }

   public static void usingFileUtils() throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");

      //get the temp directory
      File tmpDir = FileUtils.getTempDirectory();

      System.out.println(tmpDir.getName());

      //copy file to temp directory
      FileUtils.copyFileToDirectory(file, tmpDir);

      //create a new file
      File newTempFile = FileUtils.getFile(tmpDir, file.getName());

      //get the content
      String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());

      //print the content
      System.out.println(data);
   }
}
It will print the following result.
Temp
Welcome to TutorialsPoint. Simply Easy Learning.

 Print
 Add Notes
 Bookmark this page
Laravel - Hashing

Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner.
The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords −
The following lines of code explain the functionality and usage of the passwordController −
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller

class passwordController extends Controller{
   /**
      * Updating the password for the user.
      *
      * @param Request $request
      * @return Response
   */
   
   public function update(Request $request) {
      // Validate the new password length...
      $request->user()->fill([
         'password' => Hash::make($request->newPassword) // Hashing passwords
      ])->save();
   }
}
The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel.
You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below −
if (Hash::check('plain-text', $hashedPassword)) {
   // The passwords match...
}

Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page