code-rag-bench/online-tutorials huggingface dataset:
Cut rope to maximise product | Practice | GeeksforGeeks

Given a rope of length N meters, cut the rope into several ropes of varying lengths in a way that maximizes product of lengths of all resulting ropes. You must make at least one cut.
Example 1:
Input:
N = 2
Output: 1
Explanation: Since 1 cut is mandatory.
Maximum obtainable product is 1*1 = 1.

Example 2:
Input:
N = 5
Output: 6
Explanation: 
Maximum obtainable product is 2*3 = 6.

Your Task:
You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes n as input parameter and returns the maximum product.

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

Constraints:
1 ≤ N ≤ 100
 
0
nihalbaranwal
This comment was deleted.
0
abhishekguptaaa3 months ago
 long long dp[102];      long long solve( long long  n)  {      if(dp[n]!=-1)      {          return dp[n];      }            long long  mx=0;            for(long long i=1;i<n;i++)      {          mx=max(mx, max(1LL*i*(n-i), 1LL*i*dp[n-i]) );      }            return dp[n]=mx;  } 
   long long maxProduct(int n) {            dp[n+1];            memset(dp,-1,sizeof(dp));                 dp[0]=0;      dp[1]=0;      dp[2]=1;      dp[3]=2;      dp[4]=4;            if(n<=4)      {          return dp[n];      }      else      {          for(int i=5;i<n+1;i++)          {              solve(1LL*i);          }                              return dp[n];      }              }};
0
abc123programming6 months ago
JAVA SOLUTION
 
 
 
class Solution {   long maxProduct(int n) {      long[] dp= new long[n+1];      for(int i=0;i<dp.length;i++){          dp[i]= -1;      }            long ans= maxP(n,dp);      return ans;   }   static long maxP(int n,long[] dp){                     if(n<=1){           return 0;       }        if(n==2){           return 1;       }       if(n==3){           return 2;       }              dp[0]=dp[1]=0;       dp[2]=1;                          if(dp[n] != -1){           return dp[n];       }                     long max=0;                 for(int i=1;i<n;i++){           max=Math.max(max, Math.max( i*(n-i), i*maxP((n-i),dp)));       }       return dp[n]=max;   }}
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.
Python - Sentiment Analysis using Affin - GeeksforGeeks

18 Apr, 2022
Afinn is the simplest yet popular lexicons used for sentiment analysis developed by Finn Årup Nielsen. It contains 3300+ words with a polarity score associated with each word. In python, there is an in-built function for this lexicon.
Let’s see its syntax-
Installing the library:
python3
# codeprint("GFG")pip install afinn /#installing in windowspip3 install afinn /#installing in linux!pip install afinn#installing in jupyter
Code: Python code for sentiment analysis using Affin
python3
#importing necessary librariesfrom afinn import Afinnimport pandas as pd #instantiate afinnafn = Afinn() #creating list sentencesnews_df = ['les gens pensent aux chiens','i hate flowers',         'hes kind and smart','we are kind to good people']          # compute scores (polarity) and labelsscores = [afn.score(article) for article in news_df]sentiment = ['positive' if score > 0                          else 'negative' if score < 0                              else 'neutral'                                  for score in scores]     # dataframe creationdf = pd.DataFrame()df['topic'] =  news_dfdf['scores'] = scoresdf['sentiments'] = sentimentprint(df)
Output:
topic  scores sentiments
0  les gens pensent aux chiens     0.0    neutral
1               i hate flowers    -3.0   negative
2           hes kind and smart     3.0   positive
3   we are kind to good people     5.0   positive
The best part of this library package is that one can find score sentiment of different languages as well.
python3
afn = Afinn(language = 'da') #assigning 'da' danish to the object variable.afn.score('du er den mest modbydelige tæve')
Output:
-5.0
Thus, Afinn can we used easily to get scores immediately.
varshagumber28
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
HTML Object tag - GeeksforGeeks

17 Mar, 2022
The <object> tag is an HTML tag and used to display multimedia like audios, videos, images, PDFs, and Flash in web pages. It can also be used for displaying another webpage inside the HTML page. The <param> tag is also used along with this tag to define various parameters. Any text that is written within <object> and </object> tags are considered as an alternative text that appears when the data specified is not supported by the browser. This tag supports all Global and Event attributes of HTML. Example:  
HTML
<!DOCTYPE html> <html>     <body>        <h1>HTML Object Tag</h1>        <!--HTML object tag starts here-->        <object data="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png"width="550px" height="150px">GeeksforGeeks        <!--HTML object tag ends here-->        </object>    </body> </html>                   
Output:  
The <object> tag has the following attributes:  
Supported Browsers:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
Akanksha_Rai
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Promoted Fields in Golang Structure - GeeksforGeeks

13 Aug, 2019
In Go structure, promoted fields are just like anonymous fields, the type of the field is the name of the field. We use this concept in the nested structure where a structure is a field in another structure, simply by just adding the name of the structure into another structure and it behaves like the Anonymous Field to the nested structure. And the fields of that structure (other than nested structure) are the part of the nested structure, such type of fields are known as Promoted fields. If the anonymous structure or nested structure and parent structure contains a field that has the same name, then that field doesn’t promote, only different name fields get promoted to the structure.
Syntax:
type x struct{
// Fields
}

type y struct{
// Fields of y structure
x
}

Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate the// concept of the promoted fieldspackage main  import "fmt"  // Structuretype details struct {      // Fields of the    // details structure    name   string    age    int    gender string}  // Nested structuretype student struct {    branch string    year   int    details}  func main() {      // Initializing the fields of    // the student structure    values := student{        branch: "CSE",        year:   2010,        details: details{                      name:   "Sumit",            age:    28,            gender: "Male",        },    }      // Promoted fields of the student structure    fmt.Println("Name: ", values.name)    fmt.Println("Age: ", values.age)    fmt.Println("Gender: ", values.gender)      // Normal fields of    // the student structure    fmt.Println("Year: ", values.year)    fmt.Println("Branch : ", values.branch)}
Output:
Name:  Sumit
Age:  28
Gender:  Male
Year:  2010
Branch :  CSE

Explanation: In the above example, we have two structures named as details and student. Where details structure is the normal structure and student structure is the nested structure which contains the details structure as fields in it just like anonymous fields. Now, the fields of the details structure, i.e, name, age, and gender are promoted to the student structure and known as promoted fields. Now, you can directly access them with the help of the student structure like values.name, values.age, and values.gender.
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Golang Maps
Slices in Golang
How to Trim a String in Golang?
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
Interfaces in Golang
Pointers in Golang
strings.Join() Function in Golang With Examples
Time Durations in Golang
Data Types in Go
Reset the primary key to 1 after deleting all the data in MySQL?

To reset the primary key to 1 after deleting the data, use the following syntax
alter table yourTableName AUTO_INCREMENT=1;
truncate table yourTableName;
After doing the above two steps, you will get the primary key beginning from 1.
To understand the above concept, let us create a table. The query to create a table is as follows
mysql> create table resettingPrimaryKeyDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from resettingPrimaryKeyDemo;
The following is the output
+--------+
| UserId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
+--------+
4 rows in set (0.00 sec)
Here is the query to reset the primary key to 1
mysql> alter table resettingPrimaryKeyDemo AUTO_INCREMENT=1;
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> truncate table resettingPrimaryKeyDemo;
Query OK, 0 rows affected (0.89 sec)
Check the records from the table. The query is as follows −
mysql> select *from resettingPrimaryKeyDemo;
Empty set (0.00 sec)
Insert some records from the table using insert command. The query is as follows −
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.12 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)
Now check the table primary key beginning from 1. The query is as follows −
mysql> select *from resettingPrimaryKeyDemo;
The following is the output
+--------+
| UserId |
+--------+
|      1 |
|      2 |
|      3 |
+--------+
3 rows in set (0.00 sec)
SQLite - VACUUM

VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure.
VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file.
VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters.
Following is a simple syntax to issue a VACUUM command for the whole database from command prompt −
$sqlite3 database_name "VACUUM;"

You can run VACUUM from SQLite prompt as well as follows −
sqlite> VACUUM;
You can also run VACUUM on a particular table as follows −
sqlite> VACUUM table_name;
SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small.
You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt −
sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum
sqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum
sqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum
You can run the following command from the command prompt to check the auto-vacuum setting −
$sqlite3 database_name "PRAGMA auto_vacuum;"


    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Google Charts - Basic Column Chart

Following is an example of a basic column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used BarChart class to show area based chart.
//column chart
var chart = new google.visualization.ColumnChart(document.getElementById('container'));

googlecharts_column_basic.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Year', 'Asia'],
               ['2012',  900],
               ['2013',  1000],
               ['2014',  1170],
               ['2015',  1250],
               ['2016',  1530]
            ]);

            var options = {title: 'Population (in millions)'}; 

            // Instantiate and draw the chart.
            var chart = new google.visualization.ColumnChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
How do I print and have user input in a text box in Tkinter?

We can use the Tkinter text widget to insert text, display information, and get the output from the text widget. To get the user input in a text widget, we've to use the get() method. Let's take an example to see how it works.
# Import the required library
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win=Tk()

# Set the geometry
win.geometry("700x350")

def get_input():
   label.config(text=""+text.get(1.0, "end-1c"))

# Add a text widget
text=Text(win, width=80, height=15)
text.insert(END, "")
text.pack()

# Create a button to get the text input
b=ttk.Button(win, text="Print", command=get_input)
b.pack()

# Create a Label widget
label=Label(win, text="", font=('Calibri 15'))
label.pack()

win.mainloop()
Running the above code will display a window containing a text widget. Type something in the text widget and click the "Print" button to display the output.
Adjusting Text background transparency in Matplotlib

To adjust text background transparency in matplotlib, we can change the alpha value in the dictionary of bbox with facecolor='red' and alpha='0.4'.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0.
Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = np.exp(x)
plt.plot(x, y)
plt.text(-1.0, 4.0, 'y=exp(x)', fontdict=dict(fontsize=15, fontweight='bold'), bbox=dict(facecolor='red', alpha=0.4, edgecolor='black'))
plt.show()
p5.js | createVector() function

05 Oct, 2021
The createVector() function in p5.js is used to create the new p5 vector which contains both magnitude and direction. This provides a two or three-dimensional vector, specifically a geometric vector.
Syntax: 
createVector([x], [y], [z])
Parameters: This function accepts three parameters as mentioned above and described below:  
x: This parameter stores the x component of the vector.
y: This parameter stores the y component of the vector.
z: This parameter stores the z component of the vector.
Below programs illustrate the createVector() function in p5.js:
Example 1: This example uses createVector() function to draw a line.  
Javascript
function setup() {     // Create a Canvas    createCanvas(500, 550);} function draw() {        // Vector initialisation    // using createVector    t1 = createVector(10, 40);    t2 = createVector(411, 500);        // Set background color     background(200);        // Set stroke weight    strokeWeight(2);        // line using vector    line(t1.x, t1.y, t2.x, t2.y);        translate(12, 54);      line(t1.x, t1.y, t2.x, t2.y);}
Output: 
Example 2: This example uses createVector() function to draw a circle. 
Javascript
function setup() {     // Create a Canvas    createCanvas(500, 550);}  function draw() {        // Vector initialisation    // using createVector    t1 = createVector(10, 40);    t2 = createVector(41, 50);        // Set background color     background(200);        // Set stroke weight    strokeWeight(2);        // Fill yellow    fill('yellow');        // ellipse using vector    ellipse(t1.x*millis() / 1000 * 20,            t1.y, t2.x+100, t2.y+100);}
Output: 
Reference: https://p5js.org/reference/#/p5/createVector 
anikaseth98
ruhelaa48
JavaScript-p5.js
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
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
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 ?
Python | Pandas Series.dt.day

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.day attribute return a numpy array containing the day of the datetime in the underlying data of the given series object.
Syntax: Series.dt.day
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object.
# return the dayresult = sr.dt.day  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                        periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object.
# return the dayresult = sr.dt.day  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
localtime() function in C++

01 Oct, 2018
The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time.
Syntax:
tm* localtime(const time_t* time_ptr);
Parameter: This function accepts a parameter time_ptr which represents the pointer to time_t object.
Return Value: This function returns a pointer to a tm object on success, Otherwise it returns NullPointerException.
Below program illustrate the localtime() function in C++:
Example:-
// c++ program to demonstrate// example of localtime() function.  #include <bits/stdc++.h>using namespace std;  int main(){    time_t time_ptr;    time_ptr = time(NULL);      // Get the localtime    tm* tm_local = localtime(&time_ptr);      cout << "Current local time is = "         << tm_local->tm_hour << ":"         << tm_local->tm_min << ":"         << tm_local->tm_sec;      return 0;}
Current local time is = 10:8:10

CPP-Functions
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
Substring in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Templates in C++ with Examples
Operator Overloading in C++
Multidimensional Arrays in C / C++
How to calculate number of days between two dates in R ?

16 Jul, 2021
In this article, we will discuss how to Find the number of days between two dates in the R programming language. 
Example:
Input:
 Date_1 = 2020/03/21
 Date_2 = 2020/03/22
Output: 1
Explanation: In Date_1 and Date_2 have only one difference in day.So output will be 1.
Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. To get the number of days length() function is employed with seq() as an argument.
Syntax: length(seq(from=date_1, to=date_2, by=’day’)) -1
Parameter:
seq is function generates a sequence of numbers.
from is starting date.
to is ending date.
by is step, increment.
Example 1:
R
# creating date_1 variable# and storing date in it.date_1<-as.Date("2020-10-10") # creating date_2 variable# and storing date in it.date_2<-as.Date("2020-10-11").a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of# a and we are subtracting 1 because# we dont need to include current day.length(a)-1
Output:
1
Example 2:
R
# creating date_1 variable# and storing date in it.date_1<-as.Date("2020-01-10") # creating date_2 variable# and storing date in it.date_2<-as.Date("2020-02-20") a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of a# and we are subtracting 1 because we# dont need to include current day.length(a)-1
Output:
41
singghakshay
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
PHP | exit( ) Function

01 Aug, 2021
The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script.The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.The message to be displayed is passed as a parameter to the exit() function and it terminates the script and displays the message.The exit() function is an alias of the die() function.
Syntax:
exit(message)
Parameters Used:The exit() function in PHP accepts one parameter.
message : It is a mandatory parameter which specifies the message or status number to write before exiting the script.
message : It is a mandatory parameter which specifies the message or status number to write before exiting the script.
Return Value:
It does not return any value.
Errors And Exceptions
exit() is a language construct and it can be called without parentheses if no status is passed.If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed.Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP.
exit() is a language construct and it can be called without parentheses if no status is passed.
If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed.
Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP.
Below programs illustrate the exit() function:
Program 1:
<?php$link = "https://www.geeksforgeeks.org";  // opening a linkfopen($link, "r")  //using exit() to display message and terminate scriptor exit("Unable to establish a connection to $link");?>
Output:
Unable to establish a connection to https://www.geeksforgeeks.org

Program 2:
<?php//declaring variables$a=5;$b=5.0;  if($a==$b) {    //terminating script with a message using exit()    exit('variables are equal'); }else {   //terminating script with a message using exit()    exit('variables are not equal');  }?>
Output:
variables are equal

Reference :http://php.net/manual/en/function.exit.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
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 ?
Ruby | Array reverse() function

06 Dec, 2019
Array#reverse() : reverse() is a Array class method which returns a new array containing self’s elements in reverse order.
Syntax: Array.reverse()
Parameter: Array
Return: a new array containing self’s elements in reverse order.
Example #1 :
# Ruby code for reverse() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 50, 6]  # reverse method exampleputs "reverse() method form : #{a.reverse()}\n\n"  puts "reverse() method form : #{b.reverse()}\n\n"  puts "reverse() method form : #{c.reverse()}\n\n"
Output :
reverse() method form : [6, 5, nil, 33, 22, 18]

reverse() method form : [9, 88, 1, 1, 4, 1]

reverse() method form : [6, 50, 22, 18]


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

reverse() method form : ["dog", nil, "cow"]

reverse() method form : [nil, "cat"]


Ruby Array-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 | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Data Types
Ruby | Enumerator each_with_index function
Ruby | Hash delete() function
Ruby | Case Statement
Ruby | String gsub! Method
Python | Decimal to binary list conversion

26 Feb, 2019
The conversion of a binary list to a decimal number has been dealt in a previous article. This article aims at presenting certain shorthand to do the opposite, i.e binary to decimal conversion. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + format()In this method, the conversion of the decimal to binary is handled by the format function. The logic of conversion to the list is done by the list comprehension function.
# Python3 code to demonstrate # decimal to binary number conversion# using format() + list comprehension  # initializing number test_num = 38  # printing original numberprint ("The original number is : " + str(test_num))  # using format() + list comprehension# decimal to binary number conversion res = [int(i) for i in list('{0:0b}'.format(test_num))]  # printing result print ("The converted binary list is : " +  str(res))
The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]

 Method #2 : Using bin() + list comprehensionThe inbuilt function bin performs the function of conversion to binary and the list comprehension handles the logic to convert the binary number to the list.
# Python3 code to demonstrate # decimal to binary number conversion# using bin() + list comprehension  # initializing number test_num = 38  # printing original numberprint ("The original number is : " + str(test_num))  # using bin() + list comprehension# decimal to binary number conversion res = [int(i) for i in bin(test_num)[2:]]  # printing result print ("The converted binary list is : " +  str(res))
The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]

Python
Python Programs
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 ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How to Customize Linux Terminal Using powerlevel10k?

01 Jun, 2021
Sometimes we get bored with the normal Linux Terminal and feel like if we can customize the same, so we can use powerlevel10k for that. It is a theme for ZSH. It changes normal shell commands to colorful commands. To install powerlevel10k we need to install Oh My Zsh, both are open-source in GitHub. We can also use nerd font to make the powerlevel10k theme font more beautiful.
Install Oh My Zsh
To install Oh My Zsh open terminal and run
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
 If this curl installation method shows any error use wget method 
sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
Install powerlevel10k
powerlevel10k theme installation becomes easy if oh my zsh is installation successful. Just run these two commands.
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
install powerlevel10k
In another way, we can install it directly from GitHub and set it up 
git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ~/powerlevel10k
echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc
Install Nerd Font For powerlevel10k & Setup It
powerlevel10k works well with nerd font they also recommend using nerd font, and it is easy to install the font in Linux. To install nerd font go to the official nerd font GitHub page https://github.com/ryanoasis/nerd-fonts and download font example Hack Nerd Font, JetBrains Mono Nerd Font, Ubuntu Nerd Font, etc.
Install “Hack Nerd  Font Regular”
To set up it nerd font in terminal open terminal preferences and change the custom font to Hack Nerd Font Regular
change custom font to Hack Nerd Font RegularSetup
Setup powerlevel10k Theme
After update powerlevel9k to powerlevel10k, it becomes easy to set up a theme. Do just type “p10k configure” in your terminal after choose options how you want to give looks to your terminal
powerlevel10k setup process
Note: If the installation fails then just restart your OS again try to install powerlevel10k
anindra
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
How to Install Docker-CE in Redhat 8?

28 May, 2021
Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all the parts it needs, such as libraries and other dependencies, and deploy it as one package.
Step 1: Open your Redhat 8 terminal. Your terminal would look like this. Also, make sure you are login as root.
Step 2: Run the following commands.
cd /etc/yum.repos.d/
ls
Now you will see some files with .repo extension, as shown below.
Step 3: Now we are going to create our own file docker.repo follow the below commands.
cat > docker.repo
[docker]
baseurl=https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck=0
  In the next line press CTRL+D to stop appending data. 
 If you want to check whether the file is created or not, run “ls” command and check for docker.repo, and if u want to see the content of the file run, “cat docker.repo“.
Step 4: Now we are going to install docker so make sure you are connected to internet (try pinging in google). 
And run the following command. When asked for confirmation press ‘y‘.
yum install docker-ce --nobest
 Wait for the process to complete. When the process completes docker is installed in your system. 
Step 5: To check you can run the following command-
rpm -q docker-ce
or 
systemctl start docker
docker version
At this stage, you have successfully installed Docker-CE in your Redhat 8 system.
m27sanjay
linux
Shell
How To
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Packages

27 Dec, 2021
We usually organize our files in different folders and subfolders based on some criteria, so that they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we can even subcategorize according to the genre of the game or something like this. The same analogy is followed by the Python package. 
A Python module may contain several classes, functions, variables, etc. whereas a Python package can contains several module. In simpler terms a package is folder that contains various modules as files.
Let’s create a package named mypckg that will contain two modules mod1 and mod2. To create this module follow the below steps – 
Create a folder named mypckg.
Inside this folder create an empty Python file i.e. __init__.py
Then create two modules mod1 and mod2 in this folder.
Python3
def gfg():    print("Welcome to GFG")
Python3
def sum(a, b):    return a+b
The hierarchy of the our package looks like this – 
mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py
__init__.py helps the Python interpreter to recognise the folder as package. It also specifies the resources to be imported from the modules. If the __init__.py is empty this means that all the functions of the modules will be imported. We can also specify the functions from each module to be made available.
For example, we can also create the __init__.py file for the above module as – 
Python3
from .mod1 import gfgfrom .mod2 import sum
This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be imported.
We can import these modules using the from...import statement and the dot(.) operator. 
Syntax:
import package_name.module_name
We will import the modules from the above created package and will use the functions inside those modules.
Python3
from mypckg import mod1from mypckg import mod2 mod1.gfg()res = mod2.sum(1, 2)print(res)
Output:
Welcome to GFG
3
We can also import the specific function also using the same syntax.
Python3
from mypckg.mod1 import gfgfrom mypckg.mod2 import sum gfg()res = sum(1, 2)print(res)
Output:
Welcome to GFG
3
surinderdawra388
sweetyty
rajeev0719singh
kk773572498
Python
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Is it possible to use this keyword in static context in java?

A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference).
Whereas "this" in Java acts as a reference to the current object. But static contexts(methods and blocks) doesn't have any instance they belong to the class.
In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods.
Therefore, you cannot use this keyword from a static method.
In the following Java program, the class ThisExample contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using "this".
 Live Demo
public class ThisExample {
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void display() {
      System.out.println("name: "+this.getName());
   }
   public static void main(String args[]) {
      this.display();
   }
}
On compiling, this program gives you an error as shown below −
ThisExample.java:17: error: non-static variable this cannot be referenced from a static context
      this.display();
      ^
1 error
Difference between 3NF and BCNF in DBMS

15 Jan, 2021
1. Third Normal Form (3NF) :A relation is said to be in Third Normal Form (3NF), if it is in 2NF and when no non key attribute is transitively dependent on the primary key i.e., there is no transitive dependency. Also it should satisfy one of the below given conditions. For the function dependency C->D:
C should be a super key and,
D should be a prime attribute i.e, D should be a part of the candidate key.
3NF is used to reduce data duplication and to attain data integrity.
Example:For the relation R(L, M, N, O, P) with functional dependencies as {L->M, MN->P, PO->L}:
The candidate keys will be : {LNO, MNO, NOP}
      as the closure of LNO = {L, M, N, O, P} 
             closure of MNO = {L, M, N, O, P}
             closure of NOP = {L, M, N, O, P}
This relation is in 3NF as it is already in 2NF and has no transitive dependency. Also there is no non prime attribute that is deriving a non prime attribute.
2. Boyce-Codd Normal Form (BCNF) :BCNF stands for Boyce-Codd normal form and was made by R.F Boyce and E.F Codd in 1974.A functional dependency is said to be in BCNF if these properties hold:
It should already be in 3NF.
For a functional dependency say P->Q, P should be a super key.
BCNF is an extension of 3NF and it is has more strict rules than 3NF. Also, it is considered to be more stronger than 3NF.
Example:for the relation R(A, B, C, D) with functional dependencies as {A->B, A->C, C->D, C->A}:
The candidate keys will be : {A, C}
      as the closure of A = {A, B, C, D} 
             closure of C = {A, B, C, D} 
This relation is in BCNF as it is already in 3Nf (there is no prime attribute deriving no prime attribute) and on the left hand side of the functional dependency there is a candidate key.
Difference between 3NF and BCNF :
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Introduction of DBMS (Database Management System) | Set 1
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL Trigger | Student Database
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
What does getattr() function do in Python?

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
The syntax of getattr() method is −
getattr(object, name[, default])
The getattr() method can take multiple parameters −
The getattr() method returns −
value of the named attribute of the given object
default, if no named attribute is found
AttributeError exception, if named attribute is not found and default is not defined
class Male:
    age = 21
    name = "Abel"
x = Male()
print('The age is:', getattr(x, "age"))
print('The age is:', x.age)
This gives the output
('The age is:', 21)
('The age is:', 21)
Python | Removing strings from tuple - GeeksforGeeks

17 Apr, 2019
Sometimes we can come across the issue in which we receive data in form of tuple and we just want the numbers from it and wish to erase all the strings from them. This has a useful utility in Web-Development and Machine Learning as well. Let’s discuss certain ways in which this particular task can be achieved.
Method #1 : Using list comprehension + type()
The combination of above 2 functions can be used to solve this particular problem. The list comprehension does the task of reconstruction of the modified list and type function helps us to filter the strings.
# Python3 code to demonstrate# Remove string from tuples# using list comprehension + type()  # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + type()# Remove string from tuplesres = [tuple([j for j in i if type(j) != str])                           for i in test_list]  # print resultprint("The list after string removal is : " + str(res))
The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
The list after string removal is : [(1, 2), (4, ), (45, )]

 
Method #2 : Using list comprehension + isinstance()
This is almost a similar method to perform this particular task but the change here is just to use the isinstance function to check for the string data type, and rest of the formulations remains mostly similar.
# Python3 code to demonstrate# Remove string from tuples# using list comprehension + isinstance()  # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + isinstance()# Remove string from tuplesres = [tuple(j for j in i if not isinstance(j, str))                                 for i in test_list]  # print resultprint("The list after string removal is : " + str(res))
The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
The list after string removal is : [(1, 2), (4, ), (45, )]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Tryit Editor v3.7

Tryit: Display the nabla symbol